import React, { useState, useEffect } from 'react';
import {Table, Button, Spin, Radio, DatePicker, Select, Form, Modal} from 'antd';
import {getServiceStatPage} from "../../api/statistical";
import type { RadioChangeEvent } from 'antd';
import {dictionary} from "../../api/dict";
import {serverUrl} from "../../api/axios";

interface Enterprise {
    key: string;
    policyNumber: string;
    insuranceName: string;
    serviceStatusName: string;
    remarks: string;
}

interface FormData {
    num: number;
    page: number;
}

const App: React.FC = () => {

    const [data, setData] = useState<Enterprise[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [query, setQuery] = useState<FormData | null>(null);
    const [total, setTotal] = useState<number | null>(0);
    const [dictData, setDictData] = useState<any>([]);
    const [form] = Form.useForm();

    useEffect(() => {
        const query = {page: 1, num: 20};
        setQuery(query);
        getListApi({}, query.page, query.num)
        dictionary('service_status').then((res) => {
            if(res.data){
                const formattedData = res.data.map((item: { dictValue: any; dictKey: any; }) => ({
                    label: item.dictValue,
                    value: item.dictKey
                }));
                setDictData(formattedData)
            }
        })
    }, []);

    const columns: any = [
        {
            title: '序号',
            dataIndex: 'key',
            width: 50,
            align: 'center',
            render: (text: string, record: any, index: number) => index + 1
        },
        {
            title: '保单号',
            dataIndex: 'policyNumber',
            align: 'center',
            key: 'policyNumber',
        },
        {
            title: '归属中支',
            dataIndex: 'insuranceName',
            align: 'center',
            key: 'insuranceName',
        },
        {
            title: '事故预防状态',
            dataIndex: 'serviceStatusName',
            align: 'center',
            key: 'serviceStatusName',
        },
        {
            title: '备注',
            dataIndex: 'remarks',
            align: 'center',
            key: 'remarks',
        }
    ];

    // 多少每页
    const selectChange = (page: number, num: number) => {
        const query = { page, num }
        setQuery(query);
        getListApi({}, query.page, query.num)
    }

    // 条数切换
    const changePage = (current: number, pageSize?: number) => {
        const query = { page: current, num: pageSize || 20 }
        setTimeout(() => {
            setQuery(query);
            getListApi({}, query.page, query.num)
        }, 0)
    }

    // 列表接口
    const getListApi = (formData: object, page: number, num: number) => {
        setLoading(true);
        var formObj = JSON.parse(JSON.stringify(formData));
        getServiceStatPage(formObj, page, num).then(res => {
            setData(res.data.records);
            setTotal(res.data.total);
            setLoading(false);
        }).catch(() => { })
    }

    const onChange = (e: RadioChangeEvent) => {
        console.log(`radio checked:${e.target.value}`);
    };

    const onReset = () => {
        const form = formRef.current;
        form.resetFields();
    };

    const formRef = React.createRef<any>();

    const { RangePicker } = DatePicker;

    const onFinish = (values: object) => {
        const form = formRef.current;
        const safeQuery = {page: 1, num: query? query.num : 20};
        setQuery(safeQuery);
        getListApi({
            dateFilter: form.getFieldValue('dateFilter'),
            startDate: form.getFieldValue('selectDateTime') ? formatDate(form.getFieldValue('selectDateTime')[0]) : null,
            doneDate: form.getFieldValue('selectDateTime') ? formatDate(form.getFieldValue('selectDateTime')[1]) : null,
            serviceStatus: form.getFieldValue('serviceStatus')
        }, safeQuery.page, safeQuery.num)
    }

    const goExport = () => {
        showModal();
    }

    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const formatDate = (dateString: string | number | Date) => {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        // const hours = String(date.getHours()).padStart(2, '0');
        // const minutes = String(date.getMinutes()).padStart(2, '0');
        // const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }


    const handleOk = () => {
        const params = {};
        const dateFilter = form.getFieldValue('dateFilter');
        if (dateFilter) {
            params['dateFilter'] = dateFilter;
        }
        const selectDateTime = form.getFieldValue('selectDateTime');
        if (selectDateTime && selectDateTime[0]) {
            console.log(selectDateTime)
            params['startDate'] = formatDate(selectDateTime[0]);
        }
        if (selectDateTime && selectDateTime[1]) {
            params['doneDate'] = formatDate(selectDateTime[1]);
        }
        const serviceStatus = form.getFieldValue('serviceStatus');
        if (serviceStatus) {
            params['serviceStatus'] = serviceStatus;
        }
        const urlParams = new URLSearchParams(params).toString();
        window.open(serverUrl + `./ex/statistics/exportServiceStatList?` + urlParams);
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    return (
        <div className="container">
            <div>
                <div className="header-filter">
                    <div className="list-filter" style={{display: 'flex', padding: 15}}>
                    <Form
                        form={form}
                        ref={formRef}
                        className="filter"
                        layout="inline"
                        name="basic"
                        onFinish={onFinish}
                    >
                        <Form.Item label="" name="dateFilter">
                            <Radio.Group onChange={onChange}>
                                <Radio.Button value="lastWeek">近一周</Radio.Button>
                                <Radio.Button value="lastMonth">近一月</Radio.Button>
                                <Radio.Button value="last3Months">近三月</Radio.Button>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label="保单数据日期" name="selectDateTime">
                            <RangePicker style={{ width: 300 }} onChange={(value, dateString) => {}}/>
                        </Form.Item>
                        <Form.Item label="事故预防状态" name="serviceStatus">
                            <Select
                                style={{ width: 280 }}
                                allowClear
                                options={ dictData }
                                placeholder="全部"
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button htmlType="button" onClick={onReset}>
                                重置
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">查询</Button>
                        </Form.Item>
                    </Form>
                </div>
                </div>
                <Button type="primary" style={{ marginBottom: 10, float: 'right' }} onClick={goExport}>导出</Button>
                {loading ? (
                    <Spin tip="Loading..." />
                ) : (
                    <Table
                        dataSource={data}
                        columns={columns}
                        rowKey="key"
                        loading={loading}
                        bordered={true}
                        size={'small'}
                        pagination={{
                            total: total || 0,
                            current: query?.page || 1,
                            pageSize: query?.num || 10,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            showTotal: total => `共 ${total} 条`,
                            onShowSizeChange: selectChange,
                            onChange: changePage
                        }}
                        scroll={{ y: 500 }}
                        sticky
                    />
                )}
            </div>
            <Modal title="提示" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} centered width={400}>
                <p>确定要导出文件？</p>
            </Modal>
        </div>
    );
};

export default App;
