/*
 * @Author: donghao donghao@supervision.ltd
 * @Date: 2024-04-07 14:02:00
 * @LastEditors: donghao donghao@supervision.ltd
 * @LastEditTime: 2024-05-24 17:32:23
 * @FilePath: \general-ai-manage\src\pages\BusinessProject\components\updateForm.tsx
 * @Description: 企业项目编辑
 * @交互说明
 * 1. 行业从接口获取
 * 2. logo上传使用base64码，无需提前做文件上传
 * 3. 统一提交表单数据
 */
import { useCity } from '@/hooks/useCity';
import { useUploadFile } from '@/hooks/useUploadFile';
import { apiIndustrymap } from '@/services/business/dict';
import { apiEntityEdit } from '@/services/business/entity';
import { transformDictByMap } from '@/utils/dict';
import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  // ProFormDependency,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Form, message } from 'antd';
import React, { useEffect, useState } from 'react';
import {
  proFormSmallItemStyleProps,
  proFormSmallModelWidth,
} from '../../../../../config/defaultForm';
// @ts-ignore
// import cookie from 'react-cookies';
export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.ModelCategory>;

export type UpdateFormProps = {
  updateModalOpen: boolean;
  handleModal: () => void;
  values: Partial<API.ModelCategory>;
  reload: any;
};
const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const intl = useIntl();
  // const [isAuto, setIsAuto] = useState(true);
  const [form] = Form.useForm<API.ModelCategory>();
  const [cityOptions, setCityOptions] = useState<Record<string, any>[]>([]);
  const [fileList, setFileList] = useState([]);

  const { formatProvinceByData, formatCityByProvinceData, formatCityByProvince } = useCity();
  function changeCity(record1, record2) {
    // 汇总城市数据到表单
    console.log(record1, record2, 'changeProvince_record');
  }

  const { getBase64 } = useUploadFile();
  // 文件上传处理函数
  const handleUpload = async (file) => {
    try {
      const base64 = await getBase64(file);
      console.log('Base64 File:', base64);
      // 假设上传成功，将文件添加到fileList 并 给表单赋值
      form.setFieldValue('logo', base64);
    } catch (error) {
      // message.error('文件转换失败');
    }
  };
  // 文件选择变化处理函数
  const handleChangeFile = ({ file, fileList }) => {
    // 检查文件状态
    if (file.status === 'removed') {
      // 删除文件
      setFileList(fileList.filter((item) => item.uid !== file.uid));
      // message.success(`${file.name} 删除成功`);
    } else {
      // 处理上传
      handleUpload(file);
    }
    setFileList(fileList);
    return false; // 阻止自动上传
  };

  function resetForm() {
    setFileList([]);
    form.resetFields();
  }

  useEffect(() => {
    if (props.updateModalOpen && props.values?.id) {
      form.setFieldsValue(props.values);
      console.log(props.values, 'useEffect_values');
      setFileList(() => [
        {
          uid: 'test001',
          name: 'test001',
          status: 'done',
          url: props.values?.logo, // 将Base64作为URL回显
        },
      ]);
    } else {
      resetForm();
    }
  }, [props.updateModalOpen, props.values]);

  return (
    <ModalForm<API.ModelCategory>
      className="gn_form gn_modal_form"
      width={proFormSmallModelWidth}
      title={intl.formatMessage({
        id: 'business.list.table.editForm.title',
        defaultMessage: '编辑',
      })}
      initialValues={props.values}
      open={props.updateModalOpen}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => props.handleModal(),
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        console.log(values, 'add_finish_values');
        apiEntityEdit({ ...values, id: props.values?.id })
          .then(() => {
            message.success(
              intl.formatMessage({ id: 'common.action.success', defaultMessage: '$$$' }),
            );
            props.reload();
            props.handleModal();
          })
          .catch(() => {
            message.error(
              intl.formatMessage({ id: 'common.action.failure', defaultMessage: '$$$' }),
            );
          });
        return true;
      }}
    >
      <ProForm.Group>
        <ProFormText
          width={proFormSmallItemStyleProps.width}
          name="name"
          label={<FormattedMessage id="business.list.table.form.name" defaultMessage="名称" />}
          placeholder={`${intl.formatMessage({
            id: 'common.please_input',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'business.list.table.form.name',
            defaultMessage: '$$$',
          })}`}
          required={true}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="business.list.table.form.rule.required.name"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />

        <ProFormSelect
          width={proFormSmallItemStyleProps.column2Width / 2 - 8}
          name="province"
          label={<FormattedMessage id="business.list.table.form.province" defaultMessage="省份" />}
          placeholder={`${intl.formatMessage({
            id: 'common.please_select',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'business.list.table.form.province',
            defaultMessage: '$$$',
          })}`}
          required={true}
          showSearch
          debounceTime={500}
          request={() => {
            const respDataList = formatProvinceByData();
            return respDataList;
          }}
          onChange={(_, record2) => {
            form.setFieldValue('city', null); // 先清空城市
            console.log(record2, 'onDropdownVisibleChange');

            setCityOptions(() => formatCityByProvinceData(record2));
          }}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="business.list.table.form.rule.required.province"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />
        <ProFormSelect
          width={proFormSmallItemStyleProps.column2Width / 2 - 8}
          name="city"
          label={<FormattedMessage id="business.list.table.form.city" defaultMessage="城市" />}
          placeholder={`${intl.formatMessage({
            id: 'common.please_select',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'business.list.table.form.city',
            defaultMessage: '$$$',
          })}`}
          required={true}
          showSearch
          debounceTime={500}
          options={cityOptions}
          onChange={changeCity}
          fieldProps={{
            onDropdownVisibleChange: (open) => {
              if (open) {
                setCityOptions(() => formatCityByProvince(form.getFieldValue('province')));
              }
              console.log(open, 'onDropdownVisibleChange', form.getFieldValue('province'));
            },
          }}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="business.list.table.form.rule.required.city"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />
        <ProFormText
          width={proFormSmallItemStyleProps.column2Width}
          name="addr"
          label={<FormattedMessage id="business.list.table.form.address" defaultMessage="地址" />}
          placeholder={`${intl.formatMessage({
            id: 'common.please_input',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'business.list.table.form.address',
            defaultMessage: '$$$',
          })}`}
          required={true}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="business.list.table.form.rule.required.address"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />
        <ProFormSelect
          width={proFormSmallItemStyleProps.width}
          name="industry"
          label={<FormattedMessage id="model_index.create.form.industry" defaultMessage="行业" />}
          placeholder={`${intl.formatMessage({
            id: 'common.please_select',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'model_index.create.form.industry',
            defaultMessage: '$$$',
          })}`}
          required={true}
          showSearch
          debounceTime={500}
          request={async () => {
            const { data } = await apiIndustrymap();
            // console.log(data,'apiIndustrymap_data')
            return transformDictByMap(data);
          }}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="model_index.create.form.rule.required.industry"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />
        <ProFormText
          width={proFormSmallItemStyleProps.width}
          name="contact"
          label={
            <FormattedMessage id="business.list.table.form.contacts" defaultMessage="联系人" />
          }
          placeholder={`${intl.formatMessage({
            id: 'common.please_input',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'business.list.table.form.contacts',
            defaultMessage: '$$$',
          })}`}
          required={true}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="business.list.table.form.rule.required.contacts"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />
        <ProFormText
          width={proFormSmallItemStyleProps.width}
          name="phone"
          label={
            <FormattedMessage id="business.list.table.form.contactWay" defaultMessage="联系方式" />
          }
          placeholder={`${intl.formatMessage({
            id: 'common.please_input',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'business.list.table.form.contactWay',
            defaultMessage: '$$$',
          })}`}
          required={true}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="business.list.table.form.rule.required.contactWay"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />
        <ProFormTextArea
          width={proFormSmallItemStyleProps.width}
          name="summary"
          label={<FormattedMessage id="business.list.table.form.remark" defaultMessage="简介" />}
          placeholder={`${intl.formatMessage({
            id: 'common.please_input',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'business.list.table.form.remark',
            defaultMessage: '$$$',
          })}`}
          required={true}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="business.list.table.form.rule.required.remark"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
          disabled={false}
        />
        <ProFormUploadButton
          width={proFormSmallItemStyleProps.width}
          max={1}
          // action="/api/v1/file/uploadImage"
          name="logo"
          label={<FormattedMessage id="business.list.table.form.logo" defaultMessage="logo" />}
          fileList={fileList}
          onChange={handleChangeFile}
          fieldProps={{
            name: 'file',
            listType: 'picture-card',
            beforeUpload: (file) => {
              handleUpload(file);
              return false; // 阻止自动上传
            },
          }}
          icon={<i className="iconfont icon-xinjian text-[20px] text-[#DCDCDC]"></i>} // 自定义图标
          title="" // 自定义文字
          required={true}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="business.list.table.form.rule.required.logo"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />
      </ProForm.Group>
    </ModalForm>
  );
};
export default UpdateForm;
