// 数电的开票
import ProTable, { ActionType } from "@ant-design/pro-table";
import { FormInstance, Button, message, Tag, Popconfirm, Modal } from "antd";
import { useEffect, useRef, useState } from "react";
import { connect } from "umi";
import { Datum } from "@/types/invoice";
import { handleGetAppToken, handleGetBILLDETAILList, handleGetBILLList, handleGetForwardJDPJInterface, handleGetInvoiceSearch, handleGetKaiPiao, handleGetPassportInfoById, handleGetSDToken, handleSynchroAPPLYAPPROVE, handleSynchroBILLInterface } from "./service";
import moment from "moment";
import { encryptAES } from "@/utils/handleAes";
import { ProForm, ProFormSelect, ProFormTextArea } from "@ant-design/pro-components";
import InvoiceDetial from "../redReversal/components/InvoiceDetial";

interface ConnectState {
    user: {
        data: any;
    };
}

const publicParams: any = {
    // // 沙盒环境
    // baseUrl: 'https://cosmic-sandbox.piaozone.com/xhcamzchwbgonerr/',
    // user: '18620126214',
    // appId: 'FPY001',
    // appSecret: 'FPY001fpy@2023***',
    // accountId: '2280459335882518528',
    // tenantId: 'xhcamzchwbgonerr',
    // businessSystemCode: 'BUSINESS_YCIC',
    // sellerTaxpayerId: '91530112MA7MQ2JR9U',
    // sellerName: '云南交投集团经营开发有限公司彩云驿商业管理分公司',

    // 正式环境
    baseUrl: 'https://cosmic.piaozone.com/ynjtjtjykf',
    user: '18788526867',
    appId: 'FPY001',
    appSecret: 'FPY001fpy@2023***',
    accountId: '2311767813217320960',
    tenantId: 'ynjtjtjykf',
    businessSystemCode: 'BUSINESS_YCIC',
    sellerTaxpayerId: '91530000336622209K',
    sellerName: '云南交投集团经营开发有限公司',
}

