import {
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProDescriptions,
  ProFormUploadButton,
  ProFormRadio,
} from '@ant-design/pro-components';
import { Form } from 'antd';
import React, { useEffect ,useState} from 'react';
import { DictValueEnumObj } from '@/components/DictTag';
import { getCmsCompanyList } from '@/services/company/list';
import { cmsfileupload } from '@/services/Management/list';

export type ListFormProps = {
  onCancel: (flag?: boolean, formVals?: unknown) => void;
  onSubmit: (values: API.ManagementList.Manage) => Promise<void>;
  open: boolean;
  values?: Partial<API.ManagementList.Manage>;
  educationEnum: DictValueEnumObj;
  experienceEnum: DictValueEnumObj;
  areaEnum: DictValueEnumObj;
  isExplainOptions: any;
  mode?: 'view' | 'edit' | 'create';
};

const listEdit: React.FC<ListFormProps> = (props) => {
  const [form] = Form.useForm<API.ManagementList.Manage>();
  const [initialCompanyOptions, setInitialCompanyOptions] = useState<Array<{label: string, value: string | number}>>([]);
  const [loading, setLoading] = useState(false);
  const { educationEnum, experienceEnum, areaEnum, isExplainOptions } = props;
  const { mode = props.values ? 'edit' : 'create' } = props;
  // 预加载公司数据
  useEffect(() => {
    const preloadCompanyData = async () => {
      if (props.open && props.values?.companyId && props.values?.companyName) {
        setLoading(true);
        try {
          // 1. 先搜索当前公司名称
          const resData = await getCmsCompanyList({ 
            name: props.values.companyName,
          });
          
          let options = resData.rows.map((item) => ({
            label: item.name,
            value: item.companyId
          }));
          
          // 2. 如果当前公司不在搜索结果中，手动添加
          const exists = options.some(opt => opt.value === props.values!.companyId);
          if (!exists) {
            options = [
              { label: props.values.companyName, value: props.values.companyId },
              ...options
            ];
          }
          
          setInitialCompanyOptions(options);
        } catch (error) {
          console.error('预加载公司失败:', error);
          // 如果请求失败，至少添加当前公司
          setInitialCompanyOptions([
            { label: props.values.companyName, value: props.values.companyId }
          ]);
        } finally {
          setLoading(false);
        }
      }
    };
    
    preloadCompanyData();
  }, [props.open, props.values?.companyId, props.values?.companyName]);


  useEffect(() => {
    if (props.open) {
      form.resetFields();
      setTimeout(() => {
        if (props.values) {
          form.setFieldsValue({
            ...props.values,
            jobLocationAreaCode: String(props.values.jobLocationAreaCode || ''),
            isExplain: Number(props.values.isExplain) || 0,
          });
        } else {
          form.setFieldsValue({ isExplain: 0 });
        }
      }, 0);
    }
  }, [form, props.values, props.open]);
  const handleCancel = () => {
    props.onCancel();
    form.resetFields();
  };

  const handleFinish = async (values: Record<string, any>) => {
    const submitValues = {
      ...values,
      isExplain: values.isExplain ?? 0,
    };
    props.onSubmit(submitValues as API.ManagementList.Manage);
  };

  const handleChange = (_: string, value: any) => {
    form.setFieldValue('companyName', value.label);
  };

  const customUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;

    if (!file) {
      onError(new Error('文件不能为空'));
      return;
    }

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await cmsfileupload(formData);

      // Validate response structure
      if (!response || typeof response !== 'object') {
        throw new Error('上传响应格式错误');
      }

      if (response.code === 200) {
        const fileUrl = typeof response.msg === 'string' ? response.msg : '';
        const coverUrl = typeof response.coverUrl === 'string' ? response.coverUrl : '';

        if (fileUrl) {
          (form as any).setFieldValue('explainUrl', fileUrl);
        }
        if (coverUrl) {
          (form as any).setFieldValue('cover', coverUrl);
        }

        onSuccess(response);
      } else {
        const errorMessage = typeof response.message === 'string' ? response.message : '上传失败';
        throw new Error(errorMessage);
      }
    } catch (error) {
      console.error('File upload error:', error);
      const errorMessage = error instanceof Error ? error.message : '上传过程中发生未知错误';
      onError(new Error(errorMessage));
    }
  };

  if (mode === 'view') {
    return (
      <ModalForm
        title="岗位详情"
        open={props.open}
        width={800}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => handleCancel(),
          footer: null,
        }}
        submitter={false}
      >
        <ProDescriptions<API.ManagementList.Manage> column={2} dataSource={props.values || {}}>
          <ProDescriptions.Item dataIndex="jobTitle" label="岗位名称" />
          <ProDescriptions.Item dataIndex="companyName" label="招聘公司" />
          <ProDescriptions.Item dataIndex="minSalary" label="最低薪资(元/月)" />
          <ProDescriptions.Item dataIndex="maxSalary" label="最高薪资(元/月)" />
          <ProDescriptions.Item dataIndex="education" label="学历要求" valueEnum={educationEnum} />
          <ProDescriptions.Item
            dataIndex="experience"
            label="工作经验"
            valueEnum={experienceEnum}
          />
          <ProDescriptions.Item
            dataIndex="jobLocationAreaCode"
            label="工作区县"
            valueEnum={areaEnum}
          />
          <ProDescriptions.Item dataIndex="vacancies" label="招聘人数" />
          <ProDescriptions.Item dataIndex="jobLocation" label="工作地点" />
          <ProDescriptions.Item dataIndex="explainUrl" label="视频" />
          <ProDescriptions.Item dataIndex="cover" label="视频帧封面图" />
          <ProDescriptions.Item
            dataIndex="isExplain"
            label="是否显示讲解视频"
            valueType="select"
            valueEnum={{
              0: '关闭显示',
              1: '显示视频',
            }}
          />
          <ProDescriptions.Item dataIndex="jobId" label="岗位编号" />
          <ProDescriptions.Item dataIndex="companyId" label="公司编号" />
          <ProDescriptions.Item dataIndex="isHot" label="是否热门" />
          <ProDescriptions.Item dataIndex="isPublish" label="是否发布" />
          <ProDescriptions.Item
            dataIndex="description"
            label="岗位描述"
            span={2} // 跨两列显示
          />
        </ProDescriptions>
      </ModalForm>
    );
  }
  return (
    <ModalForm<API.ManagementList.Manage>
      title={mode === 'edit' ? '编辑岗位' : '新建岗位'}
      form={form}
      autoFocusFirstInput
      open={props.open}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => handleCancel(),
      }}
      submitTimeout={2000}
      onFinish={handleFinish}
      initialValues={{
        isExplain: 0,
      }}
    >
      <ProForm.Group>
        <ProFormText width="md" hidden name="explainUrl" />
        <ProFormText width="md" hidden name="cover" />
        <ProFormText width="md" hidden name="jobId" />
        <ProFormText width="md" hidden name="companyName" />
        <ProFormText width="md" name="jobTitle" label="岗位名称" placeholder="请输入岗位名称" />
        <ProFormSelect
          showSearch
          width="md"
          name="companyId"
          fieldProps={{
            onChange: (value, option) => {
              if (option && option.label) {
                form.setFieldValue('companyName', option.label);
              }
            },
            loading: loading,
            options: initialCompanyOptions,
            defaultActiveFirstOption: false,
          }}
          request={async ({ keyWords }) => {
            const resData = await getCmsCompanyList({ 
              name: keyWords,
            });
            const options = resData.rows.map((item) => ({
              label: item.name,
              value: item.companyId
            }));
            
            // 如果是编辑模式，确保当前公司被包含
            if (props.values?.companyId && props.values?.companyName && keyWords) {
              const exists = options.some(opt => opt.value === props.values!.companyId);
              if (!exists && props.values.companyName.toLowerCase().includes(keyWords.toLowerCase())) {
                options.unshift({
                  label: props.values.companyName,
                  value: props.values.companyId
                });
              }
            }
            
            return options;
          }}
          placeholder={loading ? "加载中..." : "请输入公司名称选择公司"}
          rules={[{ required: true, message: '请输入公司名称选择公司!' }]}
          label="招聘会公司"
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormDigit
          name="minSalary"
          width="md"
          min={0}
          label="最小薪资（元/月）"
          placeholder="请输入最小薪资（元）"
        />
        <ProFormDigit
          name="maxSalary"
          width="md"
          min={0}
          label="最大薪资（元/月）"
          placeholder="请输入最大薪资（元）"
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          width="md"
          name="education"
          label={'学历要求'}
          valueEnum={educationEnum}
          placeholder="请选择学历要求"
          rules={[{ required: true, message: '请选择学历要求!' }]}
        />
        <ProFormSelect
          width="md"
          name="experience"
          label={'工作经验'}
          valueEnum={experienceEnum}
          placeholder="请选择岗位"
          rules={[{ required: true, message: '请选择工作经验!' }]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          width="md"
          name="jobLocationAreaCode"
          label={'工作区县'}
          valueEnum={areaEnum}
          placeholder="请选择区县"
          rules={[{ required: true, message: '请选择区县!' }]}
        />
        <ProFormDigit
          label="招聘人数"
          name="vacancies"
          width="md"
          min={0}
          placeholder="请输入招聘人数"
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText width="lg" name="jobLocation" label="工作地点" placeholder="请输入工作地点" />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormTextArea
          width="lg"
          name="description"
          label="岗位描述"
          placeholder="请输入岗位描述"
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormRadio.Group
          name="isExplain"
          label={'是否显示讲解视频'}
          colProps={{ md: 24 }}
          placeholder="请选择是否显示讲解视频"
          options={isExplainOptions}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormUploadButton
          name="video"
          label="视频上传"
          max={1}
          fieldProps={{
            customRequest: customUpload,
            accept: 'video/*',
          }}
        />
      </ProForm.Group>
    </ModalForm>
  );
};

export default listEdit;
