// 数电的开票
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 "../DigitalElectronics/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";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";

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 InvoiceInquiry: 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 [columnsStateMap, setColumnsStateMap] = useState<any>({
        BANK_NAME: { show: false },
        BANK_ACCOUNT: { show: false },
    });
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    const columns: any = [
        {
            title: "查询条件",
            dataIndex: "searchText",
            hideInTable: true,
            fieldProps: {
                placeholder: "请输入票据编号/流水号/业务单号",
            }
        },
        {
            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',
            valueType: "select",
            valueEnum: {
                1000: { text: '专票', status: 'warning' },
                2000: { text: '普票', status: 'default' },
                3000: { text: '红票', status: 'error' },
            }
        },
        {
            title: '票据状态',
            dataIndex: 'BILL_STATE',
            width: 120,
            align: 'center',
            valueType: 'select',
            fieldProps: {
                options: [
                    { label: "填写中", value: 1000 },
                    { label: "待审核", value: 2000 },
                    { label: "开票中", value: 9000 },
                    { label: "手动开票", value: 9100 },
                    { label: "已开票", value: 9200 },
                    { label: "红冲申请中", value: 9990 },
                    { label: "已红冲", value: 9999 }
                ]
            }
            // 申请填写 1000   2000 待审核  9000 开票中  9200  已开票
        },
        {
            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,
            sorter: 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,
        }
    ]

    // 导出的列表数据
    const detailColumns: any = [
        {
            title: '序号',
            dataIndex: 'index',
            valueType: "index",
            width: 70,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        // {
        //     title: '发票代码',
        //     dataIndex: 'BILL_NO',
        //     width: 150,
        //     align: 'center',
        //     ellipsis: true,
        //     hideInSearch: true,
        // },
        // {
        //     title: '发票号码',
        //     dataIndex: '',
        //     width: 250,
        //     align: 'center',
        //     ellipsis: true,
        //     hideInSearch: true,
        // },
        {
            title: '数电发票号码',
            dataIndex: 'SERIAL_NO',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '销方识别号',
            dataIndex: 'sellerTaxpayerId',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '销方名称',
            dataIndex: 'sellerName',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '购方识别号',
            dataIndex: 'TAXPAYER_IDENTIFYCODE',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '购买方名称',
            dataIndex: 'MERCHANTS_NAME',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '开票日期',
            dataIndex: 'BILL_DATE',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '税收分类编码',
            dataIndex: 'TABLE_NAMESUM',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '特定业务类型',
            dataIndex: 'specificBusinessType',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '货物或应税劳务名称',
            dataIndex: 'ITEM_NAMESUM',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '规格型号',
            dataIndex: 'ITEM_RULESUM',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '单位',
            dataIndex: 'ITEM_UNITSUM',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '数量',
            dataIndex: 'INVOICE_COUNTSUM',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '单价',
            dataIndex: 'INVOICE_PRICESUM',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '金额',
            dataIndex: 'INVOICE_AMOUNTSUM',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '税率',
            dataIndex: 'DUTY_PARAGRAPHSUM',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '税额',
            dataIndex: 'INVOICE_TAXSUM',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '税额价税合计',
            dataIndex: 'BILL_TAXAMOUNT',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '发票来源',
            dataIndex: 'InvoiceSource',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '发票票种',
            dataIndex: 'BILL_TYPE',
            width: 180,
            align: 'center',
            valueType: "select",
            valueEnum: {
                1000: { text: '专票', status: 'warning' },
                2000: { text: '普票', status: 'default' },
                3000: { text: '红票', status: 'error' },
            }
        },
        {
            title: '票据状态',
            dataIndex: 'BILL_STATE',
            width: 120,
            align: 'center',
            valueType: 'select',
            valueEnum: {
                "1000": "填写中",
                "2000": "待审核",
                "9000": "开票中",
                "9100": "手动开票",
                "9200": "已开票",
                "9990": "红冲申请中",
                "9999": "已红冲"
            }
            // 申请填写 1000   2000 待审核  9000 开票中  9200  已开票
        },
        {
            title: '是否正数发票',
            dataIndex: 'riskLevel',
            width: 100,
            align: 'center',
            hideInSearch: true,
        },
        {
            title: '发票风险等级',
            dataIndex: '发票风险等级',
            width: 120,
            valueType: 'digit',
            align: 'right',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '开票人',
            dataIndex: 'BILL_PERSON',
            width: 120,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '备注',
            dataIndex: 'BILLDETAIL_DESC',
            width: 120,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
            sorter: true
        }
    ]

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

        // 拿到表单数据
        const formData: any = modalFormRef.current?.getFieldsValue()
        // 拿个票据明细
        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)
        // // 调用查询接口 (这里需要传入正确的code参数)
        // const responseOld = await handleGetInvoiceSearch(requestParams, accessToken);
        let result: any = []
        if (responseOld && responseOld.success) {
            let res = JSON.parse(decodeURIComponent(escape(atob(responseOld.data))))
            result = res[0].invoiceList
        } else {
            return
        }

        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: cleanString(record?.TAXPAYER_IDENTIFYCODE),// 购方税号
            buyerName: record?.MERCHANTS_NAME, // 购买方名称
            buyerProperty: "0", // 购买方性质 0-企业，1-个人，2-非企业单位
            // sellerTaxpayerId: "91530112MA7MQ2JR9U", // 销方税号 写死
            sellerTaxpayerId: publicParams.sellerTaxpayerId, // 销方税号 写死
            // sellerName: "云南交投集团经营开发有限公司彩云驿商业管理分公司", // 销方名称 写死
            sellerName: publicParams.sellerName, // 销方名称 写死
            sellerBankAndAccount: "", // 销方银行和账号 写死
            sellerAddressAndTel: "", // 销方地址和电话  写死 应该可以不传
            payee: "周洁萍", // 收款人
            reviewer: "杨尚涛",// 复核人
            drawer: "杨木青",// 开票人

            buyerAddressAndTel: `${record?.MERCHANTS_ADDRESS}、${record?.MERCHANTS_TEL}`,// 购方地址、电话
            buyerBankAndAccount: `${record?.BANK_NAME}${record?.BANK_ACCOUNT}`,// 购方银行、账号
            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字符串
        };

        // 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)

        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;
            }

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

            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: cleanString(record?.TAXPAYER_IDENTIFYCODE),// 购方税号
                buyerName: record?.MERCHANTS_NAME, // 购买方名称
                buyerProperty: "0", // 购买方性质 0-企业，1-个人，2-非企业单位

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

                payee: "周洁萍", // 收款人
                reviewer: "杨尚涛",// 复核人
                drawer: "杨木青",// 开票人

                buyerAddressAndTel: `${record?.MERCHANTS_ADDRESS}、${record?.MERCHANTS_TEL}`,// 购方地址、电话
                buyerBankAndAccount: `${record?.BANK_NAME}${record?.BANK_ACCOUNT}`,// 购方银行、账号
                buyerRecipientPhone: record?.RECEIVE_PHONENUMBER,// 购方收票手机号
                buyerRecipientMail: record?.RECEIVE_EMAIL,// 购方收件邮箱

                // redReason: record?.BILL_DESC,

                // blueinvoiceNo: record?.blueinvoiceNo,
                // originalIssueTime: record?.originalIssueTime,
                // blueInvoiceType: record?.blueInvoiceType,
                // blueinvoiceCode: record?.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字符串
            };

            // 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)

            if (response && response.success) {
                let res: any = JSON.parse(decodeURIComponent(escape(atob(response.data))));

                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)
        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) : ""



        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)

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


        // const queryData = {
        //     // sellerTaxpayerId: "91530112MA7MQ2JR9U",
        //     sellerTaxpayerId: publicParams.sellerTaxpayerId,
        //     serialNo: '202509-401206-0014',
        // };

        // // 将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 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 responseOld = await handleGetForwardJDPJInterface(reqResult)
        // responseOld = JSON.parse(responseOld as any)

        // 老
        // // 调用查询接口 (这里需要传入正确的code参数)
        // const responseOld = await handleGetInvoiceSearch(requestParams, accessToken.data.access_token);
        // 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: cleanString(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)
    }
    // 获取当前用户信息
    const handleGetUserInfo = async (id: string) => {
        const req: any = {
            UserIdEncrypted: id
        }
        const data = await handleGetPassportInfoById(req)
        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)

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

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


    return (
        <div style={{ height: 'calc(100vh - 100px)', background: "#fff" }}>
            <ProTable
                actionRef={actionRef}
                formRef={formRef}
                columns={columns}
                bordered
                expandable={{
                    expandRowByClick: true
                }}
                rowKey={(record) => {
                    return `${record?.billNo}`
                }}
                scroll={{ x: "100%", y: 'calc(100vh - 450px)' }}
                headerTitle={<span style={{ color: "#1890ff", fontSize: 14, fontWeight: 600 }}>票据列表</span>}
                search={{ span: 6, labelWidth: 100 }}
                request={async (params: any, sorter: any) => {
                    const search = window.location.search;
                    const addressParams = Object.fromEntries(new URLSearchParams(search).entries());
                    const userInfo = await handleGetUserInfo(addressParams.UserIdEncrypted)
                    // 排序字段
                    const sortstr = Object.keys(sorter).map(n => {
                        const value = sorter[n]
                        return value ? `${n} ${value.replace('end', '')}` : ''
                    })
                    // 获取票据信息表列表
                    const req: any = {
                        SearchParameter: {
                            SERVERPART_IDS: userInfo?.ServerpartIds,
                            BILL_STATES: params?.BILL_STATE || "",
                            BILL_TYPES: params?.BILL_TYPE || "",
                        },
                        PageIndex: 1,
                        PageSize: 999999,
                        sortstr: sortstr.length ? sortstr.toString() : "BILL_ID  desc",
                        keyWord: {
                            Key: "BILL_NO,SERIAL_NO,INTERBANK_NO",
                            Value: params?.searchText || ""
                        }

                    }

                    const data = await handleGetBILLList(req)
                    if (data && data.length > 0) {
                        console.log('data', data);
                        let list: any = JSON.parse(JSON.stringify(data))
                        let res: any = []
                        if (list && list.length > 0) {
                            list.forEach((item: any) => {
                                if (item.DetailList && item.DetailList.length > 0) {
                                    item.DetailList.forEach((subItem: any) => {
                                        res.push({
                                            ...subItem,
                                            sellerTaxpayerId: '91530000336622209K',
                                            sellerName: "云南交投集团经营开发有限公司",
                                            TAXPAYER_IDENTIFYCODE: item.TAXPAYER_IDENTIFYCODE,
                                            MERCHANTS_NAME: item.MERCHANTS_NAME,
                                            BILL_DATE: item.BILL_DATE,
                                            TABLE_NAMESUM: subItem.TABLE_NAME,
                                            specificBusinessType: subItem.REALESTATE_ID ? '不动产经营租赁服务' : '',
                                            ITEM_NAMESUM: subItem.ITEM_NAME,
                                            ITEM_RULESUM: subItem.ITEM_RULE,
                                            ITEM_UNITSUM: subItem.ITEM_UNIT,
                                            INVOICE_COUNTSUM: subItem.INVOICE_COUNT,
                                            INVOICE_PRICESUM: (subItem.INVOICE_AMOUNT / subItem.INVOICE_COUNT).toFixed(2),
                                            INVOICE_AMOUNTSUM: (subItem.INVOICE_AMOUNT - subItem.INVOICE_TAX).toFixed(2),
                                            DUTY_PARAGRAPHSUM: subItem.DUTY_PARAGRAPH,
                                            INVOICE_TAXSUM: subItem.INVOICE_TAX,
                                            BILL_TAXAMOUNT: subItem.INVOICE_AMOUNT,
                                            InvoiceSource: "金蝶",
                                            SERIAL_NO: item.SERIAL_NO,
                                            BILL_PERSON: item.BILL_PERSON,
                                            BILL_TYPE: item.BILL_TYPE,
                                            BILL_STATE: item.BILL_STATE,
                                            riskLevel: item.BILL_TYPE === 3000 ? '否' : '是'
                                        })
                                    })
                                }
                            })
                        }
                        setReqDetailList(res)

                        return { data: data, success: true }
                    }
                    return { data: [], success: true }
                }}
                columnsState={{
                    value: columnsStateMap,
                    onChange: setColumnsStateMap,
                }}
                toolbar={{
                    actions: [
                        <Button type="primary" onClick={() => {
                            exportXlsxFromProColumnsExcelJS(detailColumns,
                                reqDetailList,
                                `发票列表`,
                                {
                                    // topTitle: `历史销售单品报表`, // 顶部大标题
                                    // footerMaker: currentUser?.Name,
                                    // footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                                    // footerStatsTime: `${searchParams?.StartDate}-${searchParams?.EndDate}`
                                }
                            )
                        }}>导出excel</Button>
                    ]
                }}
            />

            {/* 用来输入红冲原因的 */}
            <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} showType="search" />

        </div>
    )
}


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