import React, { useEffect, useState } from 'react'

import { View, Image, Text, Input } from '@tarojs/components'
import { AtInput, AtIcon, AtActionSheet, AtActionSheetItem   , AtToast } from 'taro-ui'
import Taro from '@tarojs/taro';

import { baseUrl } from '@/service/config'

import { queryCertificate, queryCertificateFile , queryInfoByCompanyOrPerson} from '../../api/auth'

import Tip from '@/utils/tip';

import dayjs  from 'dayjs'



import './index.scss'


const SheetItem = [
    {
        typeId: 2,
        label: '逻辑狗思维体验Plus'
    },
    {
        typeId: 3,
        label: '逻辑狗思维体验Home'
    },
    {
        typeId: 4,
        label: '逻辑狗思维体验Town'
    },
]

const AuthOpra: React.FC = (props) => {

    const [type, setType] = useState<number>(0)
    
    const [label, setLabel] = useState<string>('')

    // 弹窗
    const [visible, setVisible] = useState<boolean>(false)
    
    // 编号前缀
    const [ NoPrefix, setNoPrefix ] = useState<string>('')
    
    const [ isOpened, setIsOpened ] = useState<boolean>(false)



    useEffect( () => {
        
        setType(Number(Taro.getCurrentInstance().router?.params.type))
        setNoPrefix(Taro.getCurrentInstance().router?.params.No as string)
    
    }, []) 

    const onChange = (e) => {
        console.log(e, 'e');
        
        setLabel(e.detail.value)
    }

    // 查询证书
    const QueryCertificate = async ( )  => {
        const $par = {
            query: label,
            typeId: type
        }
        if (label.length === 0) return
         
        const data = await queryInfoByCompanyOrPerson($par)

        if (data === null || !data.hasOwnProperty('startTime')) {
            // Tip.toast(`暂未查询到该公司品牌认证信息\r\n请联系相关工作人员`, 'none')
            setIsOpened(true)
            const timeID = setTimeout(() => {
                setIsOpened(false)
                clearTimeout(timeID)
            }, 2500);
            return
        }

        const $records = {
            ...data,
            startTime: dayjs(data.startTime).format('YYYY年MM月DD日'),
            endTime: dayjs(data.endTime).format('YYYY年MM月DD日'),
            No: NoPrefix + dayjs(data.startTime).format('YYYYMMDD') + '001'
        }

        goAuthResultPage($records)

    }

    // 上传证书url
    const QueryCertificateFile = async (fileUrl: string, typeId: number) => {

        const data = await queryCertificateFile({fileUrl: String(fileUrl), typeId})
        console.log(data);

        goAuthResultPage(data)
        
    }

    // 去证书结果页面
    const goAuthResultPage = (data?) => {
        const encode = encodeURIComponent( JSON.stringify(data) )
        Taro.navigateTo({
            url: `/pages/AuthResult/index?result=${encode}`
        })
    }

    // 调起微信的拍照或者相册选择证书
    const dispatchWxCamera = () => {
        Taro.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: res => {
                const tempFilePaths = res.tempFilePaths
                Taro.uploadFile({
                    url:  baseUrl + '/verify/certificate/uploadFileTemp',
                    filePath: tempFilePaths[0],
                    name: 'file',
                    header: {
                        token: Taro.getStorageSync('token')
                    },
                    formData: {
                        'user': 'test'
                    },
                    success: (uploadFileRes) => {;
                        
                        QueryCertificateFile(JSON.parse(uploadFileRes.data).data, type)
                    }
                });
            }
        })
    }  

    // 改变体验馆查询的分类
    const explorationType = (records) => {
        console.log(records);
        
    }

    // 模仿微信弹窗
    const WxToast = () => {
        return (
            <View className='cus-wx-toast' >
                <View>暂未查询到该公司品牌认证信息</View>
                <View>请联系相关工作人员</View>
            </View>
        )
    }

    // 渲染输入框
    const renderInputArea = () => {
        return (
            <View className='renderInputArea'>
                {/* {
                    type === 1 && 
                    <View className='select' onClick={() => setVisible(true)}>
                        <View >
                            <Text>请选择逻辑狗思维体验馆</Text>
                            <AtIcon value='play' size='30' customStyle={{color: '#000'}}></AtIcon>
                        </View>
                    </View>
                } */}
                <Input
                  name='value'
                  value={label}
                  onInput={onChange}
                  className='Atinput'
                  placeholderStyle='color: #666666; text-align: center;'
                  placeholder='请输入公司名称'
                />

                <View className='button' onClick={QueryCertificate}>
                    立即查询
                </View>

                <AtActionSheet isOpened={visible} onClose={() => setVisible(false)} >
                    {
                        SheetItem.map( item => (
                            <AtActionSheetItem key={item.typeId} onClick={() => explorationType(item)} >
                                {item.label}
                            </AtActionSheetItem>
                        ))
                    }
                  
                </AtActionSheet>
            </View>
        )
    }

    return (
        <View className='AuthOpra'>
            <Image
              mode='aspectFill'
              className='AuthOpra-bg'
              src={require(`../../assets/authOpra/type${type === 1 ? 0 : 5}.png`)}
            />
            { renderInputArea()}
            {
                isOpened ?  <WxToast /> : null
            }
           
          

            {/* <View className='scan-button' onClick={dispatchWxCamera}>
                <View>
                    <Image style={{width: 15, height: 15, marginRight: 13, display: 'block'}} src={require('../../assets/authOpra/scan-icon.png')}></Image>
                </View>
                <Text >扫描</Text>    
            </View> */}
            {/* <AtToast isOpened={isOpened} onClose={() => setIsOpened(false)} text='暂未查询到该公司品牌认证信息请联系相关工作人员'></AtToast> */}
        </View>
    )
}
export default AuthOpra

