import './proj-edit-step.css';
import {Breadcrumb, Cascader, Col, DatePicker, Flex, message, Modal, Row, Select, Spin} from "antd";
import locale from 'antd/es/date-picker/locale/zh_CN';
import {Link, useNavigate, useParams} from "react-router-dom";
import {useEffect, useState} from "react";
import {get, put} from "../../../util/AjaxUtils.ts";
import {Button, Form, Input} from 'antd';
import {AxiosResponse} from "axios";
import dayjs, {Dayjs} from 'dayjs';
import {ITree} from "../../../interfaces/dict/IDict.ts";

type FieldType = {
    authorName: string;
    authorIdCardType: string;
    authorIdCard: string;
    authorNation: string;
    authorProvince: string;
    authorEstablishDate: Dayjs;
};

interface Option {
    value?: string | number | null;
    label: React.ReactNode;
    children?: Option[];
    isLeaf?: boolean;
    id: string;
    pId: string;
}

export default function ProjEditStep4() {
    const nav = useNavigate();
    const pathParams = useParams();
    const [messageApi, contextHolder] = message.useMessage();
    const [form] = Form.useForm<FieldType>();
    const [loading, setLoading] = useState<boolean>(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [areaArray, setAreaArray] = useState<Option[]>([]);
    const height = window.innerHeight - 180;
    const dateFormat = 'YYYY年MM月DD日';

    const listArea = (pId: string) => {
        return new Promise<ITree[]>((resolve) => {
            get<ITree[]>({
                messageApi,
                url: '/api/area/list-area-ztree',
                config: {
                    params: {
                        id: pId
                    }
                },
                onSuccess({data}) {
                    resolve(data);
                }
            })
        })
    }

    useEffect(() => {
        get({
            messageApi,
            url: `/api/proj/get/edit-step4/${pathParams.projId}`,
            onSuccess({data}: AxiosResponse) {
                form.setFieldsValue({
                    authorName: data.authorName,
                    authorIdCardType: data.authorIdCardType ? data.authorIdCardType : 'BUSINESS_LICENSE',
                    authorIdCard: data.authorIdCard,
                    authorNation: data.authorNation ? data.authorNation : '中国',
                    authorProvince: data.authorProvince ? data.authorProvince.split(',') : '',
                    authorEstablishDate: dayjs(data.authorEstablishDate, 'YYYY-MM-DD'),
                })
            }
        })
        listArea('0').then(data => {
            const options: Option[] = data.map(item => {
                return {
                    value: item.name,
                    label: item.name,
                    isLeaf: !item.isParent,
                    id: item.id,
                    pId: item.pId
                }
            })
            setAreaArray(options);
        });
    }, [])

    return (
        <>
            {contextHolder}
            <Breadcrumb
                items={[
                    {title: <Link to={'/'}>首页</Link>},
                    {title: <Link to={'/proj-create'}>创建项目</Link>},
                    {title: <a onClick={() => {nav(-1)}}>编辑项目</a>},
                    {title: '著作人信息'},
                ]}
            />
            <div className="form-container" style={{height: `${height}px`}}>
                <div className="form-body">
                    <Form
                        name="basic"
                        form={form}
                        layout="vertical"
                        labelCol={{span: 8}}
                        wrapperCol={{span: 24}}
                        style={{width: '800px'}}
                        onFinish={() => {
                            setIsEditModalOpen(true);
                        }}
                        autoComplete="off"
                    >
                        <Row gutter={15}>
                            <Col span={12}>
                                <Form.Item<FieldType>
                                    label="姓名或公司名称"
                                    name="authorName"
                                    rules={[{required: true, message: '请输入姓名或公司名称'}]}
                                >
                                    <Input placeholder="请输入姓名或公司名称"/>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item<FieldType>
                                    label="成立日期"
                                    name="authorEstablishDate"
                                    rules={[{required: true, message: '请选择成立日期'}]}
                                >
                                    <DatePicker placeholder="请选择成立日期"
                                                format={dateFormat}
                                                locale={locale}
                                                style={{width: '100%'}}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={15}>
                            <Col span={12}>
                                <Form.Item<FieldType>
                                    label="证件类型"
                                    name="authorIdCardType"
                                    rules={[{required: true, message: '请选择证件类型'}]}
                                >
                                    <Select
                                        placeholder="请选择样证件类型"
                                        onChange={(value: string) => {
                                            console.log(`selected ${value}`);
                                        }}
                                        options={[
                                            {value: 'BUSINESS_LICENSE', label: '营业执照'},
                                            {value: 'ID_CARD', label: '身份证'},
                                        ]}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item<FieldType>
                                    label="证件号"
                                    name="authorIdCard"
                                    rules={[{required: true, message: '请输入证件号'}]}
                                >
                                    <Input placeholder="请输入证件号"/>
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={15}>
                            <Col span={12}>
                                <Form.Item<FieldType>
                                    label="国籍"
                                    name="authorNation"
                                    rules={[{required: true, message: '请选择国籍'}]}
                                >
                                    <Select
                                        placeholder="请选择国籍"
                                        options={[
                                            {value: '中国', label: '中国'},
                                        ]}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item<FieldType>
                                    label="省市"
                                    name="authorProvince"
                                    rules={[{required: true, message: '请选择省市'}]}
                                >
                                    <Cascader options={areaArray}
                                              loadData={(selectedOptions: Option[]) => {
                                                  const targetOption = selectedOptions[selectedOptions.length - 1];
                                                  listArea(targetOption.id).then(data => {
                                                      targetOption.children = data.map(item => {
                                                          return {
                                                              value: item.name,
                                                              label: item.name,
                                                              isLeaf: !item.isParent,
                                                              id: item.id,
                                                              pId: item.pId
                                                          }
                                                      });
                                                      setAreaArray([
                                                          ...areaArray
                                                      ])
                                                  });
                                              }}
                                              placeholder="请选择省市"
                                              changeOnSelect/>
                                </Form.Item>
                            </Col>
                        </Row>

                        <Form.Item wrapperCol={{span: 24}}>
                            <Flex align="center" justify="center" gap="large">
                                <Button type="primary"
                                        htmlType="submit"
                                        style={{backgroundColor: 'var(--color-primary)'}}>
                                    保存
                                </Button>
                                <Button type="default" htmlType="button" onClick={() => {
                                    nav(-1);
                                }}>
                                    返回
                                </Button>
                            </Flex>
                        </Form.Item>
                    </Form>
                </div>
            </div>
            <Modal title="提示"
                   okText="确定"
                   cancelText="取消"
                   open={isEditModalOpen}
                   onOk={() => {
                       setIsEditModalOpen(false);
                       put({
                           messageApi,
                           url: `/api/proj/update/edit-step4/${pathParams.projId}`,
                           body: {
                               authorName: form.getFieldValue('authorName'),
                               authorIdCardType: form.getFieldValue('authorIdCardType'),
                               authorIdCard: form.getFieldValue('authorIdCard'),
                               authorNation: form.getFieldValue('authorNation'),
                               authorProvince: form.getFieldValue('authorProvince').join(','),
                               authorEstablishDate: dayjs(form.getFieldValue('authorEstablishDate')).format(dateFormat),
                           },
                           onBefore() {
                               setLoading(true);
                           },
                           onSuccess() {
                               messageApi.open({
                                   type: 'success',
                                   content: '编辑成功'
                               })
                           },
                           onFinally() {
                               setLoading(false);
                           }
                       })
                   }}
                   onCancel={() => {
                       setIsEditModalOpen(false);
                   }}>
                <div>确定提交吗？</div>
            </Modal>
            <Spin tip="正在提交..." spinning={loading} fullscreen/>
        </>
    )

}