const DigitalElectronics: React.FC<{ currentUser: any }> = (props) => {
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modalFormRef = useRef<FormInstance>();
    // 当前用户信息
    const [currentUser, setCurrentUser] = useState<any>();
    // 第一个接口的token
    const [appToken, setAppToken] = useState<any>()
    // 第二个接口的token 
    const [accessToken, setAccessToken] = useState<any>()
    // 红冲原因的悬浮框
    const [showModal, setShowModal] = useState<boolean>(false)
    // 当前选择的票据信息
    const [currentRow, setCurrentRow] = useState<any>()
    // 红冲悬浮框点击的加载效果
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false)
    // 显示详情抽屉
    const [showDetailModal, setShowDetailModal] = useState<boolean>(false)
    const columns: any = [
        {
            title: '服务区名称',
            dataIndex: 'SERVERPART_NAME',
            width: 150,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '商户名称',
            dataIndex: 'MERCHANTS_NAME',
            width: 250,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '票据编号',
            dataIndex: 'BILL_NO',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.BILL_NO ?
                    <a onClick={() => {
                        setCurrentRow(record)
                        setShowDetailModal(true)
                    }}>{record?.BILL_NO}</a> : ""
            }
        },
        {
            title: '流水号',
            dataIndex: 'SERIAL_NO',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '票据类型',
            dataIndex: 'BILL_TYPE',
            width: 100,
            align: 'center',
            hideInSearch: true,
            valueType: "select",
            valueEnum: {
                1000: { text: '专票', status: 'warning' },
                2000: { text: '普票', status: 'default' },
                3000: { text: '红票', status: 'error' },
            }
        },
        {
            title: '含税标识',
            dataIndex: 'ACCOUNTED_TYPE',
            width: 100,
            align: 'center',
            hideInSearch: true,
            render: (text: number) => (
                <Tag color={text === 1 ? 'green' : 'blue'}>
                    {text === 1 ? '含税' : '不含税'}
                </Tag>
            ),
        },
        {
            title: <div style={{ textAlign: 'center' }}>含税费用金额</div>,
            dataIndex: 'INVOICE_TAXAMOUNT',
            width: 120,
            valueType: 'digit',
            align: 'right',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '开票人',
            dataIndex: 'BILL_PERSON',
            width: 120,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '开票日期',
            dataIndex: 'BILL_DATE',
            width: 120,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '开户银行',
            dataIndex: 'BANK_NAME',
            width: 200,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '银行账号',
            dataIndex: 'BANK_ACCOUNT',
            width: 200,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '票据状态',
            dataIndex: 'BILL_STATE',
            width: 120,
            align: 'center',
            hideInSearch: true,
            valueType: 'select',
            fieldProps: {
                options: [
                    { label: "填写中", value: 1000 },
                    { label: "待审核", value: 2000 },
                    { label: "开票中", value: 9000 },
                    { label: "已开票", value: 9200 },
                    { label: "红冲申请中", value: 9990 },
                    { label: "已红冲", value: 9999 }
                ]
            }
            // 申请填写 1000   2000 待审核  9000 开票中  9200  已开票
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 200,
            fixed: 'right',
            align: 'center',
            hideInSearch: true,
            render: (text: any, record: Datum) => (
                record?.BILL_STATE === 2000 || record?.BILL_STATE === 9000 ?
                    <div>
                        <Popconfirm
                            title={record?.BILL_STATE === 9000 ? '确认重新开票？' : '确认同意开票？'}
                            onConfirm={
                                () => {
                                    handleInvoice(record)
                                    handleSynchroAPPLYAPPROVEFun(1, record)
                                }
                            }
                            onCancel={() => { }}
                            okText="确认"
                            cancelText="取消"
                        >
                            <Button type="primary" size="small">{record?.BILL_STATE === 9000 ? '重新开票' : '同意开票'}</Button>
                        </Popconfirm>
                        {
                            record?.BILL_STATE === 2000 ?
                                <Popconfirm
                                    title="确认退回开票？"
                                    onConfirm={
                                        () => {
                                            // handleInvoice(record)
                                            handleReturnInvoice(record)
                                            handleSynchroAPPLYAPPROVEFun(2, record)
                                        }
                                    }
                                    onCancel={() => { }}
                                    okText="确认"
                                    cancelText="取消"
                                >
                                    <Button danger style={{ marginLeft: "8px" }} type="primary" size="small">退回开票</Button>
                                </Popconfirm> : ""
                        }
                    </div>
                    : record?.BILL_TYPE === 2000 && record?.BILL_STATE >= 9200 && record?.BILL_STATE !== 9999 ?
                        <div>
                            <Popconfirm
                                title="确认红冲发票？"
                                onConfirm={() => {
                                    setCurrentRow(record)
                                    setShowModal(true)
                                }}
                                onCancel={() => { }}
                                okText="确认"
                                cancelText="取消"
                            >
                                <Button danger style={{ marginLeft: "8px" }} size="small">红冲发票</Button>
                            </Popconfirm>
                        </div>
                        : ""
            ),
        },
    ]

    // 红冲发票
    const handleRedGoBill = async (record?: any) => {
        // 这个方法 比较复杂 我做一下注释 
        // 先拿到表单数据 里面有 红冲类型和 红冲原因
        // 红冲原因是给自己的同步接口 红冲类型 是给金飘云那边的
        // 然后再去查询一下 这张票在金飘云那边的数据 拿到这张票对应的蓝票id
        // 因为我们自己的票据信息里面 没有票据明细的内容 所以要调用自己的票据明细拿到详细的信息之后 就可以拿到这张票子里面的商品 可以传给金飘云
        // 红冲 就是 重新开一张票 然后开这张票的时候带上之前需要红冲那张票的蓝票id 即可
        // 红冲申请发出去之后  按照红冲的编码 用我们自己的接口 开一张新的票据记录 其他数据保持一致  编码为红冲编码 状态为 9000 开票中
        // 然后还有原的票同步  状态变为 9990 红冲中 
        // 最后同步开票流程变为 红冲中 

        // 拿到表单数据
        const formData: any = modalFormRef.current?.getFieldsValue()
        console.log('formData', formData);
        console.log('recordrecord', record);

        // 拿个票据明细
        const billDetail = await handleGetBILLDETAILList({
            SearchParameter: {
                BILL_ID: record?.BILL_ID
            },
            PageIndex: 1,
            PageSize: 999999,
            SortStr: "BILLDETAIL_ID"
        })

        // 调用金票云那里的列表接口
        // 构造查询数据
        const queryData = {
            // sellerTaxpayerId: "91530112MA7MQ2JR9U",
            sellerTaxpayerId: publicParams.sellerTaxpayerId,
            serialNo: record?.BILL_NO,
        };

        // 将data字段进行base64加密
        const dataStringOld = JSON.stringify(queryData);
        const encryptedDataOld = btoa(unescape(encodeURIComponent(dataStringOld)));

        // 构造最终请求参数
        const requestParams = {
            businessSystemCode: "BUSINESS_YCIC",
            interfaceCode: "BILL.INVOICE.QUERY",
            requestId: Date.now().toString(),
            data: encryptedDataOld
        };

        let newreq2: any = {
            name: "",
            value: encryptAES(JSON.stringify({
                ReqUrl: `https://cosmic.piaozone.com/ynjtjtjykf/kapi/app/sim/openApi?access_token=${accessToken}`,
                Access_token: accessToken,
                data: JSON.stringify(requestParams)
            }))
        }

        let responseOld = await handleGetForwardJDPJInterface(newreq2)
        responseOld = JSON.parse(responseOld as any)
        // console.log('最终请求参数:', requestParams);
        // // 调用查询接口 (这里需要传入正确的code参数)
        // const responseOld = await handleGetInvoiceSearch(requestParams, accessToken);
        // console.log('responseresponseresponseresponse', responseOld);
        let result: any = []
        if (responseOld && responseOld.success) {
            let res = JSON.parse(decodeURIComponent(escape(atob(responseOld.data))))
            result = res[0].invoiceList
        } else {
            return
        }

        console.log('最终请求结果:', result);
        let billDetailReq: any = []
        if (billDetail && billDetail.length > 0) {
            billDetail.forEach((item: any) => {
                billDetailReq.push({
                    amount: -item.INVOICE_AMOUNT, // 明细金额
                    detailId: item.BILLDETAIL_ID, // 业务系统明细id
                    goodsName: item.ITEM_NAME,// 商品名称
                    lineProperty: 2, // 行性质
                    price: item.INVOICE_PRICE,// 单价
                    quantity: -item.INVOICE_COUNT,// 数量
                    revenueCode: item.TABLE_NAME,// 税收分类编码
                    taxRate: (item.DUTY_PARAGRAPH / 100).toFixed(2),// 税率
                    units: item.ITEM_UNIT,// 计量单位

                })
            })
        }

        let obj: any = {
            billNo: record?.BILL_NO ? `HC-${record?.BILL_NO}` : "", // 单据编号
            billDate: moment(record?.BILL_DATE).format('YYYY-MM-DD'), // 单据日期
            totalAmount: -record?.INVOICE_TAXAMOUNT, // 单据金额
            includeTaxFlag: record?.ACCOUNTED_TYPE,// 判断是否含税
            autoInvoice: "1",// 自动开票标记
            invoiceProperty: "1",
            invoiceType: record?.BILL_TYPE == 1000 ? '08xdp' : record?.BILL_TYPE == 2000 ? '10xdp' : '', //发票种类
            buyerTaxpayerId: record?.TAXPAYER_IDENTIFYCODE,// 购方税号
            buyerName: record?.MERCHANTS_NAME, // 购买方名称
            buyerProperty: "0", // 购买方性质 0-企业，1-个人，2-非企业单位
            // sellerTaxpayerId: "91530112MA7MQ2JR9U", // 销方税号 写死
            sellerTaxpayerId: publicParams.sellerTaxpayerId, // 销方税号 写死
            // sellerName: "云南交投集团经营开发有限公司彩云驿商业管理分公司", // 销方名称 写死
            sellerName: publicParams.sellerName, // 销方名称 写死
            sellerBankAndAccount: "13710884704", // 销方银行和账号 写死
            sellerAddressAndTel: "", // 销方地址和电话  写死 应该可以不传
            drawer: record?.BILL_PERSON,// 开票人
            buyerRecipientPhone: record?.RECEIVE_PHONENUMBER,// 购方收票手机号
            buyerRecipientMail: record?.RECEIVE_EMAIL,// 购方收件邮箱

            redReason: formData?.redReasonSelect || "",
            autoMerge: "0",
            // blueinvoiceNo: '23249322851717775360',
            blueinvoiceNo: result[0].invoiceNumber,
            // originalIssueTime: record?.originalIssueTime,
            // blueInvoiceType: record?.blueInvoiceType,
            blueinvoiceCode: "",
            billDetail: billDetailReq
        }

        // 构造原始数据
        const originalData = [obj]; // 将record作为data数组的一项
        // 将data字段进行base64加密
        const dataString = JSON.stringify(originalData);
        const encryptedData = btoa(unescape(encodeURIComponent(dataString))); // base64编码，支持中文
        // 构造开票请求数据
        const invoiceData = {
            businessSystemCode: "BUSINESS_YCIC", // 来源系统编码
            interfaceCode: "BILL.PUSH", // 接口业务编码
            requestId: Date.now().toString(), // 时间戳作为请求ID
            data: encryptedData // 加密后的data字符串
        };
        console.log('加密前的请求参数:', {
            businessSystemCode: "BUSINESS_YCIC", // 来源系统编码
            interfaceCode: "BILL.PUSH", // 接口业务编码
            requestId: Date.now().toString(), // 时间戳作为请求ID
            data: obj // 加密后的data字符串
        });
        console.log('原始数据:', originalData);
        console.log('JSON字符串:', dataString);
        console.log('Base64加密后:', encryptedData);
        console.log('最终请求数据:', invoiceData);
        console.log('访问令牌:', accessToken);
        // const response = await handleGetKaiPiao(invoiceData, accessToken);

        let newreq: any = {
            name: "",
            value: encryptAES(JSON.stringify({
                ReqUrl: `https://cosmic.piaozone.com/ynjtjtjykf/kapi/app/sim/openApi?access_token=${accessToken}`,
                Access_token: accessToken,
                data: JSON.stringify(invoiceData)
            }))
        }

        let response = await handleGetForwardJDPJInterface(newreq)
        response = JSON.parse(response as any)
        console.log('开票响应:', response);

        setShowModal(false)
        setCurrentRow(null)
        if (response.success) {
            message.success('红冲成功！')
            // 同步流程的 加上红冲中的状态  
            await handleSynchroAPPLYAPPROVEFun(3, record)
            let redReasonObj: any = {
                "1": "销货退回",
                "2": "开票有误",
                "3": "开票中止",
                "4": "销售折让",
            }
            // 同步旧票子 变为 红冲申请中
            await handleSynchroBILL(2, {
                ...record,
                billDetail: billDetail
            })
            // 针对这个红冲 开一张新票子  编码为新的红冲编码 状态为9000  开票中 且票据类型变为 3000  红票 BILL_TYPE
            await handleUpdateOldBill({
                ...record,
                billDetail: billDetail,
                BILL_TYPE: 3000,
                BILL_STATE: 9000,
                BILL_NO: `HC-${record?.BILL_NO}`,
                BILL_DATE: moment().format('YYYY-MM-DD'),
                BILL_DESC: formData?.redReasonSelect ? redReasonObj[formData?.redReasonSelect] : "",
                BILL_ID: "",
                BILL_TAXAMOUNT: -record?.BILL_TAXAMOUNT,
                BILL_AMOUNT: -record?.BILL_AMOUNT,
                INVOICE_TAXAMOUNT: -record?.INVOICE_TAXAMOUNT,
                INVOICE_AMOUNT: -record?.INVOICE_AMOUNT,
            })
            actionRef.current?.reload()
        } else {
            message.error(response.message)
        }
        setConfirmLoading(false)
    }
    // 开票处理函数
    const handleInvoice = async (record: Datum) => {
        try {
            message.loading({ content: '正在发起开票...', key: 'invoice' });

            // 检查是否有access_token
            if (!accessToken) {
                message.error({ content: '缺少访问令牌，请先刷新页面重新获取', key: 'invoice' });
                return;
            }

            console.log('recordrecord', record);
            // 拿个票据明细
            const billDetail = await handleGetBILLDETAILList({
                SearchParameter: {
                    BILL_ID: record?.BILL_ID
                },
                PageIndex: 1,
                PageSize: 999999,
                SortStr: "BILLDETAIL_ID"
            })

            console.log('billDetailbillDetailbillDetailbillDetail', billDetail);


            let billDetailReq: any = []
            if (billDetail && billDetail.length > 0) {
                billDetail.forEach((item: any) => {
                    billDetailReq.push({
                        amount: item.INVOICE_AMOUNT, // 明细金额
                        detailId: item.BILLDETAIL_ID, // 业务系统明细id
                        goodsName: item.ITEM_NAME,// 商品名称
                        lineProperty: 2, // 行性质
                        price: item.INVOICE_PRICE,// 单价
                        quantity: item.INVOICE_COUNT,// 数量
                        revenueCode: item.TABLE_NAME,// 税收分类编码
                        taxRate: (item.DUTY_PARAGRAPH / 100).toFixed(2),// 税率
                        units: item.ITEM_UNIT,// 计量单位

                    })
                })
            }

            let obj: any = {
                billNo: record?.BILL_NO, // 单据编号
                billDate: moment(record?.BILL_DATE).format('YYYY-MM-DD'), // 单据日期
                totalAmount: record?.INVOICE_TAXAMOUNT, // 单据金额
                includeTaxFlag: record?.ACCOUNTED_TYPE,// 判断是否含税
                autoInvoice: "1",// 自动开票标记
                invoiceType: record?.BILL_TYPE == 1000 ? '08xdp' : record?.BILL_TYPE == 2000 ? '10xdp' : '', //发票种类

                buyerTaxpayerId: record?.TAXPAYER_IDENTIFYCODE,// 购方税号
                buyerName: record?.MERCHANTS_NAME, // 购买方名称
                buyerProperty: "0", // 购买方性质 0-企业，1-个人，2-非企业单位

                // sellerTaxpayerId: "91530112MA7MQ2JR9U", // 销方税号 写死
                sellerTaxpayerId: publicParams.sellerTaxpayerId, // 销方税号 写死
                // sellerName: "云南交投集团经营开发有限公司彩云驿商业管理分公司", // 销方名称 写死
                sellerName: publicParams.sellerName,  // 销方名称 写死
                sellerBankAndAccount: "13710884704", // 销方银行和账号 写死
                sellerAddressAndTel: "", // 销方地址和电话  写死 应该可以不传

                drawer: record?.BILL_PERSON,// 开票人
                buyerRecipientPhone: record?.RECEIVE_PHONENUMBER,// 购方收票手机号
                buyerRecipientMail: record?.RECEIVE_EMAIL,// 购方收件邮箱
                remark: record?.BILL_DESC,

                // redReason: record?.BILL_DESC,

                // blueinvoiceNo: record?.blueinvoiceNo,
                // originalIssueTime: record?.originalIssueTime,
                // blueInvoiceType: record?.blueInvoiceType,
                // blueinvoiceCode: record?.blueinvoiceCode,
                billDetail: billDetailReq
            }

            console.log('objobj', obj);
            // 构造原始数据
            const originalData = [obj]; // 将record作为data数组的一项
            // 将data字段进行base64加密
            const dataString = JSON.stringify(originalData);
            const encryptedData = btoa(unescape(encodeURIComponent(dataString))); // base64编码，支持中文
            // 构造开票请求数据
            const invoiceData = {
                businessSystemCode: "BUSINESS_YCIC", // 来源系统编码
                interfaceCode: "BILL.PUSH", // 接口业务编码
                requestId: Date.now().toString(), // 时间戳作为请求ID
                data: encryptedData // 加密后的data字符串
            };
            console.log('加密前的请求参数:', {
                businessSystemCode: "BUSINESS_YCIC", // 来源系统编码
                interfaceCode: "BILL.PUSH", // 接口业务编码
                requestId: Date.now().toString(), // 时间戳作为请求ID
                data: obj // 加密后的data字符串
            });
            console.log('原始数据:', originalData);
            console.log('JSON字符串:', dataString);
            console.log('Base64加密后:', encryptedData);
            console.log('最终请求数据:', invoiceData);
            console.log('访问令牌:', accessToken);

            // const response = await handleGetKaiPiao(invoiceData, accessToken);
            let newreq: any = {
                name: "",
                value: encryptAES(JSON.stringify({
                    ReqUrl: `https://cosmic.piaozone.com/ynjtjtjykf/kapi/app/sim/openApi?access_token=${accessToken}`,
                    Access_token: accessToken,
                    data: JSON.stringify(invoiceData)
                }))
            }
            let response = await handleGetForwardJDPJInterface(newreq)

            response = JSON.parse(response as any)
            console.log('开票响应:', response);

            if (response && response.success) {
                let res: any = JSON.parse(decodeURIComponent(escape(atob(response.data))));
                console.log('最终结果:', res);

                message.success({ content: `单据 ${record.BILL_NO} 开票申请已提交成功`, key: 'invoice' });
                actionRef.current?.reload()
                // 他们的调用成功了 再调用我们自己的 同步票据信息表 的接口
                handleSynchroBILL(1, record)


            } else {
                message.error({ content: `开票申请失败: ${response?.message || '未知错误'}`, key: 'invoice' });
            }
        } catch (error) {
            console.error('开票错误:', error);
            message.error({ content: '开票申请失败，请重试', key: 'invoice' });
        }
    };
    // 退回开票
    const handleReturnInvoice = async (record: any) => {
        let req: any = {
            ...record,
            BILL_STATE: 1000,
            BILL_NO: `【退】${record?.BILL_NO}`
        }
        const data = await handleSynchroBILLInterface(req)
        console.log('djasdahslda', data);
        if (data.Result_Code === 100) {
            message.success('退回成功！');
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    }
    // 在这个页面获取token
    const handleGetTokenInPage = async () => {
        // 老
        // let req: any = {
        //     appId: publicParams.appId,
        //     appSecret: publicParams.appSecret,
        //     accountId: publicParams.accountId,
        //     tenantid: publicParams.tenantId,
        //     language: ""

        //     // appId: "FPY001",
        //     // appSecret: "FPY001fpy@2023***",
        //     // accountId: "2280459335882518528",
        //     // tenantid: "xhcamzchwbgonerr",
        //     // language: ""
        // }
        // const token = await handleGetAppToken(req)

        // 新
        let req: any = {
            ReqUrl: "https://cosmic.piaozone.com/ynjtjtjykf/api/getAppToken.do",
            Access_token: "",
            data: JSON.stringify({
                appId: publicParams.appId,
                appSecret: publicParams.appSecret,
                accountId: publicParams.accountId,
                tenantid: publicParams.tenantId,
                language: ""
            })
        }
        let newreq: any = {
            name: "",
            value: encryptAES(JSON.stringify(req))
        }
        let token = await handleGetForwardJDPJInterface(newreq)
        let tokenData = token ? JSON.parse(token as any) : ""
        console.log('tokenDatatokenDatatokenDatatokenDatadasdsa', tokenData);



        let appToken: any = tokenData.data.app_token
        // 老
        // let tokenReq: any = {
        //     // user: "18620126214",
        //     user: publicParams.user,
        //     apptoken: appToken,
        //     tenantid: publicParams.tenantId,
        //     accountId: publicParams.accountId,
        //     usertype: ""
        //     // apptoken: appToken,
        //     // tenantid: "xhcamzchwbgonerr",
        //     // accountId: "2280459335882518528",
        //     // usertype: ""
        // }
        // const accessToken: any = await handleGetSDToken(tokenReq)

        // 新
        let tokenReq: any = {
            ReqUrl: "https://cosmic.piaozone.com/ynjtjtjykf/api/login.do",
            Access_token: "",
            data: JSON.stringify({
                user: publicParams.user,
                apptoken: appToken,
                tenantid: publicParams.tenantId,
                accountId: publicParams.accountId,
                usertype: ""
            })
        }

        let newTokenReq: any = {
            name: "",
            value: encryptAES(JSON.stringify(tokenReq))
        }
        let accessTokenData = await handleGetForwardJDPJInterface(newTokenReq)

        let accessToken = JSON.parse(accessTokenData as any)
        console.log('dajksdjaksd', accessToken);

        setAppToken(appToken)
        setAccessToken(accessToken.data.access_token)


        const queryData = {
            // sellerTaxpayerId: "91530112MA7MQ2JR9U",
            sellerTaxpayerId: publicParams.sellerTaxpayerId,
            serialNo: '20251020-5300001245-009',
        };
        console.log('queryDataqueryData', queryData);

        // 将data字段进行base64加密
        const dataStringOld = JSON.stringify(queryData);
        const encryptedDataOld = btoa(unescape(encodeURIComponent(dataStringOld)));

        // 构造最终请求参数
        const requestParams = {
            businessSystemCode: "BUSINESS_YCIC",
            interfaceCode: "BILL.INVOICE.QUERY",
            requestId: Date.now().toString(),
            data: encryptedDataOld
        };

        console.log('最终请求参数:', requestParams);

        let reqResult: any = {
            ReqUrl: `https://cosmic.piaozone.com/ynjtjtjykf/kapi/app/sim/openApi?access_token=${accessToken.data.access_token}`,
            Access_token: accessToken.data.access_token,
            data: JSON.stringify(requestParams)
        }

        let newreqResult: any = {
            name: "",
            value: encryptAES(JSON.stringify(reqResult))
        }
        let responseOld = await handleGetForwardJDPJInterface(newreqResult)
        console.log('responseOldresponseOldresponseOld', responseOld);
        responseOld = JSON.parse(responseOld as any)

        // 老
        // // 调用查询接口 (这里需要传入正确的code参数)
        // const responseOld = await handleGetInvoiceSearch(requestParams, accessToken.data.access_token);
        // console.log('responseresponseresponseresponse', responseOld);
        // let result: any = []
        // if (responseOld && responseOld.success) {
        //     let res = JSON.parse(decodeURIComponent(escape(atob(responseOld.data))))
        //     result = res[0].invoiceList
        // } else {
        //     return
        // }
    }
    const handleSynchroBILL = async (type: number, obj: any) => {
        // type 1 开票的同步状态 即 9000   2 开票的红冲状态 即 9990
        // 发票明细列表
        let detailList: any = []
        if (obj?.billDetail && obj?.billDetail.length > 0) {
            obj?.billDetail.forEach((item: any) => {
                detailList.push({
                    ITEM_NAME: item.goodsName,// 款项名称
                    ITEM_RULE: item.specification,// 规格型号
                    ITEM_UNIT: item.units,// 计量单位
                    INVOICE_COUNT: item.quantity,// 开票数量
                    INVOICE_PRICE: item.price,// 开票单价
                    INVOICE_AMOUNT: item.amount,// 开票金额
                    DUTY_PARAGRAPH: item.taxRate,// 开票税率
                    INVOICE_TAX: item.taxAmount,// 开票税额
                    INVOICE_DISCOUNT: item.discountAmount,// 折扣金额
                    INVOICE_DISCOUNTTAX: "",// 折扣税额 
                    ITEM_ACTAMOUNT: "",// 款项价税合计 
                    ITEM_DEDUCTIONAMOUNT: "",// 扣除额 
                    ITEM_ID: "",// 关联数据表内码（多个）
                    TABLE_NAME: "",// 数据表名称
                    OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),// 操作时间
                })
            })
        }
        let req: any = {
            ...obj,
            BILL_TYPE: obj.BILL_TYPE || "", // 票据类型（1000：增值税专用发票；2000：普通发票） ,
            BILL_NO: obj?.BILL_NO || "",//票据编号
            SERIAL_NO: obj?.SERIAL_NO || "",// 流水号（实际发票号码）
            BILL_TAXAMOUNT: obj?.BILL_TAXAMOUNT,// 含税开票金额
            BILL_AMOUNT: obj?.BILL_AMOUNT,// 除税开票金额 
            DUTY_PARAGRAPH: obj?.DUTY_PARAGRAPH,// 开票税率
            INVOICE_TAXAMOUNT: obj?.INVOICE_TAXAMOUNT,// 含税费用金额
            INVOICE_AMOUNT: obj?.INVOICE_AMOUNT,// 除税费用金额 
            TAXTAIL_DIFFERENCE: obj?.TAXTAIL_DIFFERENCE,// 含税尾差 
            TAIL_DIFFERENCE: obj?.TAIL_DIFFERENCE,//  除税尾差 
            TAX_PRICE: obj?.TAX_PRICE,//  开票税金 
            SERVERPART_ID: obj?.SERVERPART_ID,
            SERVERPART_NAME: obj?.SERVERPART_NAME,
            SERVERPARTSHOP_ID: obj?.SERVERPARTSHOP_ID,//  门店内码 
            SERVERPARTSHOP_NAME: obj?.SERVERPARTSHOP_NAME,//  门店名称 
            MERCHANTS_ID: obj?.MERCHANTS_ID,//  商户内码 
            MERCHANTS_NAME: obj?.MERCHANTS_NAME,//  商户名称 
            BILL_PERSON: obj?.BILL_PERSON,//  开票人 
            BILL_DATE: obj?.BILL_DATE,//  开票日期 
            BANK_NAME: obj?.BANK_NAME,//  开户银行 
            BANK_ACCOUNT: obj?.BANK_ACCOUNT,//  银行账号 
            TAXPAYER_IDENTIFYCODE: obj?.TAXPAYER_IDENTIFYCODE,//  统一信用代码 
            INTERBANK_NO: obj?.INTERBANK_NO,//  联行号 
            TAXPAYER_CODE: obj?.sellerTaxpayerId,//  开票方纳税人识别号 
            ACCOUNTED_TYPE: obj?.ACCOUNTED_TYPE,//  入账类型 
            ACCOUNTED_DATE: obj?.ACCOUNTED_DATE,//  入账时间 
            DOWNLOAD_URL: obj?.DOWNLOAD_URL,// 下载地址
            RECEIVE_PHONENUMBER: obj?.RECEIVE_PHONENUMBER,// 收票方手机
            RECEIVE_EMAIL: obj?.RECEIVE_EMAIL,// 收票方邮箱
            BILL_STATE: type === 1 ? 9000 : type === 2 ? '9990' : '',//  票据状态 
            DetailList: obj?.DetailList,//  发票明细列表 
        }
        const data = await handleSynchroBILLInterface(req)
        console.log('data2222', data);
    }
    // 获取当前用户信息
    const handleGetUserInfo = async (id: string) => {
        const req: any = {
            UserIdEncrypted: id
        }
        const data = await handleGetPassportInfoById(req)
        console.log('datae2e12e1', data);
        setCurrentUser(data)
        return data
    }
    // 同步操作的流程信息 审核通过  和 审核驳回 都要去调用一下 同步流程的方法
    const handleSynchroAPPLYAPPROVEFun = async (type: number, obj: any) => {
        // type  1 审核通过   2 拒绝审核  3 红冲中
        // obj 当前票据信息
        const req: any = {
            ACTINST_NAME: type === 1 ? '审核开票申请' : type === 2 ? '驳回开票申请' : type === 3 ? "红冲发票申请" : "",// 状态名称  审核开票申请 || 驳回开票申请 
            APPROVE_TYPE: obj?.BILL_ID,// 票的id
            APPROVE_INFO: type === 1 ? '同意开票' : type === 2 ? '驳回开票' : type === 3 ? "红冲发票" : "",// 同意开票 || 驳回开票
            STAFF_ID: currentUser?.ID,
            STAFF_NAME: currentUser?.Name,
            APPROVE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            APPROVE_STATE: type === 1 ? 9000 : type === 2 ? 1000 : type === 3 ? '9990' : "",
            APPROVE_DESC: "T_BILL"
        }
        let reqData: any = {
            name: "",
            value: encryptAES(JSON.stringify(req))
        }

        const data = await handleSynchroAPPLYAPPROVE(reqData)
        console.log('datadatadata312321', data);

    }
    // 红冲的时候 同步原先的票子 传入红冲原因
    const handleUpdateOldBill = async (record: any) => {
        let req: any = {
            ...record,
        }
        const data = await handleSynchroBILLInterface(req)
        console.log('新票子', data);
    }

    useEffect(async () => {
        // 先调用token  后续这个页面用得到
        await handleGetTokenInPage()


    }, [])


    return (
        <div>
            <ProTable
                actionRef={actionRef}
                formRef={formRef}
                columns={columns}
                bordered
                expandable={{
                    expandRowByClick: true
                }}
                rowKey={(record) => {
                    return `${record?.billNo}`
                }}
                scroll={{ x: "100%", y: 'calc(100vh - 350px)' }}
                headerTitle={<span style={{ color: "#1890ff", fontSize: 14, fontWeight: 600 }}>待开票列表</span>}
                search={{ span: 6, labelWidth: 100 }}
                request={async (params: any) => {
                    const search = window.location.search;
                    const addressParams = Object.fromEntries(new URLSearchParams(search).entries());
                    const userInfo = await handleGetUserInfo(addressParams.UserIdEncrypted)

                    // 获取票据信息表列表
                    const req: any = {
                        SearchParameter: {
                            SERVERPART_IDS: userInfo?.ServerpartIds,
                            BILL_STATES: "2000,9000",
                            BILL_TYPES: ""
                        },
                        PageIndex: 1,
                        PageSize: 999999
                    }

                    const data = await handleGetBILLList(req)
                    console.log('dsahdgasyifgdhsvs', data);
                    if (data && data.length > 0) {
                        return { data: data, success: true }
                    }
                    return { data: [], success: true }
                }}
            />

            {/* 用来输入红冲原因的 */}
            <Modal
                title={"红冲原因"}
                open={showModal}
                destroyOnClose
                confirmLoading={confirmLoading}
                onCancel={() => {
                    setShowModal(false)
                    setCurrentRow(null)
                }}
                onOk={() => {
                    modalFormRef.current?.validateFields().then(res => {
                        if (res) {
                            modalFormRef.current?.submit()
                        }
                    })
                }}
            >
                <ProForm
                    formRef={modalFormRef}
                    submitter={false}
                    onFinish={() => {
                        setConfirmLoading(true)
                        handleRedGoBill(currentRow)
                    }}
                >
                    <ProFormSelect
                        label={'红冲类型'}
                        name={"redReasonSelect"}
                        rules={[
                            {
                                required: true,
                                message: '请选择红冲类型'
                            }
                        ]}
                        fieldProps={{
                            options: [
                                { label: "销货退回", value: '1' },
                                { label: "开票有误", value: '2' },
                                { label: "开票中止", value: '3' },
                                { label: "销售折让", value: '4' },
                            ]
                        }}
                    />
                    {/* <ProFormTextArea
                        label={"红冲原因"}
                        name={"redReason"}
                        rules={[
                            {
                                required: true,
                                message: '请输入红冲原因'
                            }
                        ]}
                    /> */}
                </ProForm>
            </Modal>

            <InvoiceDetial showDetail={showDetailModal} setShowDetail={setShowDetailModal} parentRow={currentRow} setParentRow={setCurrentRow} />

        </div>
    )
}


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