
import { useEffect, useRef, useState } from "react";
import { connect } from "umi";
import { handleCancel, handleGetBWTokenFun, handleGetCertifyQrcode, handleGetCertifyQrcodeResult, handleGetDeliver, handleGetInvoiceDetail, handleGetInvoicePageTable, handleGetUserInfoById } from "./service";
import { FormInstance, message, Modal, Space } from "antd";
import { ActionType, ProTable } from "@ant-design/pro-components";
import moment from "moment";

const { confirm } = Modal;


const InvoicingIndex: React.FC<{ currentUser: any }> = (props) => {
    // 查询人脸的认证的状态
    const timerRef = useRef<NodeJS.Timeout | null>(null);  // 保存定时器引用
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    // 表格数据
    const [tableData, setTableData] = useState<any>()
    // 当前的百旺配置详情
    const [BWDetailObj, setBWDetailObj] = useState<any>()
    // 显示表格
    const [showTable, setShowTable] = useState<boolean>(false)
    // 当前用户详情
    const [userInfo, setUserInfo] = useState<any>()


    useEffect(() => {
        // 开始刷脸认证的流程
        handleGetFacialAuthentication()
    }, [])


    // 开始刷脸认证的流程
    const handleGetFacialAuthentication = async () => {
        let url = window.location.search.split('?')[1]
        const params = new URLSearchParams(url);
        let resultObj: any = {};
        for (const [key, value] of params.entries()) {
            resultObj[key] = value;
        }
        let code = "menuCloud"

        if (resultObj.UserIdEncrypted) {
            handleGetUserInfo(resultObj.UserIdEncrypted)
        }


        const detail = await handleGetInvoiceDetail(code)
        let detailObj = detail.data
        setBWDetailObj(detail.data)
        // taxNo

        // let req: any = {
        //     code: code
        // }
        // const data = await handleGetBWTokenFun(req)
        // let token = data.data.data.token

        let codeReq: any = {
            qrCodeType: 0,
            operatorType: 0
        }
        // 刷脸二维码的值
        const qrCodeData = await handleGetCertifyQrcode('menuCloud', codeReq)
        let length = qrCodeData.data.response.qrCode.split(',') && qrCodeData.data.response.qrCode.split(',').length > 0 ? qrCodeData.data.response.qrCode.split(',').length : 0

        let img = qrCodeData.data.response.qrCode.split(',')[length - 1]
        let src = `data:image/png;base64,${img}`

        const instance = confirm({
            width: 600,
            content: <div>
                <div style={{ fontSize: '18px', fontWeight: 600, display: 'flex', justifyContent: 'center' }}>请先扫码进行人脸认证！</div>
                <div style={{ width: '100%', height: '300px', display: 'flex', justifyContent: 'center' }}>
                    <img style={{ width: '300px', height: '300px' }} src={src} />
                </div>
            </div>,
            footer: false
        });

        // handleGetCertifyQrcodeResult
        timerRef.current = setInterval(async () => {
            const resultData = await handleGetCertifyQrcodeResult('menuCloud', {
                certifyQueryType: 1
            })
            let res: any = resultData.data.response
            if (res.certificationStatus == '1') {
                if (timerRef.current) {
                    clearInterval(timerRef.current)
                    timerRef.current = null
                }
                // instance.destroy(); 
                message.success({ content: '认证成功！' })
                setShowTable(true)
            }
        }, 2000);
    }

    // 列表显示内容
    const columns: any = [
        {
            title: "统计日期",
            dataIndex: "staticDate",
            hideInTable: true,
            valueType: "dateRange",
            initialValue: [moment().startOf('M'), moment()],
            search: {
                transform: (value: any) => {
                    return {
                        beginDate: moment(value[0]).format('YYYY-MM-DD'),
                        endDate: moment(value[1]).format('YYYY-MM-DD')
                    };
                },
            },
            fieldProps: {
                picker: "day",
                format: 'YYYY-MM-DD',
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>申请流水号</div>,
            dataIndex: "serialNo",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>开票单号</div>,
            dataIndex: "orderNo",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>订单日期</div>,
            dataIndex: "orderDateTime",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            render: (_, record) => {
                return record?.orderDateTime ? moment(record?.orderDateTime).format('YYYY-MM-DD HH:mm:ss') : ""
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>开票时间</div>,
            dataIndex: "invoiceTime",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            render: (_, record) => {
                return record?.invoiceTime ? moment(record?.invoiceTime).format('YYYY-MM-DD HH:mm:ss') : ""
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>开票终端</div>,
            dataIndex: "invoiceTerminalCode",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>销方税号</div>,
            dataIndex: "taxNo",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>销方名称</div>,
            dataIndex: "sellerName",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>购方税号</div>,
            dataIndex: "buyerTaxNo",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>购方名称</div>,
            dataIndex: "buyerName",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: <div style={{ textAlign: 'center' }}>invoiceType</div>,
            title: "开票类型",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            render: (_, record) => {
                return record?.invoiceType === 1 ? '蓝票' : record?.invoiceType === 2 ? '红票' : ''
            }
        },
        {
            dataIndex: <div style={{ textAlign: 'center' }}>invoiceTypeCode</div>,
            title: "发票种类编码",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            dataIndex: <div style={{ textAlign: 'center' }}>remarks</div>,
            title: "备注",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>发票代码</div>,
            dataIndex: "invoiceCode",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>发票号码</div>,
            dataIndex: "invoiceNo",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>数电发票号码</div>,
            dataIndex: "digitInvoiceNo",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>不含税金额</div>,
            dataIndex: "invoiceTotalPrice",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>税额</div>,
            dataIndex: "invoiceTotalTax",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>含税金额</div>,
            dataIndex: "invoiceTotalPriceTax",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>发票状态</div>,
            dataIndex: "status",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            render: (_, record) => {
                return record?.status === 0 ? '开票中' : record?.status === 1 ? '开票完成' : record?.status === 2 ? '开票失败' : record?.status === 3 ? '发票已作废' : record?.status === 4 ? '发票作废中' : ''
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>发票状态描述</div>,
            dataIndex: "statusMessage",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>附件地址</div>,
            dataIndex: "pdfUrl",
            hideInSearch: true,
            width: 150,
            ellipsis: true,
            render: (_, recprd) => {
                return <a>查看附件</a>
            }
        },
        {
            title: '操作',
            dataIndex: "options",
            width: 100,
            hideInSearch: true,
            fixed: 'right',
            render: (_, record) => {
                return <Space>
                    <a onClick={() => {
                        handleInvoicing(record)
                    }}>
                        开票
                    </a>
                    <a onClick={() => {
                        handleCancelInvoicing(record)
                    }}>
                        作废
                    </a>

                </Space>
            }
        }
    ]

    // 开票
    const handleInvoicing = async (obj: any) => {
        const req: any = {
            // taxNo: BWDetailObj.taxNo,
            invoiceCode: obj.invoiceCode, // 发票代码
            invoiceNo: obj.invoiceNo, // 发票号码
            digitInvoiceNo: obj.digitInvoiceNo, // 数电发票号码
            pushPhone: obj.pushPhone, // 交付手机
            pushEmail: obj.pushEmail // 交付邮箱
        }
        // return
        const data = await handleGetDeliver('menuCloud', req)
    }

    // 作废
    const handleCancelInvoicing = async (obj: any) => {
        const req: any = {
            taxNo: BWDetailObj.taxNo,
            serialNo: obj.serialNo,
            orderNo: obj.orderNo,
            invoiceCode: obj.invoiceCode,
            invoiceNo: obj.invoiceNo,
            invalidOperator: "操作人"
        }
        const data = await handleCancel('menuCloud', req)
    }

    // 获取用户信息
    const handleGetUserInfo = async (UserIdEncrypted: string) => {
        const req: any = { UserIdEncrypted: UserIdEncrypted }
        const data = await handleGetUserInfoById(req)
        let userDetail: any = data.Result_Data
        setUserInfo(userDetail)
    }


    return (
        <div>
            {
                showTable ?
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        rowKey={(record) => {
                            return `${record?.id}`
                        }}
                        scroll={{ x: "100%", y: 'calc(100vh - 400px)' }}
                        headerTitle={<span style={{ color: "#1890ff", fontSize: 14, fontWeight: 600 }}>发票列表</span>}
                        search={{ span: 6 }}
                        request={async (params: any) => {
                            // startOf('M').
                            let [state, end] = [moment().format('YYYY-MM-DD 00:00:00'), moment().format('YYYY-MM-DD 23:59:59')]
                            const req: any = {
                                // serialNo: "25032610065056001376",
                                taxNo: BWDetailObj.taxNo || '',
                                pageNo: params?.current || 1,
                                pageSize: params?.pageSize || 1,
                                beginDate: state || '',
                                endDate: end || ''
                            }
                            const data = await handleGetInvoicePageTable('menuCloud', req)
                            let tableData: any = data.data.response

                            if (tableData.list && tableData.list.length > 0) {
                                return {
                                    data: tableData.list,
                                    success: true,
                                    total: tableData.total,  // 总数据条数
                                    current: tableData.pageNo, // 当前页码
                                    pageSize: tableData.pageSize, // 每页条数
                                }
                            }
                            return { data: [], success: true }
                        }}
                    /> : ""
            }



        </div>
    )
}

export default connect(({ user }: ConnectState) => ({
    currentUser: user.data
}))(InvoicingIndex);