import React, { useState, useEffect, useCallback } from 'react'
import { View, Text, Image, Icon } from '@tarojs/components'
import { AtInput, AtCurtain , AtIcon } from 'taro-ui'

import Taro from '@tarojs/taro'

import './index.scss'

import NavBar from '@/components/NavBar'

import type { modalProps, authQrcodeType } from './data'

import { authQrcode } from '../../api/qrcode'
import Tip from '@/utils/tip'

const Modal: React.FC<modalProps> = ({visable, closeModal, errorCode}) => {

    const RenderImage = (): React.ReactNode => {
        switch (errorCode) {
            case 1:
                return (
                    <View>
                        <Image
                          style={{width: 143, height: 103}}
                          src={require('../../assets/ScanQrcode/hava-already.png')}
                        />
                        <View >
                            <View className='label'>条形码已经被使用</View>
                            <View className='desc' >您可在查询记录里查看~</View>
                        </View>
                    </View>
                )
        
            case 0:
                return (
                    <View>
                        <Image
                          style={{width: 143, height: 103}}
                          src={require('../../assets/ScanQrcode/query-faild.png')}
                        />
                        <View>
                            <View className='label'>商品查询失败</View>
                            <View className='desc' >请填写正确的数字条形码~</View>
                        </View>
                    </View>
                )
        }
    }


    return (
        <AtCurtain
          isOpened={visable}
          onClose={closeModal}
        >
        <View className='card'>
            { RenderImage() }
        </View>
        
      </AtCurtain>
    )
}


const ScanQrcode: React.FC = () => {

    const [ visable, setVisable ] = useState<boolean>(false)

    const [ code, setCode] = useState<string>('')

    const [ errorCode, setErrorCode ]  = useState<-1 | 0 | 1>(0)

    const [ qrcode, setQrcode ] = useState<string>('')

    // 输入二维码
    const onChange = (e: string): void => setCode(e)

    // 打开弹窗
    const openModal = (): void => setVisable(true)

    // 关闭
    const closeModal = (): void => setVisable(false)
 
    // 打开摄像头扫码
    const scanQrcode = (): void => {
        setCode('')
        Taro.scanCode({
            success: res => {
                console.log(res);
                const { result } = res
                AuthQrcode(result)
            },
            fail: () => {
                // Tip.toast('图片不是条形码或者二维码',  'none', 3000 )
            }
        })
    } 

    // 查询二维码
    const AuthQrcode = useCallback(async (params: string = ''): Promise<void> => {
        console.log(params, 'params');
        
        if (params.length === 0) return
        Taro.setStorageSync('goodsTypePdfId',  params || code)
        
        Tip.loading('查询中')

        const data = await authQrcode( params || code)

        Tip.loaded()

        const {errorCode: ErrorCode, goodsParentType, isNewCode } = data as unknown as authQrcodeType
        setErrorCode(ErrorCode)

        if (isNewCode === 0 ) {  // 旧码

            Taro.navigateTo({
                 url: '/pages/ShopCate/index'
            });

            return 
        } 

        if (errorCode !== -1) {
            openModal()
        }
        
    }, [code, errorCode])


    // 去查询详情页
    const goPage = (): void => {
        Taro.navigateTo({
             url: '/pages/QueryRecord/index'
        });
    }

    return (
        <View className='ScanQrcode'>
            <NavBar
              icon={<AtIcon value='chevron-left' size='30rpx' color='#000'  />}
              title='' 
              background='#fff'
              fixed={false}
            />
            <View className='header'>
                <Text className='left'>输入/扫描数字条形码 </Text>
                <Text className='right' onClick={goPage}>查询记录</Text>
            </View>
            <View className='Atinput-box'>
                <AtInput 
                  name='qrcode'
                  className='Atinput'
                  onChange={onChange}
                  value={code}
                  placeholder='请输入数字条形码'
                  placeholderStyle='placeholder-class'
                />
                <Image className='scan-icon' onClick={scanQrcode} src={require('../../assets/ScanQrcode/scan-icon.png')}></Image>
            </View>
            <View className='query-btn' onClick={() => AuthQrcode(code)}>立即查询</View>

            {/* 验证方法 */}
            <View className='verify'>
                <View className='header'>  
                    <View className='flag'></View>
                    <Text>验证方法</Text>
                </View>
                <View className='content'>
                    <Image
                      mode='aspectFill'
                      className='shop' 
                      src={require('../../assets/ScanQrcode/shop.png')}
                    />
                    <View className='text'>
                        通过手机扫一扫盒子
                        <Text>左侧条形码</Text>
                        或者输入
                        <Text>条形码下方数字</Text>
                        ，即 可进行真伪验证
                    </View>
                </View>
            </View>
            <Modal  visable={visable} closeModal={closeModal} errorCode={errorCode} />
        </View>
    )
}
export default ScanQrcode