StampItem.1.js 15.9 KB

import { useState } from 'react';
import {post,get} from 'axios'
import {Dimensions, View,Text,Image,TextInput,StyleSheet,TouchableOpacity,TouchableHighlight,Alert} from 'react-native'
import * as React from 'react'
import moment from 'moment'

import Modal from 'react-native-modal';
import Options from '../assets/Options.svg'
import Available from '../assets/available.svg'
import {SERVER} from '../common/servername'
import QRCode from 'react-native-qrcode-svg';
import {Share as Share_} from 'react-native'

export default ({ item,myStore, height,update, handleHeight,index,setItemNum,store,user }) => {
    const [stamp,setStamp] = React.useState(["","","","","","","","","","","",""])
    const [tempHeight,setTempHeight] = React.useState(0)
    const [num,setNum] = React.useState("")
    const [isMyStore,SetisMyStore] = React.useState(false)
    
    const [Item,setItem] = React.useState([{}])
    const [isModalVisible,setIsModalVisible] = React.useState(false)
    const [isModalVisible_Present,setIsModalVisible_Present] = React.useState(false)
    const [isModalVisible_Use,setIsModalVisible_Use] = React.useState(false)
    const [storeData,setStoreData] = React.useState([])
    const [maxNum, setMaxNum] = React.useState([])
    const [indStampNum,setIndStampNum] = useState([])
    const [useNum,setUseNum] = React.useState(0)
    React.useEffect(() => {
        if(index==2) {
            SetisMyStore(myStore.map((e,i) => e.id).indexOf(store.id)<0?false:true)
            handleHeight(tempHeight)
        }
    },[index,tempHeight])
    const toggleModal = () => {
        if(isModalVisible == true) {
           setIsModalVisible(false)
        }
        else {
            setIsModalVisible(true)
        }
    };
    
    const toggleModal_Present= () => {
        if(isModalVisible_Present == true) {
           setIsModalVisible_Present(false)
        }
        else {
            setIsModalVisible_Present(true)
        }
    };
    const toggleModal_Use= () => {
        if(isModalVisible_Use == true) {
           setIsModalVisible_Use(false)
        }
        else {
            setIsModalVisible_Use(true)
        }
    };
    React.useEffect(() => {
        if(!item[0]) {
            if(myStore.map((e,i) => e.id).indexOf(store.id)>=0) {
                get(`http://${SERVER}/stamps/${store.id}`).then(res => {
                    setItem(res.data.data)
                    setItemNum(res.data.data.map((e,i) =>e.totalCount-e.totalUsedCount ))
                    if(res.data.data.length==0) setItemNum(0)
                    setIndStampNum([...Array(res.data.data.length)].map((el,j) => res.data.data[j].totalCount-res.data.data[j].totalUsedCount))
                    get(`http://${SERVER}/stamps/${store.id}`).then(res => {
                        if(res.data.success) {
                            setStoreData(res.data.data)
                            setMaxNum([...Array(res.data.data.length)].map(() => 0))
                        }
                    })
                
                })
            }
            else {
                get(`http://${SERVER}/stamps/${store.id}`,{UserId:user.id?user.id:7,StoreId:store.id}).then(e => {
                    setItem(e.data.data)
                    setItemNum(e.data.data.map((e,i) =>e.totalCount-e.totalUsedCount ))
                    console.log('read',e.data.data)
                    if(e.data.data.length==0) setItemNum(0)
                    setIndStampNum([...Array(e.data.data.length)].map((el,j) => e.data.data[j].totalCount-e.data.data[j].totalUsedCount))
                    get(`http://${SERVER}/stamps/${store.id}`).then(res => {
                        if(res.data.success) {
                            setStoreData(res.data.data)
                            setMaxNum([...Array(res.data.data.length)].map(() => 0))
                        }
                    })
            
                })
            }
        }
        else {
            get(`http://${SERVER}/stamps/${store.id}`).then(res => {
                if(res.data.success) {
                    setStoreData(res.data.data)
                    setMaxNum([...Array(res.data.data.length)].map(() => 0))
                }
            })
            setItem(item)
        }
    },[])
    
    React.useEffect(() => {
        if(!item[0]) {
            if(myStore.map((e,i) => e.id).indexOf(store.id)>=0) {
                get(`http://${SERVER}/stamps/${store.id}`).then(res => {
                    setItem(res.data.data)
                    setItemNum(res.data.data.map((e,i) =>e.totalCount-e.totalUsedCount ))
                    if(res.data.data.length==0) setItemNum(0)
                    setIndStampNum([...Array(res.data.data.length)].map((el,j) => res.data.data[j].totalCount-res.data.data[j].totalUsedCount))
                    get(`http://${SERVER}/stamps/${store.id}`).then(res => {
                        if(res.data.success) {
                            setStoreData(res.data.data)
                            setMaxNum([...Array(res.data.data.length)].map(() => 0))
                        }
                    })
                
                })
            }
            else {
                post(`http://${SERVER}/stamps/read`,{UserId:user.id?user.id:7,StoreId:store.id}).then(e => {
                    setItem(e.data.data)
                    setItemNum(e.data.data.map((e,i) =>e.totalCount-e.totalUsedCount ))
                    console.log('read',e.data.data)
                    if(e.data.data.length==0) setItemNum(0)
                    setIndStampNum([...Array(e.data.data.length)].map((el,j) => e.data.data[j].totalCount-e.data.data[j].totalUsedCount))
                    get(`http://${SERVER}/stamps/${store.id}`).then(res => {
                        if(res.data.success) {
                            setStoreData(res.data.data)
                            setMaxNum([...Array(res.data.data.length)].map(() => 0))
                        }
                    })
            
                })
            }
        }
        else {
            get(`http://${SERVER}/stamps/${store.id}`).then(res => {
                if(res.data.success) {
                    setStoreData(res.data.data)
                    setMaxNum([...Array(res.data.data.length)].map(() => 0))
                }
            })
            setItem(item)
        }
    },[update])
    React.useEffect(() => {
        storeData.forEach((e,i,arr) => {
            e.StampConditions.map((el,j,arr1) => {
                if(maxNum[i] < el.conditionCount) {
                    const temp = (el.conditionCount/4).toString().split(".")[1]
                    setMaxNum([
                        ...maxNum.slice(0,i),
                        el.conditionCount + (temp=="25"?3:temp=="5"?2:temp=="75"?1:0),
                        ...maxNum.slice(i+1,maxNum.length)
                    ])
                }
            }) 
        })
    },[maxNum])
    const onShare = async (e) => {
        try {
          const result = await Share_.share({
            message:
              `상가톡에서 스탬프를 이용해주세요!\n[${user.nickname}]님 으로부터 소중한 스탬프가 도착했습니다!\n\n아래 링크를 클릭하여 스탬프를 받아주세요!\n[https://sangatalk.page.link/?link=https://sanggatalk.io/app/stamp?params=${store.id},${e.id},${num}&apn=com.sangatalk]\n\n상가톡 서비스 문의는 아래 링크를 참고해주세요 ^~^\n상가톡 채널 바로가기 : [ http://sanggatalk.io ]\n상가톡 고객센터 바로가기 : [ http://sanggatalk.io/ClilentCenter ]\n`,

          }).then(({action,activityType}) => {
            if (action === Share_.sharedAction) {
              if (result.activityType) {
                // shared with activity type of result.activityType
              } else {
                // shared
              }
            } else if (result.action === Share_.dismissedAction) {
              // dismissed
            }
              
          })
        } catch (error) {
          alert(error.message);
        }
      };
    return (
        <View onLayout={(e) => {
            setTempHeight(e.nativeEvent.layout.height)}}  style={{paddingLeft:16,paddingRight:16,paddingBottom:24,backgroundColor:"white"}}>
            {storeData.map((e,j) => {
                return (
                    <View>
                    <View>
                    {isMyStore?<TouchableOpacity onPress={() => toggleModal_Present(true)} style={{position:"absolute",right:16,top:16,padding:5.5,borderWidth:1,borderColor:"#FFD63A"}}>
            <Text style={{color:"#FFD63A",fontSize:14,fontWeight:"bold",lineHeight:16}}>
                 
            </Text>
            <Text style={{color:"#FFD63A",fontSize:14,fontWeight:"bold",lineHeight:16}}>
                 
            </Text>
        </TouchableOpacity>:undefined}
        <View style={{paddingTop:13,paddingBottom:11.5}}>
            <View style={{flexDirection:"row"}}>
                <Text style={{fontSize:15}}>
                    {store?store.name:Item[0]&&Item[0].storeName}
                    
                </Text>
                <TouchableOpacity onPress={() => toggleModal()} style={{marginLeft:"auto",marginRight:80}}>
                    <Text style={{color:"#979292",fontSize:11}}>사용가능 { Math.floor((indStampNum[j]+1) / 10)}</Text>
                </TouchableOpacity>
            </View>
            <View style={{width:"50%"}}>
                    {e.StampConditions.map((el,i,arr) => {
                        return (
                            <Text style={[{color:"#615F5F",fontSize:11},i==0?{marginTop:9}:i==arr.length-1?{marginBottom:15}:{}]}>
                                
                                {"스탬프 "+ el.conditionCount + "개 모으면 " + el.reward}
                            </Text>)
                    })}
                <Text style={{color:"#615F5F",fontSize:11,marginTop:9,marginBottom:15}}>
                    
                </Text>
            </View>
            
        </View>
        <View style={{flexWrap:"wrap",flexDirection:"row",justifyContent:"space-between"}}>
            {[...Array(maxNum[j])].map((el,i) => 
            <View>
            <View style={[indStampNum[j]> maxNum-i-1? {width:60,height:60,borderColor:"#615F5F",
            borderWidth:1,borderRadius:100,marginRight:14,marginLeft:14,
            justifyContent:"center",marginBottom:18,backgroundColor:"#FFD63A"}:{width:60,height:60,borderColor:"#615F5F",
            borderWidth:1,borderRadius:100,marginRight:14,marginLeft:14,
            justifyContent:"center",marginBottom:18},indStampNum[j] >= e.StampConditions[j].conditionCount && maxNum[j]-i === e.StampConditions[j].conditionCount ? {backgroundColor:"white"}:{}
            ]}>
            {indStampNum[j] >= e.StampConditions[j].conditionCount && maxNum[j]-i === e.StampConditions[j].conditionCount ? <Available onPress={() => {toggleModal()
            setUseNum(maxNum[j]-i)}} style={{marginLeft:-3}} width={65}height={65}/>
            :
                <Text style={ [{textAlign:"center",fontSize:28,fontWeight:"bold",color:"#615F5F"},
                    indStampNum>maxNum[j]-i-1?{color:"white"}:{},e.StampConditions.map((e,i) => e.conditionCount).indexOf(maxNum[j]-i)>=0?{fontSize:14} :{}]}>

                        {e.StampConditions.map((e,i) => e.conditionCount).indexOf(maxNum[j]-i)>=0? "사용\n가능":maxNum[j]-i}
                </Text>
                }
            </View>
            {Item[maxNum[j]-i-1]?<View style={{margin:"auto",position:"absolute",bottom:3,justifyContent:"center",width:"100%"}}>
                <Text style={{fontSize:12,color:"#979292",textAlign:"center",justifyContent:"center"}}>
                    {moment(Item[maxNum[j]-i-1].createdAt).format("MM.DD")}
                </Text>
            </View>:undefined}
            </View>)}
        </View>


      <Modal  onBackdropPress={() => toggleModal_Present()} isVisible={isModalVisible_Present}>
        <View>
            
        <View style={{ width:"90%",backgroundColor:"white",alignSelf:"center",paddingLeft:24,paddingTop:24,paddingBottom:24,paddingRight:24}}>
            <Text style={{fontSize:16,color:"#615F5F",fontWeight:"bold",textAlign:"center",marginBottom:3}}>
                선물할 스탬프 수량
            </Text>
            <View style={{marginTop:25,marginBottom:24,flexDirection:"row",marginLeft:"auto",marginRight:"auto"}}>
                <TextInput value={num} onChangeText={(e) => {
                        setNum(e)   
                    }} keyboardType="number-pad" style={{textAlign:"center",width:"33%",paddingTop:9,paddingBottom:9,fontSize:16,fontWeight:"bold",borderColor:"#FFD63A",borderWidth:1,}}/>
                <Text style={{alignSelf:"center",marginLeft:16,color:"#615F5F",fontSize:16,fontWeight:"bold"}}>
                    
                </Text>
            </View>
        </View>
        <View style={{flexDirection:"row",alignSelf:"center"}}>
            <TouchableOpacity onPress={() => {toggleModal_Present()
            onShare(e)}} style={{paddingTop:12,paddingBottom:15,backgroundColor:"#FFD63A",width:"45%",alignSelf:"center"}}>
                <Text style={{textAlign:"center",color:"black",fontSize:14}}>
                    선물하기
                </Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={() => toggleModal_Present()} style={{paddingTop:12,paddingBottom:15,backgroundColor:"white",width:"45%",alignSelf:"center"}}>
                <Text style={{textAlign:"center",color:"black",fontSize:14}}>
                    취소
                </Text>
            </TouchableOpacity>
        </View>
        </View>
      </Modal>
  <Modal onBackButtonPress={() => setIsModalVisible(false)} onBackdropPress={() => toggleModal()} isVisible={isModalVisible}>
    <View>
    
    <View style={{ width:"80%",backgroundColor:"white",alignSelf:"center",paddingLeft:24,paddingTop:24,paddingBottom:24,paddingRight:24}}>
        <Text style={{fontSize:16,color:"#615F5F",fontWeight:"bold",textAlign:"center",marginBottom:25}}>
                 스탬프를 사용하시겠습니까?
            </Text>
            <Text style={{fontSize:15,color:"black",textAlign:"center"}}>
                {store.name}
            </Text>
            <Text style={{fontSize:15,color:"#615F5F",textAlign:"center",marginTop:9}}>
                {e.useCondition}
            </Text>
        </View>
    </View>
    
    <View style={{flexDirection:"row",alignSelf:"center"}}>
        <TouchableOpacity onPress={() => {toggleModal()
        toggleModal_Use()}} style={{paddingTop:12,paddingBottom:15,backgroundColor:"#FFD63A",width:"40%",alignSelf:"center"}}>
            <Text style={{textAlign:"center",color:"black",fontSize:14}}>
                사용하기
            </Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={() => toggleModal()} style={{paddingTop:12,paddingBottom:15,backgroundColor:"white",width:"40%",alignSelf:"center"}}>
            <Text style={{textAlign:"center",color:"black",fontSize:14}}>
                취소
            </Text>
        </TouchableOpacity>
    </View>
  </Modal>

  <Modal onBackButtonPress={() => toggleModal_Use()} onBackdropPress={() => toggleModal_Use()} isVisible={isModalVisible_Use}>
    <View>
    
    <View style={{ width:"80%",backgroundColor:"white",alignSelf:"center",paddingLeft:24,paddingTop:24,paddingBottom:24,paddingRight:24,justifyContent:"center"}}>
        <Text style={{fontSize:16,color:"#615F5F",fontWeight:"bold",textAlign:"center",marginBottom:25}}>
            QR코드를 점원에게 제시해주세요.
        </Text>
            <View style={{alignSelf:"center",marginLeft:"auto",marginRight:"auto"}} >
                <QRCode size={120} value={JSON.stringify({url:`http://${SERVER}/stamps/use`,StoreId:`${store.id}`,StampId:`${e.id}`,UserId:`${user.id}`,count:`${useNum}`})}/>
            </View>
        </View>
    </View>
  </Modal>
                </View>
                        
                    </View>
                )
            })}


            
        </View>
    )
}

const style = StyleSheet.create({
    text:{
        color:"#707070",
        fontSize:11,
        fontWeight:"900"
    }
})