import React, {useState, useEffect} from 'react';
import {Table, Button, Spin, Descriptions, Divider, message, Input} from 'antd';
import {getEnterpriseArchives} from 'api/statistical'

import {downPdf} from 'utils/exportPdf';

interface CustomerRetentionProps {
    customer: any;
}

interface Item {
    key: string;
    label: string;
    children: any;
    span?: number;
    policyCoverageData?: any;
}

interface PolicyItem {
    baseData: any,
    policyCoverageList: any,
    hivePolicyInnerCoInsurerList: any
}

interface HiveClaimStatistics {
    key: string;
    title: string;
    children: any;
    span?: number;
}

interface PolicyServiceItem {
    policyNumber: string,
    accidentPreventionList: any,
    riskList: any,
    hazardInvestigationList: any,
}


const EnterpriseFile: React.FC<CustomerRetentionProps> = ({ customer }) => {
    const [loading, setLoading] = useState<boolean>(false);
    const [items, setItems] = useState<Item[]>([]);
    const [items2, setItems2] = useState<PolicyItem[]>([]);
    const [items3, setItems3] = useState<HiveClaimStatistics[][]>([]);
    const [items4, setItems4] = useState<PolicyServiceItem[]>([]);
    const [downloadStat, setDownloadStat] = useState<boolean>(false);
    useEffect(() => {
        setLoading(true);
        message.open({
            type: 'loading',
            content: '数据加载中..',
            duration: 0,
        });
        getEnterpriseArchives({ customerId: customer.customerId}).then(res => {
            var baseData = [
                {
                    key: 'customerNo',
                    label: '客户编号',
                    children: res.data.customerNo
                },
                {
                    key: 'type',
                    label: '企业类型',
                    children: res.data.typeName
                },
                {
                    key: 'socialCreditCode',
                    label: '统一社会信用代码',
                    children: res.data.socialCreditCode
                },
                {
                    key: 'legalPerson',
                    label: '法定代表人',
                    span: 2,
                    children: res.data.legalPerson
                },
                {
                    key: 'contacts',
                    label: '联系人',
                    children: res.data.contacts
                },
                {
                    key: 'email',
                    label: '电子邮箱',
                    children: res.data.email
                },
                {
                    key: 'contactsPhone',
                    label: '联系电话',
                    children: res.data.contactsPhone
                },
                {
                    key: 'typePname',
                    label: '行业分类',
                    children: res.data.typePname
                },
                {
                    key: 'businessScope',
                    label: '许可范围',
                    span: 2,
                    children: res.data.businessScope
                },
                {
                    key: 'orgRegistrationAddress',
                    label: '注册地址',
                    children: res.data.orgRegistrationAddress
                }];
            setItems(baseData);
            let policyArr = [];
            for (var index = 0; index < res.data.policyList.length; index ++) {
                let policyCoverageList = [];
                for (var cIndex = 0; cIndex < res.data.policyList[index].policyCoverageList.length; cIndex ++) {
                    policyCoverageList.push(res.data.policyList[index].policyCoverageList[cIndex])
                }
                let hivePolicyInnerCoInsurerList = [];
                for (var hIndex = 0; hIndex < res.data.policyList[index].hivePolicyInnerCoInsurerList.length; hIndex ++) {
                    hivePolicyInnerCoInsurerList.push(res.data.policyList[index].hivePolicyInnerCoInsurerList[hIndex])
                }
                policyArr.push({
                    baseData:[{
                        key: 'policyNumber',
                        label: '保单号',
                        children: res.data.policyList[index].policyNumber
                    },
                        {
                            key: 'insurCustomerName',
                            label: '投保人',
                            children: res.data.policyList[index].insurCustomerName
                        },
                        {
                            key: 'customerName',
                            label: '被保人',
                            children: res.data.policyList[index].customerName
                        },
                        {
                            key: 'duePremium',
                            label: '保费',
                            span: 2,
                            children: res.data.policyList[index].duePremium
                        },
                        {
                            key: 'startDate',
                            label: '起保日期',
                            children: res.data.policyList[index].startDate
                        },
                        {
                            key: 'doneDate',
                            label: '终保日期',
                            children: res.data.policyList[index].doneDate
                        },
                        {
                            key: 'policyStatusName',
                            label: '保单状态',
                            children: res.data.policyList[index].policyStatusName
                        },
                        {
                            key: 'premiumRate',
                            label: '保单费率',
                            children: res.data.policyList[index].premiumRate
                        },
                        {
                            key: 'sumInsured',
                            label: '累计责任限额',
                            children:res.data.policyList[index].sumInsured
                        }],
                    policyCoverageList: policyCoverageList,
                    hivePolicyInnerCoInsurerList: hivePolicyInnerCoInsurerList
                });
            }
            setItems2(policyArr);

            let hiveClaimArr = [];
            for (var index2 = 0; index2 < res.data.hiveClaimStatisticsList.length; index2 ++) {
                const hiveClaim = [
                    {
                        title: '保单号',
                        key: 'policyno',
                        children: res.data.hiveClaimStatisticsList[index2].policyno
                    },
                    {
                        title: '报案时间',
                        key: 'reporttime',
                        children: res.data.hiveClaimStatisticsList[index2].reporttime
                    },
                    {
                        title: '立案时间',
                        key: 'claimtime',
                        children: res.data.hiveClaimStatisticsList[index2].claimtime
                    },
                    {
                        title: '任务节点',
                        key: 'tasktype',
                        children: res.data.hiveClaimStatisticsList[index2].tasktype
                    },
                    {
                        title: '估损金额',
                        key: 'claimloss',
                        children: res.data.hiveClaimStatisticsList[index2].claimloss
                    },
                    {
                        title: '定损总金额',
                        key: 'sumlossapproval',
                        children: res.data.hiveClaimStatisticsList[index2].sumlossapproval
                    },
                    {
                        title: '从业人员人身伤亡定损金额',
                        key: 'peoplelossapproval',
                        children: res.data.hiveClaimStatisticsList[index2].peoplelossapproval
                    },
                    {
                        title: '医疗救护费用定损金额',
                        key: 'medicsumapprv',
                        children: res.data.hiveClaimStatisticsList[index2].medicsumapprv
                    },
                    {
                        title: '第三者人身伤亡定损金额',
                        key: 'ossapproval',
                        children: res.data.hiveClaimStatisticsList[index2].ossapproval
                    },
                    {
                        title: '事故鉴定费用定损金额',
                        key: 'accidentsumaprv',
                        children: res.data.hiveClaimStatisticsList[index2].accidentsumaprv
                    },
                    {
                        title: '第三者财产损失定损金额',
                        key: 'lossapproval',
                        children: res.data.hiveClaimStatisticsList[index2].lossapproval
                    },
                    {
                        title: '法律诉讼费用定损金额',
                        key: 'lawsumapprv',
                        children: res.data.hiveClaimStatisticsList[index2].lawsumapprv
                    },
                    {
                        title: '事故抢险救援费用定损金额',
                        key: 'accidentrssumapprv',
                        children: res.data.hiveClaimStatisticsList[index2].accidentrssumapprv
                    },
                    {
                        title: '其他费用定损金额',
                        key: 'othersumapprv',
                        children: res.data.hiveClaimStatisticsList[index2].othersumapprv
                    },
                    {
                        title: '赔付总金额',
                        key: 'totalamtcharg',
                        children: res.data.hiveClaimStatisticsList[index2].totalamtcharg
                    },
                    {
                        title: '赔付时间',
                        key: 'bankpaytime',
                        children: res.data.hiveClaimStatisticsList[index2].bankpaytime
                    },
                    {
                        title: '决案时间',
                        key: 'endcasedate',
                        children: res.data.hiveClaimStatisticsList[index2].endcasedate
                    },
                    {
                        title: '从业人员人身伤亡赔付金额',
                        key: 'peoplemdiesumcharg',
                        children: res.data.hiveClaimStatisticsList[index2].peoplemdiesumcharg
                    },
                    {
                        title: '医疗救护费用赔付金额',
                        key: 'medicsumcharg',
                        children: res.data.hiveClaimStatisticsList[index2].medicsumcharg
                    },
                    {
                        title: '第三者人身伤亡赔付金额',
                        key: 'tempcharg',
                        children: res.data.hiveClaimStatisticsList[index2].lossinjurycharg
                    },
                    {
                        title: '事故鉴定费用赔付金额',
                        key: 'accidentrssumcharg',
                        children: res.data.hiveClaimStatisticsList[index2].accidentrssumcharg
                    },
                    {
                        title: '第三者财产损失赔付金额',
                        key: 'losscharg',
                        children: res.data.hiveClaimStatisticsList[index2].losscharg
                    },
                    {
                        title: '法律诉讼费用赔付金额',
                        key: 'lawsumcharg',
                        children: res.data.hiveClaimStatisticsList[index2].lawsumcharg
                    },
                    {
                        title: '事故抢险救援费用赔付金额',
                        key: 'hiveClaim',
                        children: res.data.hiveClaimStatisticsList[index2].hiveClaim
                    },
                    {
                        title: '其他费用赔付金额',
                        key: 'othersumcharg',
                        children: res.data.hiveClaimStatisticsList[index2].othersumcharg
                    }
                ];
                hiveClaimArr.push(hiveClaim);
            }
            setItems3(hiveClaimArr);

            let policyServiceArr = [];
            for (var index3 = 0; index3 < res.data.serviceStatisticsList.length; index3 ++) {
                let accidentPreventionList = [];
                for (var aIndex = 0; aIndex < res.data.serviceStatisticsList[index3].accidentPreventionList.length; aIndex ++) {
                    accidentPreventionList.push(res.data.serviceStatisticsList[index3].accidentPreventionList[aIndex])
                }
                let riskList = [];
                for (var rIndex = 0; rIndex < res.data.serviceStatisticsList[index3].riskList.length; rIndex ++) {
                    riskList.push(res.data.serviceStatisticsList[index3].riskList[rIndex])
                }
                let hazardInvestigationList = [];
                for (var sIndex = 0; sIndex < res.data.serviceStatisticsList[index3].hazardInvestigationList.length; sIndex ++) {
                    hazardInvestigationList.push(res.data.serviceStatisticsList[index3].hazardInvestigationList[sIndex])
                }
                policyServiceArr.push({
                    policyNumber: res.data.serviceStatisticsList[index3].policyNumber,
                    accidentPreventionList: accidentPreventionList,
                    riskList: riskList,
                    hazardInvestigationList: hazardInvestigationList
                })
            }
            setItems4(policyServiceArr);

            message.destroy();
            setLoading(false);
        }).catch(() => {})
    }, []);

    const columnsPolicyCoverage = [
        {
            title: '条款代码',
            dataIndex: 'clausecode',
            key: 'clausecode',
        },
        {
            title: '条款类型',
            dataIndex: 'coverageType',
            key: 'coverageType',
        },
        {
            title: '条款名称',
            dataIndex: 'productElementName',
            key: 'productElementName',
        },
        {
            title: '责任限额(元)',
            dataIndex: 'sumInsured',
            key: 'sumInsured',
        }
    ];

    const columnsHivePolicyInnerCoInsurer = [
        {
            title: '联保机构',
            dataIndex: 'orgName',
            key: 'orgName',
        },
        {
            title: '联保份额',
            dataIndex: 'shareRate',
            key: 'shareRate',
        },
    ];

    const columnsAccidentPrevention = [
        {
            title: '服务时间',
            dataIndex: 'completedAt',
            key: 'completedAt',
        },
        {
            title: '服务名称',
            dataIndex: 'serviceName',
            key: 'serviceName',
        },
        {
            title: '被服务对象',
            dataIndex: 'serviceObjectName',
            key: 'serviceObjectName',
        },
        {
            title: '服务分类',
            dataIndex: 'serviceRange',
            key: 'serviceRange',
        },
        {
            title: '服务机构',
            dataIndex: 'executedOrganName',
            key: 'executedOrganName',
        },
        {
            title: '服务报告',
            dataIndex: 'uploadStatus',
            key: 'uploadStatus',
        },
    ];

    const columnsRisk = [
        {
            title: '风险编号',
            dataIndex: 'riskNumber',
            key: 'riskNumber',
        },
        {
            title: '风险名称',
            dataIndex: 'riskName',
            key: 'riskName',
        },
        {
            title: '风险描述',
            dataIndex: 'riskontent',
            key: 'riskontent',
        },
        {
            title: '场所/部位',
            dataIndex: 'discoveredAddress',
            key: 'discoveredAddress',
        },
        {
            title: '风险等级',
            dataIndex: 'riskGrade',
            key: 'riskGrade',
        },
        {
            title: '管控状态',
            dataIndex: 'status',
            key: 'status',
        },
        {
            title: '发现时间',
            dataIndex: 'discoveredAt',
            key: 'discoveredAt',
        },
    ];

    const columnsHazardInvestigation = [
        {
            title: '隐患编号',
            dataIndex: 'hiddenNumber',
            key: 'hiddenNumber',
        },
        {
            title: '隐患描述',
            dataIndex: 'description',
            key: 'description',
        },
        {
            title: '隐患类型',
            dataIndex: 'hiddenDangerType',
            key: 'hiddenDangerType',
        },
        {
            title: '隐患分类',
            dataIndex: 'dangerTypeName',
            key: 'dangerTypeName',
        },
        {
            title: '隐患等级',
            dataIndex: 'riskGrade',
            key: 'riskGrade',
        },
        {
            title: '发现时间',
            dataIndex: 'discoveredAt',
            key: 'discoveredAt',
        },
        {
            title: '整改状态',
            dataIndex: 'correctionStatus',
            key: 'correctionStatus',
        },
    ];
    const handleCapture = () => {
        setDownloadStat(true);
        setLoading(true);
        setTimeout(() => {
            downPdf("企业档案", "main-customer-htm")
                .then(() => {
                    console.log("PDF已经生成并保存！");
                    setLoading(false);
                    setDownloadStat(false);
                })
                .catch((error: any) => {
                    console.error("生成PDF时发生错误: ", error);
                    setLoading(false);
                    setDownloadStat(false);
                });
        }, 7000);
        // }, 200);
    };

    return (
        <div>
            <div style={{ height: 40 }}>
                <Button type="primary" style={{ float: 'right' }} onClick={handleCapture} loading={loading}>PDF下载</Button>
            </div>
            <div className="main-customer-htm">
                <div style={{
                    height: '106px',
                    border: '1px solid rgba(220, 228, 248, 0.29)',
                    borderRadius: '2px',
                    backgroundColor: 'rgba(220, 228, 248, 0.29)',
                    marginBottom: '20px',
                    justifyContent: 'center',
                    display: 'flex'}}>
                    <div style={{
                        fontSize: 'xx-large',
                        textAlign: 'center',
                        display: 'flex',
                        alignItems: 'center'
                    }}>{customer.customerName}企业档案</div></div>
                <div>
                    <div className={downloadStat? 'asd': 'header-filter'} style={downloadStat?{}:{width: '99%', marginLeft: '0.5%'}}>
                        <div className={downloadStat? 'asd': 'list-filter'} style={downloadStat?{}:{display: 'flex', padding: 7}}>
                            <Descriptions title="企业基本信息">
                                    {items.map(item => (
                                        <Descriptions.Item label={item.label} key={item.key}>
                                            {item.children}
                                        </Descriptions.Item>
                                    ))}
                            </Descriptions>
                        </div>
                    </div>
                    <div className={downloadStat? 'asd': 'header-filter'} style={downloadStat?{}:{width: '99%', marginLeft: '0.5%'}}>
                        <div className={downloadStat? 'asd': 'list-filter'} style={downloadStat?{}:{padding: 7}}>
                            <div className="ant-descriptions-header">
                                <div className="ant-descriptions-title">保单信息</div>
                            </div>
                            {items2.map(pItem => (
                                <div style={{border: '1px solid #dce4f84a',
                                    borderRadius: 5,
                                    padding: 10,
                                    backgroundColor: '#dce4f84a',
                                    marginTop: 10}}>
                                    <div style={{marginBottom: 20, color: '#4F85EA', fontWeight: 600}}>基本信息</div>
                                    <Descriptions>
                                        {pItem.baseData.map((item: { label: string, key: string, children: string }) => (
                                            <Descriptions.Item label={item.label} key={item.key}>
                                                {item.children}
                                            </Descriptions.Item>
                                        ))}
                                    </Descriptions>
                                    <div style={{marginBottom: 20, color: '#4F85EA', fontWeight: 600}}>责任条款</div>
                                    <Table
                                        className={downloadStat ? 'special-class' : 'regular-class'}
                                        dataSource={pItem.policyCoverageList}
                                        columns={columnsPolicyCoverage}
                                        bordered={true}
                                        size={'small'}
                                        rowKey="key"
                                        scroll={{ y: 300 }}
                                        pagination={false}
                                    />
                                    <br/>
                                    <div style={{marginBottom: 20, color: '#4F85EA', fontWeight: 600}}>联保信息</div>
                                    <Table
                                        className={downloadStat ? 'special-class' : 'regular-class'}
                                        dataSource={pItem.hivePolicyInnerCoInsurerList}
                                        columns={columnsHivePolicyInnerCoInsurer}
                                        bordered={true}
                                        size={'small'}
                                        rowKey="key"
                                        scroll={{ y: 300 }}
                                        pagination={false}
                                    />
                                    <br />
                                </div>
                            ))}
                        </div>
                    </div>
                    <div className={downloadStat? 'asd': 'header-filter'} style={downloadStat?{}:{width: '99%', marginLeft: '0.5%'}}>
                        <div className={downloadStat? 'asd': 'list-filter'} style={downloadStat?{}:{padding: 7}}>
                            <div className="ant-descriptions-header">
                                <div className="ant-descriptions-title">理赔记录</div>
                            </div>
                            {items3.map((item3, index) => (
                                <div style={{border: '1px solid #dce4f84a',
                                    borderRadius: 5,
                                    padding: 10,
                                    backgroundColor: '#dce4f84a'}}>
                                    {(index === 0 || item3[0].children !== items3[index - 1][0].children) && (
                                        <div style={{ marginBottom: 20, fontWeight: 600 }}>
                                            保单号： {item3[0].children}
                                        </div>
                                    )}
                                    <div style={{marginBottom: 20, color: '#4F85EA', fontWeight: 600}}>基本信息</div>
                                    <Descriptions>
                                        {item3.slice(1, 4).map(tim => (
                                            <Descriptions.Item label={tim.title} key={tim.key}>
                                                {tim.children}
                                            </Descriptions.Item>
                                        ))}
                                    </Descriptions>
                                    <div style={{marginBottom: 20, color: '#4F85EA', fontWeight: 600}}>定损信息</div>
                                    <Descriptions>
                                        {item3.slice(5, 13).map(tim => (
                                            <Descriptions.Item label={tim.title} key={tim.key}>
                                                {tim.children}
                                            </Descriptions.Item>
                                        ))}
                                    </Descriptions>
                                    <div style={{marginBottom: 20, color: '#4F85EA', fontWeight: 600}}>赔付信息</div>
                                    <Descriptions>
                                        {item3.slice(14, 24).map(tim => (
                                            <Descriptions.Item label={tim.title} key={tim.key}>
                                                {tim.children}
                                            </Descriptions.Item>
                                        ))}
                                    </Descriptions>
                                </div>
                            ))}
                        </div>
                    </div>
                    <div className={downloadStat? 'asd': 'header-filter'} style={downloadStat?{}:{width: '99%', marginLeft: '0.5%'}}>
                        <div className={downloadStat? 'asd': 'list-filter'} style={downloadStat?{}:{padding: 7}}>
                            <div className="ant-descriptions-header">
                                <div className="ant-descriptions-title">服务记录</div>
                            </div>
                            {items4.map((item4, index) => (
                                <div style={{border: '1px solid #dce4f84a',
                                    borderRadius: 5,
                                    padding: 10,
                                    backgroundColor: '#dce4f84a'}}>
                                    <div style={{marginBottom: 20, fontWeight: 600}}>保单号： {item4.policyNumber}</div>
                                    <div style={{marginBottom: 20, color: '#4F85EA', fontWeight: 600}}>事故预防服务</div>
                                    <Table
                                        className={downloadStat ? 'special-class' : 'regular-class'}
                                        dataSource={item4.accidentPreventionList}
                                        columns={columnsAccidentPrevention}
                                        bordered={true}
                                        size={'small'}
                                        scroll={{ y: 300 }}
                                        rowKey="key"
                                        pagination={false}
                                    />
                                    <br/>
                                    <div style={{marginBottom: 20, color: '#4F85EA', fontWeight: 600}}>风险辨识</div>
                                    <Table
                                        className={downloadStat ? 'special-class' : 'regular-class'}
                                        dataSource={item4.riskList}
                                        columns={columnsRisk}
                                        bordered={true}
                                        size={'small'}
                                        scroll={{ y: 300 }}
                                        pagination={false}
                                    />
                                    <br/>
                                    <div style={{marginBottom: 20, color: '#4F85EA', fontWeight: 600}}>隐患排查</div>
                                    <Table
                                        className={downloadStat ? 'special-class' : 'regular-class'}
                                        dataSource={item4.hazardInvestigationList}
                                        columns={columnsHazardInvestigation}
                                        bordered={true}
                                        size={'small'}
                                        scroll={{ y: 300 }}
                                        rowKey="key"
                                        pagination={false}
                                    />
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default EnterpriseFile;
