import React, { useEffect, useRef, useState } from "react";
import ProForm, { ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-form";
import { Col, Drawer, FormInstance, Row, Table, Typography, Space, Button, Empty, Divider, Input, message, Select, Modal, Tooltip, ConfigProvider, DatePicker } from "antd";
import { connect } from "umi";
import { ActionType, ProTable } from "@ant-design/pro-components";
import { handleGetAPPLYAPPROVEList, handleGetBILLDETAILList, handleSynchroBILLDETAILList } from "@/pages/DigitalElectronics/service";
import moment from "moment";
import { encryptAES } from "@/utils/handleAes";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";
import { getFieldEnum } from "@/pages/serverpartAssets/service";
import RealEstate from "@/pages/realEstate";
import { handleGetREALESTATEList } from "@/pages/realEstate/service";
import zhCN from 'antd/locale/zh_CN';
import dayjs from "dayjs";
import 'dayjs/locale/zh-cn';
import weekday from "dayjs/plugin/weekday";
import localeData from "dayjs/plugin/localeData";
import customParseFormat from 'dayjs/plugin/customParseFormat';
import updateLocale from 'dayjs/plugin/updateLocale';
dayjs.extend(updateLocale);
dayjs.updateLocale('zh-cn', {
    weekStart: 0,
});
dayjs.extend(weekday);
dayjs.extend(localeData);
dayjs.extend(customParseFormat);
const { Text } = Typography;

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

interface ParamsType {
    showDetail: boolean;
    setShowDetail: (v: boolean) => void;
    parentRow: any;
    setParentRow: (v: any) => void;
    parentTableRef?: any; // 父表格实例
    showType?: string; // 没值 开票审核页面   search 票据查询页面
}


const InvoiceDetail = ({ showDetail, setShowDetail, parentRow, setParentRow, parentTableRef, showType }: ParamsType) => {
    const realEstateRef = useRef<any>();
    const formRef = useRef<FormInstance<any>>();
    const detailActionRef = useRef<ActionType>();

    const { RangePicker } = DatePicker;
    // 保存的加载效果
    const [saveLoading, setSaveLoading] = useState<boolean>(false)
    // 明细表格默认隐藏的内容 
    const [columnsStateMap, setColumnsStateMap] = useState<any>({
        INVOICE_PRICE: { show: false },
        INVOICE_DISCOUNT: { show: false },
    });
    useEffect(() => {
        if (formRef.current) {
            if (parentRow) {
                formRef.current.setFieldsValue(parentRow);
            } else {
                formRef.current.resetFields();
            }
        }
    }, [parentRow]);
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    // 判断是否进入了编辑状态 
    const [isEdit, setIsEdit] = useState(false);
    // 表格数据
    const [tableEditData, setTableEditData] = useState<any>();
    // 税率枚举列表
    const [taxRateList, setTaxRateList] = useState<any>();
    // 不动产信息
    const [realEstateData, setRealEstateData] = useState<any>();
    // 选择不动产的悬浮框
    const [selectRealEstateModal, setSelectRealEstateModal] = useState<any>();
    // 选择的不动产id
    const [selectRealEstateId, setSelectRealEstateId] = useState<any>();
    // 选择不动产的loading
    const [realEstateLoading, setRealEstateLoading] = useState<boolean>(false);
    // 当前发票明细 点击的行的信息
    const [currentRow, setCurrentRow] = useState<any>();
    // 解析不动产的枚举
    const [realEstateEnum, setRealEstateEnum] = useState<any>();
    // 判断当前的发票明细里面 有没有不动产
    const [haveRealEstate, setHaveRealEstate] = useState<boolean>(false)

    const detailColumns: any = [
        {
            title: "序号",
            dataIndex: "index",
            valueType: "index",
            align: 'center',
            width: 70,
            fixed: 'left'
        },
        {
            title: <div style={{ textAlign: 'center' }}>款项名称</div>,
            align: 'left',
            width: 200,
            dataIndex: "ITEM_NAME",
            ellipsis: true,
            fixed: 'left'
        },
        {
            title: <div style={{ textAlign: 'center' }}>税务代码</div>,
            align: 'left',
            width: 180,
            dataIndex: "TABLE_NAME",
            fixed: 'left',
            ellipsis: true,
            render: (_, record) => {
                const currentItem = tableEditData?.find((item: any) => item.BILLDETAIL_ID === record.BILLDETAIL_ID) || record;
                return isEdit ? <Input
                    key={record.BILLDETAIL_ID}
                    defaultValue={currentItem.TABLE_NAME} onBlur={(e: any) => {
                        let value: string = e.target.value || ""
                        let tableData: any = JSON.parse(JSON.stringify(tableEditData))
                        tableData.forEach((item: any) => {
                            if (item.BILLDETAIL_ID === record.BILLDETAIL_ID) {
                                item.TABLE_NAME = value
                            }
                        })
                        setTableEditData(tableData)
                    }} /> : currentItem.TABLE_NAME
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>租赁日期</div>,
            dataIndex: "LEASEDATE",
            width: 200,
            align: 'center',
            hideInTable: !haveRealEstate && showType === 'search',
            render: (_, record) => {
                const currentItem = tableEditData?.find((item: any) => item.BILLDETAIL_ID === record.BILLDETAIL_ID) || record;
                return isEdit ?
                    <ConfigProvider locale={zhCN}>
                        <RangePicker
                            defaultValue={[currentItem?.START_LEASEDATE ? dayjs(currentItem.START_LEASEDATE) : null, currentItem?.END_LEASEDATE ? dayjs(currentItem.END_LEASEDATE) : null]}
                            onChange={(e: any) => {
                                console.log('eee', e);
                                let [start, end] = [moment(e[0].$d).format('YYYY-MM-DD'), moment(e[1].$d).format('YYYY-MM-DD')]
                                console.log('2321321', [start, end]);

                                let tableData: any = JSON.parse(JSON.stringify(tableEditData))
                                console.log('tableDatatableData', tableData);
                                tableData.forEach((item: any) => {
                                    if (item.BILLDETAIL_ID === record.BILLDETAIL_ID) {
                                        item.START_LEASEDATE = start
                                        item.END_LEASEDATE = end
                                    }
                                })
                                setTableEditData(tableData)
                            }}
                        />
                    </ConfigProvider>
                    :
                    `${record?.START_LEASEDATE || ""}${record?.END_LEASEDATE ? `-${record?.END_LEASEDATE}` : ''}`
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>税率</div>,
            align: 'center',
            width: 70,
            fixed: 'left',
            dataIndex: "DUTY_PARAGRAPH",
            render: (_, record) => {
                const currentItem = tableEditData?.find((item: any) => item.BILLDETAIL_ID === record.BILLDETAIL_ID) || record;
                return isEdit ?
                    <Select
                        key={record.BILLDETAIL_ID}
                        style={{ width: '100%' }}
                        defaultValue={currentItem?.DUTY_PARAGRAPH ? currentItem?.DUTY_PARAGRAPH.toString() : ""}
                        options={taxRateList}
                        onChange={(e: any) => {
                            let value: string = e || ""
                            let tableData: any = JSON.parse(JSON.stringify(tableEditData))
                            tableData.forEach((item: any) => {
                                if (item.BILLDETAIL_ID === record.BILLDETAIL_ID) {
                                    item.DUTY_PARAGRAPH = value
                                }
                            })
                            setTableEditData(tableData)
                        }}
                    /> :
                    currentItem?.DUTY_PARAGRAPH ? `${currentItem?.DUTY_PARAGRAPH}%` : ""
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品条码</div>,
            align: 'left',
            width: 100,
            fixed: 'left',
            dataIndex: "ITEM_ID",
            ellipsis: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>规格型号</div>,
            align: 'center',
            width: 80,
            dataIndex: "ITEM_RULE",
            ellipsis: true,
            render: (_, record) => {
                const currentItem = tableEditData?.find((item: any) => item.BILLDETAIL_ID === record.BILLDETAIL_ID) || record;
                return isEdit ? <Input
                    key={record.BILLDETAIL_ID}
                    defaultValue={currentItem.ITEM_RULE} onBlur={(e: any) => {
                        let value: string = e.target.value || ""
                        let tableData: any = JSON.parse(JSON.stringify(tableEditData))
                        tableData.forEach((item: any) => {
                            if (item.BILLDETAIL_ID === record.BILLDETAIL_ID) {
                                item.ITEM_RULE = value
                            }
                        })
                        setTableEditData(tableData)
                    }} /> : currentItem.ITEM_RULE
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>计量单位</div>,
            align: 'center',
            width: 80,
            dataIndex: "ITEM_UNIT",
            ellipsis: true,
            render: (_, record) => {
                const currentItem = tableEditData?.find((item: any) => item.BILLDETAIL_ID === record.BILLDETAIL_ID) || record;
                return isEdit ? <Input
                    key={record.BILLDETAIL_ID}
                    defaultValue={currentItem.ITEM_UNIT} onBlur={(e: any) => {
                        let value: string = e.target.value || ""
                        let tableData: any = JSON.parse(JSON.stringify(tableEditData))
                        tableData.forEach((item: any) => {
                            if (item.BILLDETAIL_ID === record.BILLDETAIL_ID) {
                                item.ITEM_UNIT = value
                            }
                        })
                        setTableEditData(tableData)
                    }} /> : currentItem.ITEM_UNIT
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>数量</div>,
            align: 'right',
            width: 60,
            valueType: 'digit',
            dataIndex: "INVOICE_COUNT"
        },
        {
            title: <div style={{ textAlign: 'center' }}>单价</div>,
            align: 'right',
            width: 80,
            valueType: 'digit',
            dataIndex: "INVOICE_PRICE"
        },
        {
            title: <div style={{ textAlign: 'center' }}>金额</div>,
            align: 'right',
            width: 80,
            valueType: 'digit',
            dataIndex: "INVOICE_AMOUNT"
        },
        {
            title: <div style={{ textAlign: 'center' }}>税额</div>,
            align: 'right',
            width: 80,
            valueType: 'digit',
            dataIndex: "INVOICE_TAX"
        },
        {
            title: <div style={{ textAlign: 'center' }}>折扣</div>,
            align: 'center',
            width: 80,
            dataIndex: "INVOICE_DISCOUNT"
        },
        {
            title: "不动产",
            dataIndex: "option",
            width: 70,
            align: 'center',
            hideInTable: !haveRealEstate && showType === 'search',
            render: (_: any, record: any) => {
                return record?.REALESTATE_ID ?
                    <a onClick={() => {
                        setCurrentRow(record)
                        setSelectRealEstateId([Number(record?.REALESTATE_ID)])
                        setSelectRealEstateModal(true)
                    }}>
                        {realEstateEnum && realEstateEnum[record?.REALESTATE_ID] ? realEstateEnum[record?.REALESTATE_ID] : record?.REALESTATE_ID}
                    </a> : showType === 'search' ? '' :
                        <Tooltip title={"选择不动产"}>
                            <Button type={'primary'} onClick={async () => {
                                console.log('选择不动产', record);
                                console.log('票据信息', parentRow);

                                setCurrentRow(record)
                                setSelectRealEstateModal(true)
                            }}>+</Button>
                        </Tooltip>

            }
        }
        // {
        //     title: <div style={{ textAlign: 'center' }}>操作时间</div>,
        //     align: 'center',
        //     width: 150,
        //     dataIndex: "OPERATE_DATE",
        //     render: (_, record) => {
        //         return record?.OPERATE_DATE ? moment(record?.OPERATE_DATE).format('YYYY-MM-DD HH:mm:ss') : ""
        //     }
        // },
    ];

    const approveColumns: any = [
        {
            title: <div style={{ textAlign: 'center' }}>环节名称</div>,
            width: 200,
            align: 'center',
            dataIndex: "ACTINST_NAME",
        },
        {
            title: <div style={{ textAlign: 'center' }}>票据状态</div>,
            width: 150,
            dataIndex: "APPROVE_STATE",
            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 }
                ]
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>审批人</div>,
            dataIndex: "STAFF_NAME",
            align: 'center',
            width: 150,
        },
        {
            title: <div style={{ textAlign: 'center' }}>审批时间</div>,
            dataIndex: "APPROVE_DATE",
            align: 'center',
            width: 150,
            render: (_, record) => {
                return record?.APPROVE_DATE ? moment(record?.APPROVE_DATE).format('YYYY-MM-DD HH:mm:ss') : "-"
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>审批意见</div>,
            dataIndex: "APPROVE_INFO",
            ellipsis: true
        }
    ];

    // 不动产列表配置
    const realEstateColumns: any = [
        {
            title: "服务区名称",
            dataIndex: "SERVERPART_NAME",
            hideInSearch: true,
            ellipsis: true,
            width: 180,
            align: 'center'
        },
        {
            title: "不动产类型",
            dataIndex: "REALESTATE_TYPE",
            width: 150,
            valueType: "select",
            align: 'center',
            valueEnum: {
                1000: "房屋租赁",
                2000: "车辆资产",
            }
        },
        {
            title: "产权证号",
            dataIndex: "ESTATE_IDENTITY",
            hideInSearch: true,
            ellipsis: true,
            width: 150,
            align: 'center',
        },
        {
            title: "资料编码",
            dataIndex: "SPECIALINDUSTRY_NUMBER",
            hideInSearch: true,
            ellipsis: true,
            width: 150,
            align: 'center',
        },
        {
            title: "省份名称",
            dataIndex: "PROVINCE_NAME",
            hideInSearch: true,
            ellipsis: true,
            width: 150,
            align: 'center'
        },
        {
            title: "城市名称",
            dataIndex: "CITY_NAME",
            hideInSearch: true,
            ellipsis: true,
            width: 150,
            align: 'center'
        },
        {
            title: "详细地址",
            dataIndex: "REALESTATE_ADDRESS",
            hideInSearch: true,
            ellipsis: true,
            width: 180,
            align: 'center'
        },
        {
            title: "是否跨地",
            dataIndex: "CROSS_CITYSIGN",
            hideInSearch: true,
            ellipsis: true,
            width: 120,
            align: 'center',
            render: (_: any, record: any) => {
                return record?.CROSS_CITYSIGN ? "是" : "否"
            }
        },
        {
            title: "面积单位",
            dataIndex: "AREA_UNIT",
            hideInSearch: true,
            ellipsis: true,
            width: 120,
            align: 'center',
            valueType: "select",
            valueEnum: {
                1: "平方千米",
                2: "平方米",
                3: "公顷",
                4: "亩",
                5: "h㎡",
                6: "k㎡",
                7: "㎡"
            }
        },
        {
            title: "租赁期限",
            dataIndex: "LEASEDATE",
            hideInSearch: true,
            ellipsis: true,
            width: 250,
            align: 'center',
            render: (_: any, record: any) => {
                return `${record?.START_LEASEDATE || ""}${record?.END_LEASEDATE ? `-${record?.END_LEASEDATE}` : ''}`
            }
        }
    ]

    // 保存税务代码触发的事件
    const handleSaveTaxCode = async () => {
        // 当前的表格数据
        let newreqResult: any = {
            name: "",
            value: encryptAES(JSON.stringify({ list: tableEditData }))
        }
        setSaveLoading(true)

        const data = await handleSynchroBILLDETAILList(newreqResult)
        setSaveLoading(false)
        if (data.Result_Code === 100) {
            message.success('同步成功！')
            setIsEdit(false)
            detailActionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    }

    // 拿到选择的不动产 给表格显示
    const handleGetSelectRealEstate = (data: any) => {
        setRealEstateData(data)
    }
    // 获取到这个服务区的全部 不动产信息 并给枚举的解析赋值
    const handleGetThisServerpartRealEstateData = async () => {
        const req: any = {
            searchParameter: {
                SERVERPART_IDS: "",
                REALESTATE_STATE: 1
            },
            PageIndex: 1,
            PageSize: 999999,
        }
        let newReq: any = {
            name: "",
            value: encryptAES(JSON.stringify(req))
        }
        const data: any = await handleGetREALESTATEList(newReq)
        console.log('datadatadata', data);
        let obj: any = {}
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                obj[item.REALESTATE_ID] = item.ESTATE_IDENTITY
            })
        }
        setRealEstateEnum(obj)
        return data
    }

    return (
        <Drawer
            width="90%"
            open={showDetail}
            title="票据详情"
            onClose={() => {
                setShowDetail(false);
                setParentRow(undefined);
                setIsEdit(false)
                setTableEditData(null)
            }}
            bodyStyle={{ padding: '0 24px 24px' }}
            destroyOnClose
        >
            {/* 统一 labelCol 宽度：通过 formProps 设置 */}
            <ProForm
                formRef={formRef}
                submitter={false}
                layout="horizontal"
                formProps={{ labelCol: { span: 8 } }}
            >
                {/* 第一行：三列（每列 span=8） */}
                <Divider orientation="left">票据基本信息</Divider>
                <Row gutter={16}>
                    <Col span={8}>
                        <ProFormSelect name="BILL_TYPE" label="票据类型" readonly fieldProps={{
                            options: [
                                { label: "专票", value: 1000 },
                                { label: "普票", value: 2000 },
                                { label: "红票", value: 3000 }
                            ]
                        }} />
                        <ProFormText name="SERVERPART_NAME" label="服务区" readonly />
                        <ProFormText name="BILL_TAXAMOUNT" label="含税开票金额" readonly />
                        <ProFormText name="BILL_PERSON" label="开票申请人" readonly />

                    </Col>

                    <Col span={8}>
                        <ProFormText name="BILL_NO" label="票据编号" readonly />
                        <ProFormText name="SERIAL_NO" label="流水号" readonly />
                        <ProFormText name="BILL_AMOUNT" label="除税开票金额" readonly />
                        <ProFormText name="BILL_DATE" label="申请日期" readonly />

                    </Col>

                    <Col span={8}>
                        <ProFormText name="ORIBILL_NO" label="原单据号" readonly />
                        <ProFormSelect name="BILL_STATE" label="票据状态" readonly fieldProps={{
                            options: [
                                { label: "填写中", value: 1000 },
                                { label: "待审核", value: 2000 },
                                { label: "开票中", value: 9000 },
                                { label: "已开票", value: 9200 },
                                { label: "红冲申请中", value: 9990 },
                                { label: "已红冲", value: 9999 }
                            ]
                        }} />
                        <ProFormText name="TAX_PRICE" label="开票税金" readonly />
                        <ProFormText name="ACCOUNTED_DATE" label="开票日期" readonly />
                        {/* <ProFormText name="INTERBANK_NO" label="联行号" readonly /> */}
                        {/* <ProFormText name="TAXPAYER_CODE" label="纳税人识别号" readonly /> */}
                    </Col>
                </Row>
                <Divider orientation="left">收票方</Divider>
                {/* 第二行 */}
                <Row gutter={16}>
                    <Col span={8}>
                        <ProFormText name="MERCHANTS_NAME" label="商户名称" readonly />
                        <ProFormText name="MERCHANTS_ADDRESS" label="购方地址" readonly />
                        <ProFormText name="RECEIVE_EMAIL" label="收票邮箱" readonly />

                    </Col>


                    <Col span={8}>
                        <ProFormText name="TAXPAYER_IDENTIFYCODE" label="统一信用代码" readonly />
                        <ProFormText name="MERCHANTS_TEL" label="购方电话" readonly />

                        <ProFormText
                            name="DOWNLOAD_URL"
                            label="发票图片"
                            readonly
                            fieldProps={{
                                value: parentRow?.DOWNLOAD_URL ? (
                                    <a
                                        href={parentRow.DOWNLOAD_URL}
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        style={{ color: '#1890ff', textDecoration: 'none' }}
                                    >
                                        查看发票图片
                                    </a>
                                ) : '',
                            }}
                        />
                    </Col>


                    <Col span={8}>
                        <ProFormText name="BANK_NAME" label="开户银行" readonly />
                        <ProFormText name="BANK_ACCOUNT" label="银行账号" readonly />

                    </Col>
                </Row>

                <Row gutter={16}>
                    <Col span={24}>
                        <ProFormTextArea
                            name="BILL_DESC"
                            label="备注"
                            readonly
                            fieldProps={{
                                autoSize: true,
                            }}
                        />
                    </Col>
                </Row>

                {/* 发票明细 */}
                <div style={{ marginTop: 24 }}>
                    <Space direction="vertical" style={{ width: '100%' }}>
                        <Text strong>发票明细</Text>
                        {
                            selectRealEstateModal ? '' :
                                <ProTable
                                    actionRef={detailActionRef}
                                    search={false}
                                    columns={detailColumns}
                                    bordered
                                    scroll={{ x: "100%", y: '500px' }}
                                    // pagination={false}
                                    pagination={{
                                        defaultPageSize: 100,
                                        pageSizeOptions: ['100', '200', '500', '1000'],
                                    }}
                                    request={async () => {
                                        // 调用一次  获取这个服务区里面的全部 不动产信息
                                        handleGetThisServerpartRealEstateData()

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

                                        if (billDetail && billDetail.length > 0) {
                                            setTableEditData(billDetail)
                                            setReqDetailList(billDetail)
                                            console.log('billDetailbillDetailbillDetail', billDetail);

                                            // 因为要给原先的  不动产信息赋值租赁时间  所以先取出全部的 不动产id
                                            let allREALESTATE_ID: string = ''
                                            billDetail.forEach((item: any) => {
                                                if (item.REALESTATE_ID) {
                                                    if (allREALESTATE_ID) {
                                                        allREALESTATE_ID += `,${item.REALESTATE_ID}`
                                                    } else {
                                                        allREALESTATE_ID = `${item.REALESTATE_ID}`
                                                    }
                                                }
                                            })
                                            console.log('allREALESTATE_IDallREALESTATE_ID', allREALESTATE_ID);

                                            // 看看有没有不动产信息  
                                            if (allREALESTATE_ID) {
                                                setHaveRealEstate(true)
                                            } else {
                                                setHaveRealEstate(false)
                                            }

                                            // 请求到的当前的全部不动产信息
                                            const req: any = {
                                                searchParameter: {
                                                    REALESTATE_IDS: allREALESTATE_ID,
                                                    REALESTATE_STATE: 1
                                                },
                                                PageIndex: 1,
                                                PageSize: 999999,
                                            }
                                            let newReq: any = {
                                                name: "",
                                                value: encryptAES(JSON.stringify(req))
                                            }
                                            const data: any = await handleGetREALESTATEList(newReq)

                                            // 然后去找一样的不动产id  去匹配上 租赁时间的值
                                            billDetail.forEach((item: any) => {
                                                data.forEach((subItem: any) => {
                                                    if (Number(item.REALESTATE_ID) === Number(subItem.REALESTATE_ID) && !item.START_LEASEDATE && !item.END_LEASEDATE) {
                                                        item.START_LEASEDATE = subItem.START_LEASEDATE
                                                        item.END_LEASEDATE = subItem.END_LEASEDATE
                                                    }
                                                })
                                            })

                                            console.log('最终的结果 ', billDetail);
                                            return { data: billDetail, success: true }
                                        }
                                        return { data: [], success: true }
                                    }}
                                    columnsState={{
                                        value: columnsStateMap,
                                        onChange: setColumnsStateMap,
                                    }}
                                    toolbar={{
                                        actions: [
                                            <>
                                                {
                                                    parentRow?.BILL_STATE <= 2000 ?
                                                        <>
                                                            {
                                                                isEdit && parentRow?.BILL_STATE < 9000 ?
                                                                    <>
                                                                        <Button type="primary" loading={saveLoading} style={{ marginRight: '4px' }} onClick={() => {
                                                                            handleSaveTaxCode()
                                                                        }}>保存</Button>
                                                                        <Button onClick={() => {
                                                                            setIsEdit(false)
                                                                        }}>取消</Button>
                                                                    </> :
                                                                    <Button type="primary" onClick={() => {
                                                                        setIsEdit(true)
                                                                    }}>编辑表格</Button>
                                                            }
                                                        </> : ""
                                                }
                                            </>,
                                            <Button type={'primary'} onClick={async () => {
                                                exportXlsxFromProColumnsExcelJS(detailColumns,
                                                    reqDetailList,
                                                    `${parentRow?.BILL_NO}发票明细`,
                                                    {
                                                        // topTitle: `历史销售单品报表`, // 顶部大标题
                                                        // footerMaker: currentUser?.Name,
                                                        // footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                                                        // footerStatsTime: `${searchParams?.StartDate}-${searchParams?.EndDate}`
                                                    }
                                                )
                                            }}>导出excel</Button>
                                        ]
                                    }}
                                />
                        }

                    </Space>
                </div>

                {/* 不动产信息 */}
                {/* <div style={{ marginTop: 24 }}>
                    <Space direction="vertical" style={{ width: '100%' }}>
                        <Text strong>不动产信息</Text>
                    </Space>
                    <div>
                        <ProTable
                            actionRef={detailActionRef}
                            search={false}
                            columns={realEstateColumns}
                            bordered
                            scroll={{ x: "100%", y: '500px' }}
                            pagination={false}
                            // dataSource={realEstateData}
                            request={async () => {
                                if (selectRealEstateId && selectRealEstateId.length > 0) {
                                    const req: any = {
                                        searchParameter: {
                                            REALESTATE_IDS: selectRealEstateId.toString()
                                        },
                                        PageIndex: 1,
                                        PageSize: 999999,
                                    }
                                    let newReq: any = {
                                        name: "",
                                        value: encryptAES(JSON.stringify(req))
                                    }
                                    const data: any = await handleGetREALESTATEList(newReq)
                                    if (data && data.length > 0) {
                                        return { data, success: true }
                                    }
                                    return { data: [], success: true }
                                } else {
                                    return { data: [], success: true }
                                }
                            }}
                            columnsState={{
                                value: columnsStateMap,
                                onChange: setColumnsStateMap,
                            }}
                            toolbar={{
                                actions: [
                                    <>
                                        {
                                            parentRow?.BILL_STATE <= 2000 ?
                                                <Button type={'primary'} onClick={async () => {
                                                    // 点击开的时候判断一下 当前是否已经有选择的不动产内容了 有的话 要带回去给表格默认勾选
                                                    // let rowKey: any = []
                                                    // if (realEstateData && realEstateData.length > 0) {
                                                    //     rowKey = realEstateData.map((item: any) => item.REALESTATE_ID)
                                                    // }
                                                    // setSelectRealEstateId(rowKey)
                                                    setSelectRealEstateModal(true)
                                                }}>选择不动产</Button> : ''
                                        }
                                    </>
                                ]
                            }}
                        />
                    </div>
                </div> */}

                {/* 审批意见 */}
                <div style={{ marginTop: 24 }}>
                    <Space direction="vertical" style={{ width: '100%' }}>
                        <Text strong>审批意见</Text>

                        <ProTable
                            search={false}
                            columns={approveColumns}
                            options={false}
                            bordered
                            request={async () => {
                                // 拿个税率的枚举
                                const taxRateLabel: any = await getFieldEnum({ FieldExplainField: 'DUTY_PARAGRAPH', notformate: true })
                                setTaxRateList(taxRateLabel)

                                const req: any = {
                                    SearchParameter: {
                                        APPROVE_TYPE: parentRow?.BILL_ID,// 票的id
                                        APPROVE_DESC: "T_BILL"
                                    },
                                    PageIndex: 1,
                                    PageSize: 999999,
                                    SortStr: "APPROVE_DATE desc"
                                }
                                let reqData: any = {
                                    name: "",
                                    value: encryptAES(JSON.stringify(req))
                                }

                                const data = await handleGetAPPLYAPPROVEList(reqData)
                                if (data && data.length > 0) {
                                    return { data, success: true }
                                }
                                return { data: [], success: true }
                            }}
                        />
                    </Space>
                </div>



            </ProForm>


            {/* 不动产的悬浮框  */}
            <Modal
                width={'90%'}
                title={"选择不动产"}
                open={selectRealEstateModal}
                destroyOnClose
                onCancel={() => {
                    setSelectRealEstateModal(false)
                }}
                confirmLoading={realEstateLoading}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                footer={showType === 'search' ? '' : <div>
                    <Button onClick={() => {
                        setSelectRealEstateModal(false)
                    }}>取消</Button>
                    <Button loading={realEstateLoading} style={{ marginLeft: '8px' }} type={'primary'} onClick={async () => {
                        // 已经开票申请了的 就不能改变不动产数据了
                        // if (parentRow?.BILL_STATE > 2000) {
                        //     setCurrentRow(undefined)
                        //     setSelectRealEstateModal(false)
                        //     setRealEstateLoading(false)
                        //     return
                        // }


                        // let data = realEstateRef?.current?.selectRowDetail
                        let data: any = []

                        let nowSelectKey: any = realEstateRef?.current?.selectRowKey
                        let nowTableData: any = realEstateRef?.current?.tableData
                        if (nowTableData && nowTableData.length > 0) {
                            nowTableData.forEach((item: any) => {
                                if (item.REALESTATE_ID === nowSelectKey[0]) {
                                    data = [item]
                                }
                            })
                        }

                        console.log('datadasds', data);
                        // 开始保存内容
                        handleGetSelectRealEstate(data)
                        if (tableEditData && tableEditData.length > 0) {
                            setRealEstateLoading(true)
                            let list: any = JSON.parse(JSON.stringify(tableEditData))
                            let idList: any = []
                            // 因为 我们选择的 租赁开始结束时间在  data 中
                            // 但是实际的list 是来自tableEditData  所以得根据id拼进去  造一个对应id 对应的 租赁时间的对象
                            let leaseObj: any = {}
                            if (data && data.length > 0) {
                                idList = data.map((item: any) => Number(item.REALESTATE_ID))
                                data.forEach((item: any) => {
                                    leaseObj[item.REALESTATE_ID] = {
                                        START_LEASEDATE: item.START_LEASEDATE,
                                        END_LEASEDATE: item.END_LEASEDATE
                                    }
                                })
                            }
                            console.log('leaseObjleaseObj', leaseObj);

                            list.forEach((item: any) => {
                                if (item.REALESTATE_ID === currentRow?.REALESTATE_ID) {
                                    item.REALESTATE_ID = idList && idList.length > 0 ? Number(idList.toString()) : ""
                                    item.START_LEASEDATE = leaseObj[item.REALESTATE_ID]?.START_LEASEDATE
                                    item.END_LEASEDATE = leaseObj[item.REALESTATE_ID]?.END_LEASEDATE
                                }
                            })
                            setSelectRealEstateId(idList)
                            console.log('listlistlist', list);

                            let newreqResult: any = {
                                name: "",
                                value: encryptAES(JSON.stringify({ list: list }))
                            }
                            const res: any = await handleSynchroBILLDETAILList(newreqResult)
                            if (res.Result_Code === 100) {
                                message.success('同步成功！')
                                detailActionRef.current?.reload()
                                setCurrentRow(undefined)
                                if (parentTableRef) {
                                    parentTableRef.current?.reload()
                                }
                            } else {
                                message.error(data.Result_Desc)
                            }
                        }
                        setSelectRealEstateModal(false)
                        setRealEstateLoading(false)
                    }}>确定</Button>
                </div>}
                onOk={async () => {

                }}
            >
                <RealEstate serverPartId={parentRow?.SERVERPART_ID} isComponent={true} onRef={realEstateRef} selectRealEstateId={selectRealEstateId} parentRow={currentRow} showType={'search'} />
            </Modal>
        </Drawer>
    );
};

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