import React, { useEffect, useState } from 'react';
import { Modal, Form, message, Input, Upload, Button } from 'antd';
import type { UploadProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import DomesticForm from './DomesticForm';
import ForeignForm from './ForeignForm';
import { uploadFile, updateSupplierBase } from '../services'

interface Props {
    visible: boolean;
    onOk: () => void;
    onCancel: () => void;
    initialValues?: coscoSupplierBases;
    changeData?: changeDataValueProps;

}

// 基础信息
interface coscoSupplierBases {
    id?: string;
    supplierType?: string;
    name?: string;
    nameEn?: string;
    range?: string;
    workAddress?: string;
    parentCompanyInvestor?: string;
    legalPerson?: string;
    capital?: string;
    contactsName?: string;
    contactsPhone?: string;
    contactsEmail?: string;
    nation?: string;
    vat?: string;
    currency?: string;
    licenceAccessory?: string;
    licenceDate?: string;
    enterpriseType?: string;
    socialCreditCode?: string;
    regAddress?: string;
    idCard?: string;
    contactsType?: string;
    telephone?: string;
}

//提交全部数据
interface updateSupplierBases {
    title?: string;
    changeDesc?: string;
    coscoSupplierSurveyAttachments?: coscoSupplierSurveyAttachments[];
    coscoSupplierBase: coscoSupplierBases;
    attachment?: {
        uid: string;
        name: string;
        url: string;
        status: string;
    }[];
}

//变更内容
interface changeDataValueProps {
    id?: string;
    title?: string;
    changeDesc?: string;
    coscoSupplierSurveyAttachments?: coscoSupplierSurveyAttachments[];
}
interface coscoSupplierSurveyAttachments {
    attachmentsType: string;
    fileName: string;
    fileType: string;
    fileSize: string;
    filePath: string;
    fileUrl: string;
}
//变更要求
interface changeComparisonDataProps {
    name?: string;
    range?: string;
}
const BaseInfoFormModal: React.FC<Props> = ({
    visible,
    onOk,
    onCancel,
    initialValues,
    changeData
}) => {
    const [form] = Form.useForm();
    //短信
    const [countdown, setCountdown] = useState(0);
    //变更企业名称与 经营范围 时需要 添加 名称 变更说明与附件上传
    const [changeComparisonData, setChangeComparisonData] = useState<changeComparisonDataProps>();
    //查看数据
    const [viewData, setViewData] = useState<updateSupplierBases>();

    //数据初始化
    useEffect(() => {
        if (visible && initialValues) {
            form.setFieldsValue({
                ...changeData,
                coscoSupplierBase: {
                    ...initialValues,
                    licenceAccessoryD: initialValues?.licenceAccessory
                        ? [{
                            uid: '-1',
                            name: '营业执照',
                            status: 'done',
                            url: initialValues.licenceAccessory,
                            thumbUrl: initialValues.licenceAccessory,
                        }]
                        : [],
                },
                attachment: changeData?.coscoSupplierSurveyAttachments
                    ? [{
                        uid: '-1',
                        name: changeData?.coscoSupplierSurveyAttachments[0].fileName,
                        url: changeData?.coscoSupplierSurveyAttachments[0].fileUrl,
                        status: 'done',
                        response: {
                            fileName: changeData?.coscoSupplierSurveyAttachments[0].fileName,
                            fileType: changeData?.coscoSupplierSurveyAttachments[0].fileType,
                            fileSize: changeData?.coscoSupplierSurveyAttachments[0].fileSize,
                            filePath: changeData?.coscoSupplierSurveyAttachments[0].filePath,
                            fileUrl: changeData?.coscoSupplierSurveyAttachments[0].fileUrl,
                            attachmentsType: "change",
                        }
                    }]
                    : [],

            });
            setChangeComparisonData({
                name: initialValues.name,
                range: initialValues.range,
            })
            setViewData({
                ...changeData,
                coscoSupplierBase: {
                    ...initialValues,
                }
            });
        } else {
            form.resetFields();
        }
    }, [visible, initialValues, changeData]);



    // 获取短信验证码
    const handleGetCaptcha = () => {
        form
            .validateFields(['contactPhone'])
            .then((values) => {
                message.success(`验证码已发送至 ${values.contactPhone}`);
                let count = 60;
                setCountdown(count);

                const timer = setInterval(() => {
                    count--;
                    setCountdown(count);
                    if (count === 0) {
                        clearInterval(timer);
                    }
                }, 1000);
            })
            .catch((errorInfo) => {
                message.error('请先输入正确的手机号');
            });

    };

    //确认提交
    const handleFinish = async () => {
        Modal.confirm({
            title: '是否确认个人信息变更？',
            onOk: async () => {
                const values = await form.validateFields();
                const payload = {
                    ...values,
                };
                //values.attachment 有附件就处理
                if (values.attachment) {
                    const file = values.attachment?.[0].response;
                    payload.coscoSupplierSurveyAttachments = [
                        {
                            attachmentsType: file.attachmentsType,
                            fileName: file.fileName,
                            fileType: file.fileType,
                            fileSize: file.fileSize,
                            filePath: file.filePath,
                            fileUrl: file.fileUrl,
                        }
                    ];
                }
                // 处理营业执照回显字段转换问题
                if (payload.coscoSupplierBase.supplierType === 'dvs') {
                    let licenceAccessoryD = payload.coscoSupplierBase.licenceAccessoryD;
                    if (licenceAccessoryD[0].response) {
                        payload.coscoSupplierBase.licenceAccessory = payload.coscoSupplierBase.licenceAccessoryD[0].response.url
                    } else {
                        payload.coscoSupplierBase.licenceAccessory = payload.coscoSupplierBase.licenceAccessoryD[0].url
                    }
                    delete payload.coscoSupplierBase.licenceAccessoryD
                }
                const res = await updateSupplierBase(payload);
                if (res.code === 200) {
                    message.success('修改成功');
                    onOk();
                }
            },
        });

    };
    //上传接口
    const uploadProps: UploadProps = {
        name: 'file',
        showUploadList: true,
        beforeUpload: (file) => {
            if (file.size > 1048576) { // 1MB
                message.error('文件大小不能超过1MB');
                return Upload.LIST_IGNORE; // 阻止上传
            }
            return true;
        },
        customRequest: async ({ file, onSuccess, onError }) => {
            try {
                const realFile = file as File;
                const res = await uploadFile(realFile);
                const uploadedFile = {
                    uid: res.fileSize,
                    name: res.fileName,
                    status: 'done',
                    url: res.url,
                    fileName: res.fileName,
                    fileType: res.fileType,
                    fileSize: res.fileSize,
                    filePath: res.filePath,
                    fileUrl: res.url,
                    attachmentsType: "change",
                };
                onSuccess?.(uploadedFile, new XMLHttpRequest())
                message.success('上传成功');
            } catch (err: any) {
                onError?.(err);
                message.error(err.message || '上传失败');
            }
        }
    };
    return (
        <Modal
            title="企业基本信息"
            visible={visible}
            onCancel={onCancel}
            onOk={handleFinish}
            destroyOnClose
            width={800}
        >
            <Form form={form} labelCol={{ flex: '140px' }} wrapperCol={{ flex: 1 }}>
                {viewData?.coscoSupplierBase?.supplierType === 'dvs' ? (
                    <DomesticForm
                        form={form}
                        countdown={countdown}
                        handleGetCaptcha={handleGetCaptcha}
                    />
                ) : (
                    <ForeignForm
                        form={form}
                        countdown={countdown}
                        handleGetCaptcha={handleGetCaptcha}
                    />
                )}
                <Form.Item shouldUpdate>
                    {() => {
                        // 每次Form数据变化都会重新render
                        const currentName = form.getFieldValue(['coscoSupplierBase', 'name']);
                        const currentRange = form.getFieldValue(['coscoSupplierBase', 'range']);
                        const shouldShowPanel =
                            (changeComparisonData?.name !== undefined && currentName !== changeComparisonData.name) ||
                            (changeComparisonData?.range !== undefined && currentRange !== changeComparisonData.range);

                        if (!shouldShowPanel) return null;

                        return (
                            <>
                                <Form.Item
                                    name='title'
                                    label="名称"
                                    labelCol={{ flex: '140px' }}
                                    rules={[{ required: true, message: '请输入名称' }]}
                                >
                                    <Input placeholder="请输入名称" />
                                </Form.Item>
                                <Form.Item
                                    name='changeDesc'
                                    label="变更说明"
                                    labelCol={{ flex: '140px' }}
                                    rules={[{ required: true, message: '请输入变更说明' }]}
                                >
                                    <Input.TextArea placeholder="请输入变更说明" rows={2} maxLength={200} showCount />
                                </Form.Item>
                                <Form.Item
                                    name="attachment"
                                    label="附件"
                                    labelCol={{ flex: '140px' }}
                                    valuePropName="fileList"
                                    getValueFromEvent={(e) => Array.isArray(e) ? e : e?.fileList}
                                >
                                    <Upload {...uploadProps} maxCount={1}>
                                        <Button icon={<UploadOutlined />}>上传</Button>
                                    </Upload>
                                </Form.Item>
                            </>
                        );
                    }}
                </Form.Item>

            </Form>
        </Modal >
    );
};

export default BaseInfoFormModal;
