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 { formatDateTime, formatHashTag, formatImgUrl, formatPriceDiv, formatRemoveHashTag, formatWeightDiv } from "@/common/fotmat";
import useCheckAuthorize from "@/use/useCheckAuthorize";
import { GetPayCode } from "@/api/onlinePay";
import LoadingCard from "@/components/loadingCard";
import { GetOrderPayApi, GetPrepayOrderPayApi } from "@/api/orderPay";


type Param = {
    show?: true|false,
    onClose?: () => void,
    company?: string,
    qrcode?: string,
    orderInfo?: any,

}
type ListParam = {
    product_code: string,
    product_name: string,
    product_color_code: string,
    product_color_name: string,
    num: string,
    weight: string,
    length: string,
    sale_price: string,
    total_price: string
}
export default memo(({show = true, onClose, company, orderInfo}:Param) => {
    const [detail, setDetail] = useState<any>()
    
    useEffect(() => {
        if(show) {
            getCore()
        }
    }, [show])
    
    useEffect(() => {
        if(orderInfo) {
            let lists:ListParam[] = []
            orderInfo.product_list?.map(pitem => {
                pitem?.product_colors?.map(citem => {
                    lists.push({
                        product_code: formatRemoveHashTag(pitem.code),
                        product_name: pitem.name,
                        product_color_code: formatRemoveHashTag(citem.code),
                        product_color_name: citem.name,
                        num: citem.roll.toString(),
                        length: (citem.length/100).toString(),
                        weight: formatWeightDiv(citem.estimate_weight).toString(),
                        sale_price: formatPriceDiv(citem.sale_price).toString(),
                        total_price: formatPriceDiv(citem.total_sale_price||citem.estimate_amount).toString(),
                    })
                })
            })
            setDetail(() => ({
                title: "面料销售电子确认单",
                company: orderInfo.company_name, //后端公司
                order_type: orderInfo.sale_mode_name, //类型：大货
                sale_user: orderInfo.sale_user_name, //业务员
                order_created_time: formatDateTime(orderInfo.create_time), 
                order_no: orderInfo.order_no,
                shipment_mode: orderInfo.shipment_mode_name, //发货方式
                target_user_name: userName(orderInfo), //收件人
                target_address: address(orderInfo), //收货地址
                target_description: orderInfo.remark, //发货备注
                pay_account: orderInfo.account, //专属收款账号
                bank_account_name: orderInfo.account_name, //账户名称
                bank_name: orderInfo.bank_of_deposit, //开户银行
                pay_type:"", //支付方式, 可不传
                client: orderInfo.purchaser_name, //客户名称
                phone: userPhone(orderInfo), //收货手机号码
                order_total_length: (orderInfo.total_number/100).toString(), //订单布匹长度
                order_total_price: formatPriceDiv(orderInfo.total_sale_price).toString(), //订单价格
                order_total_num: (orderInfo.total_number).toString(),
                qrcode:"",  //跳转链接
                order_total_weight: formatWeightDiv(orderInfo.total_estimate_weight).toString(),  //订单布匹重量
                list: lists 
            }))
        }
    }, [orderInfo])

    //收货地址
    const address = (addressInfo) => {
        if(addressInfo?.shipment_mode == 2) {
            return addressInfo?.province_name?addressInfo.province_name + addressInfo.city_name + addressInfo.district_name + addressInfo.address_detail:''
        } else {
            return addressInfo?.take_goods_address
        }
    }

    //收件人
    const userName = (addressInfo) => {
        return addressInfo?.shipment_mode == 2? orderInfo.target_user_name:  ''
    }

    //手机号
    const userPhone = (addressInfo) => {
        return addressInfo?.shipment_mode == 2? orderInfo.target_user_phone : orderInfo.take_goods_phone
    }
    

    //获取支付二维码
    const [payCodeImage, setPayCodeImage] = useState<string>('')
    const fileData = useRef({
        filePath: '',
        base64: ''
    })
    const {fetchData, state} = GetPayCode()
    const getCore = async () => {
        let res = await fetchData(detail)
        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',
        })
    }
    

    //检查是否开启保存图片权限
    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.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>
    )
})