import { Image, ScrollView, Text, View } from "@tarojs/components";
import { memo, useEffect, useRef, useState } from "react";
import classnames from "classnames";
import styles  from './index.module.scss'
import Popup from "@/components/popup";
import Taro from "@tarojs/taro";
import { alert } from "@/common/common";
import { formatImgUrl } from "@/common/fotmat";
import useCheckAuthorize from "@/use/useCheckAuthorize";
import { GetPayCode } from "@/api/onlinePay";
import LoadingCard from "@/components/loadingCard";


type Param = {
    show?: true|false,
    onClose?: () => void
}


type Item = {
    product_code: string,
    product_name: string,
    product_color_code: string,
    product_color_name: string,
    num: string,
    weight: string,
    sale_price: string,
    total_price: string
}
type CodeParam = {
    title: string,
    company: string,
    order_type: string,
    sale_user: string,
    order_created_time: string,
    order_no: string,
    department: string,
    shipment_mode: string,
    target_user_name: string,
    target_address: string,
    target_description: string,
    pay_account: string,
    bank_account_name: string,
    bank_name: string,
    pay_type: string,
    client: string,
    phone: string,
    order_total_length: string,
    order_total_price: string,
    qrcode: string,
    order_total_weight: string,
    list: Item[]
}
export default memo(({show = true, onClose}:Param) => {

    //获取支付二维码
    const [payCodeImage, setPayCodeImage] = useState<string>('')
    const fileData = useRef({
        filePath: '',
        base64: ''
    })
    const {fetchData, state} = GetPayCode()
    const getCore = async () => {
        let res = await fetchData({
            title: "面料销售电子确认单",
            company: "什么什么公司123",
            order_type: "散剪",
            sale_user: "小崔",
            order_created_time:"2022/02/01 12:32:13",
            order_no:"XS-211005888",
            department:"嘻嘻嘻",
            shipment_mode:"自提",
            target_user_name:"大崔",
            target_address:"阿斯顿发斯蒂芬",
            target_description:"无",
            pay_account:"1234567890123450001",
            bank_account_name:"佛山市浩川长盛科技有限公司",
            bank_name:"招商银行佛山分行禅城支行",
            pay_type:"现结",
            client:"客户名称",
            phone:"15818085802",
            order_total_length:"12",
            order_total_price:"63000",
            qrcode:"https://www.zzfzyc.com/checkorder/XS-211005888",
            order_total_weight:"300.00",
            list: [{product_code:'5215',product_name:'26S双纱亲水滑爽棉',product_color_code:'053',product_color_name:'洋红',num:'4',weight:'123.23',sale_price:'43',total_price:'4510.7'}]
        })
        const base64 = res.data.base64
        setPayCodeImage(() => base64)
        const time = new Date().valueOf()
        const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64) || [];
        let filePath = Taro.env.USER_DATA_PATH + '/img' + time +'.'+ format
        fileData.current.filePath = filePath
        fileData.current.base64 = bodyData
        const save = Taro.getFileSystemManager()
        save.writeFile({
            filePath: fileData.current.filePath,
            data: fileData.current.base64,
            encoding: 'base64',
        })
        
    }
    useEffect(() => {
        if(show)
            getCore()
    }, [show])

    //检查是否开启保存图片权限
    const {check} = useCheckAuthorize({scope:'scope.writePhotosAlbum', msg:'您没授权，无法保存图片'})
    const saveImageCheck = async () => {
        const res = await check()
        res&&saveImage()
    }

    //保存图片
    const saveImage = () => {
        alert.loading('正在保存图片')
        Taro.saveImageToPhotosAlbum({
            filePath: fileData.current.filePath,
            success: function (res) {
                alert.success('图片保存成功')
            },
            fail: function (err) {
                console.log('err::', err)
            }
        })
    }

    //预览图片
    const showImage = () => {
        console.log('fileData.current.filePath::', fileData.current.filePath)
        Taro.previewImage({
            current: fileData.current.filePath, // 当前显示
            urls: [fileData.current.filePath] // 需要预览的图片http链接列表
        })
    }
    
    //复制功能
    return (
        <View className={styles.scanPay_main}>
            <Popup show={show} showTitle={false} onClose={onClose}>
                <View className={styles.scanPay_con}>
                    <View className={classnames('iconfont icon-a-moreback', styles.miconfont_title)} onClick={onClose}></View>
                    <View className={styles.title}>扫码支付</View>
                    <View className={styles.desc}>
                        <Text className={classnames(styles.miconfont, 'iconfont, icon-zhuyi')}></Text>
                        扫码支付成功后，自动更新状态
                    </View>
                    <View className={styles.scanPay_list}>
                        {(state.loading)&&<LoadingCard/>||
                        <ScrollView scrollY className={styles.scanPay_list}>
                            <Image mode="widthFix" src={payCodeImage} onClick={showImage}></Image>
                        </ScrollView>}
                    </View>
                    <View className={styles.btns} onClick={saveImageCheck}>保存电子确认单</View>
                </View>
            </Popup>
        </View>
        
    )
})