import { useEffect, useState } from 'react';
import {
  ModalForm,
  ProForm,
  ProFormDateTimeRangePicker,
  ProFormDigit,
  ProFormList,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Form } from 'antd';
import { DictValueEnumObj } from '@/components/DictTag';
import { FormattedMessage, useIntl } from '@umijs/max';
import { getCmsCompanyList } from '@/services/company/list';
import ProFromMap from '@/components/ProFromMap';

export type ListFormProps = {
  onCancel: (flag?: boolean, formVals?: unknown) => void;
  onSubmit: (values: API.JobFairList.JobFairListRows) => Promise<void>;
  open: boolean;
  values?: Partial<API.JobFairList.JobFairListRows>;
  jobFairType?: DictValueEnumObj;
};
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const listEdit: React.FC<ListFormProps> = (props) => {
  const [form] = Form.useForm();
  const intl = useIntl();
  const { jobFairType } = props;

  const [open, setOpen] = useState<boolean>(false);
  const [viewInfo, setViewInfo] = useState<any>({});
  const [companyOptions, setCompanyOptions] = useState([]);

  useEffect(() => {
    form.resetFields();
    if (props.values) {
      console.log(props.values);
      form.setFieldsValue({
        ...props.values,
        createTimeRanger: [props.values.startTime, props.values.endTime],
      });
      setViewInfo(props.values);
    }
  }, [form, props]);

  const handleChange = (_: string, value: any) => {
    const ls = form.getFieldsValue().companyList.map((item: any) => {
      if (value.value === item.companyId) {
        return {
          ...item,
          companyName: value.title,
        };
      }
      return item;
    });
    form.setFieldValue('companyList', ls);
    console.log(ls);
  };

  const handleCancel = () => {
    props.onCancel();
    form.resetFields();
  };

  const handleFinish = async (values: Record<string, any>) => {
    props.onSubmit(values as API.JobFairList.JobFairListRows);
  };

  const select = (result) => {
    if (result.location) {
      const { lat, lng } = result.location;
      form.setFieldValue('latitude', lat);
      form.setFieldValue('longitude', lng);
      form.setFieldValue('address', result.address);
      const obj = {
        latitude: lat,
        longitude: lng,
        address: result.address,
      };
      setViewInfo(obj);
      setOpen(false);
    }
  };

  const cancel = () => {
    setOpen(false);
  };
  return (
    <ModalForm<{
      name: string;
      company: string;
    }>
      title={`${props.values ? '编辑' : '新增'}招聘会`}
      form={form}
      autoFocusFirstInput
      open={props.open}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => handleCancel(),
      }}
      submitTimeout={2000}
      onFinish={handleFinish}
    >
      <ProFormDigit label="InputNumber" name="jobFairId" disabled hidden={true} />
      <ProForm.Group>
        <ProFormText width="md" name="name" label="招聘会名称" placeholder="请输入招聘会名称" />
        <ProFormRadio.Group
          valueEnum={jobFairType}
          name="jobFairType"
          label="招聘会类型"
          colProps={{ md: 24 }}
          placeholder="请选择招聘会类型"
          rules={[
            {
              required: false,
              message: (
                <FormattedMessage id="请选择招聘会类型！" defaultMessage="请选择招聘会类型！" />
              ),
            },
          ]}
        />
        <ProFormDateTimeRangePicker
          transform={(values) => {
            return {
              startTime: values ? values[0] : undefined,
              endTime: values ? values[1] : undefined,
            };
          }}
          width="xl"
          name="createTimeRanger"
          label="招聘会时间"
        />
      </ProForm.Group>

      <ProForm.Group>
        <div>
          <Button onClick={() => setOpen(true)}>选择位置信息</Button>
          <div style={{ margin: '10px 0 0 0' }}>
            {viewInfo.address ? (
              <span style={{ padding: '0 0 0 16px' }}>地址：{viewInfo.address}</span>
            ) : null}
            {viewInfo.latitude ? (
              <span style={{ padding: '0 0 0 16px' }}>
                经纬度：{viewInfo.latitude},{viewInfo.longitude}
              </span>
            ) : (
              <span style={{ padding: '0 0 0 16px', color: 'red' }}>请选择位置!</span>
            )}
          </div>
        </div>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText width="xl" name="location" label="招聘会地点" placeholder="请输入招聘会地点" />
        <ProFormTextArea
          width="xl"
          name="description"
          label="招聘会描述"
          placeholder="请输入招聘会地点"
        />
      </ProForm.Group>
      <ProFormList
        name="companyList"
        creatorButtonProps={{
          position: 'bottom',
          creatorButtonText: '新建一行',
        }}
        copyIconProps={{
          tooltipText: '复制此行到末尾',
        }}
        deleteIconProps={{
          tooltipText: '移除本行',
        }}
      >
        <ProForm.Group>
          <ProFormSelect
            key="companyId"
            showSearch
            width="md"
            name="companyId"
            onChange={handleChange}
            request={async ({ keyWords }) => {
              let resData = await getCmsCompanyList({ name: keyWords });
              return resData.rows.map((item) => ({ label: item.name, value: item.companyId }));
            }}
            placeholder="请输入公司名称选择公司"
            rules={[{ required: true, message: '请输入公司名称选择公司!' }]}
            label="招聘会公司列表"
          />
          <ProFormText width="md" name="companyName" label=" " hidden={true} />
        </ProForm.Group>
      </ProFormList>
      <ProForm.Group>
        <ProFormText
          width="md"
          name="address"
          label="地理位置"
          hidden={true}
          placeholder="请输入地理位置"
        />
        <ProFormDigit
          label="纬度"
          placeholder="请输入纬度"
          name="latitude"
          width="md"
          hidden={true}
          min={-90}
          max={90}
          fieldProps={{ controls: false }}
          rules={[
            {
              required: true,
              message: '请输入纬度！',
            },
          ]}
        />
        <ProFormDigit
          label="经度"
          placeholder="请输入经度"
          name="longitude"
          width="md"
          min={-180}
          hidden={true}
          max={180}
          fieldProps={{ controls: false }}
          rules={[
            {
              required: true,
              message: '请输入经度！',
            },
          ]}
        />
      </ProForm.Group>
      <ProFromMap open={open} onSelect={select} onCancel={cancel}></ProFromMap>
    </ModalForm>
  );
};

export default listEdit;
