import {Button, Divider, Flex, Form, Input, Modal, Radio, Space} from "antd";
import {useEffect, useState} from "react";
import {listDictionary, IDictionary, get, put} from "../../util/AjaxUtils.ts";
import useMessage from "antd/es/message/useMessage";
import InvoiceInfoList from "./info/InvoiceInfoList.tsx";
import InvoiceOrderList from "./order/InvoiceOrderList.tsx";
import useModal from "antd/es/modal/useModal";

type FormFieldType = {
    invoiceTitle: string;
    invoiceNo: string;
    invoiceAddress: string;
    invoicePhone: string;
    invoiceAccount: string;
    invoiceBank: string;
    content: string;
    rate: string;
    type: string;
    orderIds: string[];
    invoiceNote: string;
    isSaveInvoiceInfo: boolean;
    invoiceAmount: number;
}

type EditProps = {
    invoiceId: string;
    handleOk: () => void;
    handleCancel: () => void;
}

export default function InvoiceEdit(props: EditProps) {
    const [messageApi, messageContext] = useMessage();
    const [modal, modalContext] = useModal();
    const [form] = Form.useForm<FormFieldType>();
    const [contentArray, setContentArray] = useState<IDictionary[]>([]);
    const [rateArray, setRateArray] = useState<IDictionary[]>([]);
    const [typeArray, setTypeArray] = useState<IDictionary[]>([]);
    const [isInvoiceInfoListOpen, setIsInvoiceInfoListOpen] = useState(false);
    const [isInvoiceOrderListOpen, setIsInvoiceOrderListOpen] = useState(false);
    const [orderAmount, setOrderAmount] = useState('0');

    useEffect(() => {
        if(!props.invoiceId) {
            return;
        }
        // 开票内容
        listDictionary('e0251d55-cd52-4f57-be92-b2bef8a6dd62', messageApi).then((data) => {
            setContentArray([...data]);
        })
        // 开票税率
        listDictionary('b67d5208-db1d-4d0e-99de-cc22d9d50041', messageApi).then((data) => {
            setRateArray([...data]);
        })
        // 开票类型
        listDictionary('e4808c45-64ee-42fa-a413-a470fbdc0aea', messageApi).then((data) => {
            setTypeArray([...data]);
        })
        get<FormFieldType>({
            messageApi,
            url: `/api/invoice/get/${props.invoiceId}`,
            onSuccess({data}) {
                form.setFieldsValue(data);
                setOrderAmount((data.invoiceAmount / 100).toFixed(2));
            }
        })
    }, []);

    return (
        <>
            {messageContext}
            {modalContext}
            <Form
                name="basic"
                initialValues={{isSaveInvoiceInfo: 0}}
                form={form}
                onFinish={(values) => {
                    modal.confirm({
                        title: '提示',
                        content: '确定提交吗？',
                        okText: '确定',
                        cancelText: '取消',
                        okButtonProps: {
                            style: {
                                backgroundColor: 'val(--color-primary)'
                            }
                        },
                        onOk: () => {
                            put<any>({
                                messageApi,
                                url: `/api/invoice/update/${props.invoiceId}`,
                                body: values,
                                onSuccess() {
                                    messageApi.success('提交成功');
                                    props.handleOk();
                                }
                            })
                        }
                    });
                }}
            >
                <Divider orientation="left" plain>开票信息</Divider>
                <table className="pay-table">
                    <colgroup>
                        <col width="120"/>
                        <col/>
                    </colgroup>
                    <tbody>
                    <tr>
                        <td colSpan={2}>
                            <Button type="link" onClick={() => {
                                setIsInvoiceInfoListOpen(true);
                            }}>选择开票信息</Button>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">公司名称 *</td>
                        <td>
                            <Form.Item
                                name="invoiceTitle"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请输入公司名称'}]}
                            >
                                <Input placeholder="请输入公司名称"/>
                            </Form.Item>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">纳税人识别号 *</td>
                        <td>
                            <Form.Item
                                name="invoiceNo"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请输入纳税人识别号'}]}
                            >
                                <Input placeholder="请输入纳税人识别号"/>
                            </Form.Item>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">公司地址 *</td>
                        <td>
                            <Form.Item
                                name="invoiceAddress"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请输入公司地址'}]}
                            >
                                <Input placeholder="请输入公司地址"/>
                            </Form.Item>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">联系电话 *</td>
                        <td>
                            <Form.Item
                                name="invoicePhone"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请输入联系电话'}]}
                            >
                                <Input placeholder="请输入联系电话"/>
                            </Form.Item>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">开户行 *</td>
                        <td>
                            <Form.Item
                                name="invoiceAccount"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请输入开户行'}]}
                            >
                                <Input placeholder="请输入开户行"/>
                            </Form.Item>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">开户行账号 *</td>
                        <td>
                            <Form.Item
                                name="invoiceBank"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请输入开户行账号'}]}
                            >
                                <Input placeholder="请输入开户行账号"/>
                            </Form.Item>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">开票内容 *</td>
                        <td>
                            <Form.Item
                                name="content"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请选择开票内容'}]}
                            >
                                <Radio.Group>
                                    <Space direction="vertical">
                                        {contentArray.map(item => <Radio value={item.dataName}
                                                                         key={item.dataId}>{item.dataName}</Radio>)}
                                    </Space>
                                </Radio.Group>
                            </Form.Item>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">开票税率 *</td>
                        <td>
                            <Form.Item
                                name="rate"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请选择开票税率'}]}
                            >
                                <Radio.Group>
                                    {rateArray.map(item => <Radio value={item.dataName}
                                                                  key={item.dataId}>{item.dataName}</Radio>)}
                                </Radio.Group>
                            </Form.Item>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">发票类型 *</td>
                        <td>
                            <Form.Item
                                name="type"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请选择发票类型'}]}
                            >
                                <Radio.Group>
                                    <Space direction="vertical">
                                        {typeArray.map(item => <Radio value={item.dataName}
                                                                      key={item.dataId}>{item.dataName}</Radio>)}
                                    </Space>
                                </Radio.Group>
                            </Form.Item>
                        </td>
                    </tr>


                    <tr>
                        <td className="table-label">保存开票信息 *</td>
                        <td>
                            <Form.Item
                                name="isSaveInvoiceInfo"
                                style={{marginBottom: '0'}}
                            >
                                <Radio.Group>
                                    <Radio value={0}>否</Radio>
                                    <Radio value={1}>是</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </td>
                    </tr>
                    </tbody>
                </table>
                <Divider orientation="left" plain>开票内容</Divider>
                <table className="pay-table">
                    <colgroup>
                        <col width="120"/>
                        <col/>
                    </colgroup>
                    <tbody>
                    <tr>
                        <td className="table-label">开票金额 *</td>
                        <td>
                            <Form.Item
                                name="orderIds"
                                style={{marginBottom: '0'}}
                                rules={[{required: true, message: '请选择开票金额'}]}
                            >
                                <div>
                                    <span>￥</span>
                                    <span style={{fontSize: '20px', fontWeight: 'bold'}}>{orderAmount}</span>
                                    <Button type="link" size="small" onClick={() => {
                                        setIsInvoiceOrderListOpen(true);
                                    }}>请选择需要开票的订单</Button>
                                </div>
                            </Form.Item>
                        </td>
                    </tr>
                    <tr>
                        <td className="table-label">开票备注</td>
                        <td>
                            <Form.Item
                                name="invoiceNote"
                                style={{marginBottom: '0'}}
                            >
                                <Input.TextArea placeholder="请输入开票备注" rows={4}/>
                            </Form.Item>
                        </td>
                    </tr>
                    </tbody>
                </table>
                <Form.Item style={{marginBottom: '0'}}>
                    <Flex justify="center" style={{marginTop: '15px'}}>
                        <Space>
                            <Button type="primary" htmlType="submit" style={{
                                backgroundColor: 'var(--color-primary)'
                            }}>提交</Button>
                            <Button type="default" onClick={() => {
                                props.handleCancel();
                            }}>返回</Button>
                        </Space>
                    </Flex>
                </Form.Item>
            </Form>
            <Modal open={isInvoiceInfoListOpen}
                   title="开票信息"
                   width={1000}
                   footer={false}
                   onCancel={() => setIsInvoiceInfoListOpen(false)}
            >
                <InvoiceInfoList
                    handleOk={(selectedInvoice) => {
                        form.setFieldsValue({
                            invoiceTitle: selectedInvoice.invoiceTitle,
                            invoiceNo: selectedInvoice.invoiceNo,
                            invoiceAddress: selectedInvoice.invoiceAddress,
                            invoicePhone: selectedInvoice.invoicePhone,
                            invoiceAccount: selectedInvoice.invoiceAccount,
                            invoiceBank: selectedInvoice.invoiceBank
                        });
                        setIsInvoiceInfoListOpen(false);
                    }}
                    handleCancel={() => {
                        setIsInvoiceInfoListOpen(false);
                    }}
                />
            </Modal>
            <Modal open={isInvoiceOrderListOpen}
                   title="开票订单"
                   width={1000}
                   footer={false}
                   onCancel={() => setIsInvoiceOrderListOpen(false)}
            >
                <InvoiceOrderList
                    selectedOrderIds={form.getFieldValue('orderIds')}
                    handleOk={(selectedOrders) => {
                        let totalAmount = 0;
                        const orderIds: string[] = [];
                        selectedOrders.forEach((item) => {
                            totalAmount += item.totalAmount;
                            orderIds.push(item.orderId);
                        });
                        setOrderAmount((totalAmount / 100).toFixed(2));
                        setIsInvoiceOrderListOpen(false);
                        form.setFieldValue('orderIds', orderIds);
                    }}
                    handleCancel={() => {
                        setIsInvoiceOrderListOpen(false);
                    }}
                />
            </Modal>
        </>
    );
}