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 } from "antd";
import { connect } from "umi";
import { ProTable } from "@ant-design/pro-components";
import { handleGetAPPLYAPPROVEList, handleGetBILLDETAILList } from "@/pages/DigitalElectronics/service";
import moment from "moment";
import { encryptAES } from "@/utils/handleAes";

const { Text } = Typography;

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

interface ParamsType {
    showDetail: boolean;
    setShowDetail: (v: boolean) => void;
    parentRow: any;
    setParentRow: (v: any) => void;
}


const InvoiceDetail = ({ showDetail, setShowDetail, parentRow, setParentRow }: ParamsType) => {
    const formRef = useRef<FormInstance<any>>();
    // 明细表格默认隐藏的内容 
    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 detailColumns: any = [
        {
            title: <div style={{ textAlign: 'center' }}>款项名称</div>,
            align: 'center',
            width: 150,
            dataIndex: "ITEM_NAME"
        },
        {
            title: <div style={{ textAlign: 'center' }}>税务代码</div>,
            align: 'center',
            width: 150,
            dataIndex: "TABLE_NAME"
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品条码</div>,
            align: 'center',
            width: 150,
            dataIndex: "ITEM_ID"
        },
        {
            title: <div style={{ textAlign: 'center' }}>规格型号</div>,
            align: 'center',
            width: 150,
            dataIndex: "ITEM_RULE"
        },
        {
            title: <div style={{ textAlign: 'center' }}>计量单位</div>,
            align: 'center',
            width: 100,
            dataIndex: "ITEM_UNIT"
        },
        {
            title: <div style={{ textAlign: 'center' }}>数量</div>,
            align: 'right',
            width: 80,
            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: 'center',
            width: 80,
            dataIndex: "DUTY_PARAGRAPH",
            render: (_, record) => {
                return record?.DUTY_PARAGRAPH ? `${record?.DUTY_PARAGRAPH}%` : ""
            }
        },
        {
            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: <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
        }
    ];


    return (
        <Drawer
            width="70%"
            open={showDetail}
            title="票据详情"
            onClose={() => {
                setShowDetail(false);
                setParentRow(undefined);
            }}
            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="SERVERPARTSHOP_NAME" label="门店" readonly />
                        <ProFormText name="BILL_AMOUNT" label="除税开票金额" readonly />
                        <ProFormText name="BILL_DATE" label="申请日期" readonly />

                    </Col>

                    <Col span={8}>
                        <ProFormText name="SERIAL_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>
                        <ProTable
                            search={false}
                            columns={detailColumns}
                            bordered
                            request={async () => {
                                console.log('parentRowparentRowparentRow', parentRow);
                                const billDetail = await handleGetBILLDETAILList({
                                    SearchParameter: {
                                        BILL_ID: parentRow?.BILL_ID
                                    },
                                    PageIndex: 1,
                                    PageSize: 999999,
                                    SortStr: "BILLDETAIL_ID"
                                })
                                console.log('billDetailbillDetailbillDetail', billDetail);

                                if (billDetail && billDetail.length > 0) {
                                    return { data: billDetail, success: true }
                                }
                                return { data: [], success: true }
                            }}
                            columnsState={{
                                value: columnsStateMap,
                                onChange: setColumnsStateMap,
                            }}
                        />
                    </Space>
                </div>

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

                        <ProTable
                            search={false}
                            columns={approveColumns}
                            options={false}
                            bordered
                            request={async () => {
                                console.log('parentRowparentRowparentRow', parentRow);

                                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)
                                console.log('data', data);
                                if (data && data.length > 0) {
                                    return { data, success: true }
                                }
                                return { data: [], success: true }
                            }}
                        />
                    </Space>
                </div>

            </ProForm>
        </Drawer>
    );
};

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