import React,{ useEffect,useState } from 'react';
import {
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect,
  ProFormSelect
} from '@ant-design/pro-components';
import { Form } from 'antd';
import { getCmsJobTitleList } from '@/services/classify/jobs';
import { getDictValueEnum } from '@/services/system/dict';



// tree
type JobListParams = API.ClassifyJobs.Params;

export type ListFormProps = {
  onCancel: (flag?: boolean, formVals?: unknown) => void;
  onSubmit: (values: any) => Promise<void>;
  open: boolean;
  values?: Partial<API.ClassifyJobs.Jobs>;
  // jobGroupOptions: DictOptionType[];
  // statusOptions: DictValueEnumObj;
};

const listEdit: React.FC<ListFormProps> = (props) => {
  const [form] = Form.useForm();
  const [treeData, setTreeData] = useState<API.ClassifyJobs.Jobs[]>([]);
  const [statusOptions, setStatusOptions] = useState<Record<string, any>>({});
  const [loading, setLoading] = useState(false);
  
  const buildTree = (data: API.ClassifyJobs.Jobs[], parentId: number = 0): API.ClassifyJobs.Jobs[] => {
    return data
      .filter(item => item.parentId === parentId)
      .map(item => ({
        ...item,
        children: buildTree(data, item.jobId),
      }));
  };

  useEffect(() => {
    const fetchData = async () => {
      const res = await getCmsJobTitleList({ 
        tree: false,
        // 明确传递所有必要参数
        pageSize: 1000, // 确保获取全部数据
        current: 1 
      } as JobListParams);
      setLoading(true);
      try {
     // 获取状态枚举
     const statusData = await getDictValueEnum('sys_jobs_status', true);
     setStatusOptions(statusData);
       // 获取岗位数据
       const res = await getCmsJobTitleList({ tree: false } as JobListParams);
       console.log('原始数据:', res.rows);

      const treeData = buildTree(res.rows || []);
      console.log('转换后的树形数据:', treeData);
      setTreeData(treeData);
   
      // 设置表单初始值
      if (props.values) {
        form.setFieldsValue({
          ...props.values,
          parentId: props.values.parentId || undefined,
        });
        }
        } catch (error) {
        console.error('数据加载失败:', error);
        } finally {
        setLoading(false);
        }
};
fetchData();
}, []);

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


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

  return (
    <ModalForm
      title={`${props.values ? '编辑' : '新增'}企业`}
      form={form}
      autoFocusFirstInput
      open={props.open}
      width={600}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => handleCancel(),
      }}
      submitTimeout={2000}
      onFinish={handleFinish}
    >
      <ProFormDigit label="InputNumber" name="jobId" disabled hidden={true} />

       {/* 新增：父级岗位选择 */}
       <ProFormTreeSelect
        name="parentId"
        label="父级岗位"
        width="md"
        placeholder="请选择父级岗位"
        allowClear
        fieldProps={{
          treeData,
          fieldNames: { label: 'jobName', value: 'jobId', children: 'children' },
          treeDefaultExpandAll: true,
          showSearch: true,
          variant:'outlined',
          dropdownStyle: { maxHeight: 400, overflow: 'auto' },
          filterTreeNode: (input, option) =>
            String(option?.title ?? '').toLowerCase().includes(input.toLowerCase())
        }}
      />
      <ProForm.Group>
        <ProFormText width="md" name="jobname" label="单位名称" placeholder="请输入单位名称" />
        <ProFormDigit
          width="md"
          name="orderNum"
          label="显示顺序"
          placeholder="请输入显示顺序"
          min={0}
          fieldProps={{ precision: 0 }}
          rules={[{ required: true, message: '请输入显示顺序' }]}
        />
      
      </ProForm.Group>
      <ProFormSelect
        name="status"
        label="状态"
        width="md"
        valueEnum={statusOptions}
        placeholder="请选择状态"
      />
      <ProForm.Group>
        <ProFormText width="md" name="code" label="信用代码" placeholder="请输入信用代码" />
        <ProFormText width="md" name="industry" label="主要行业" placeholder="请输入主要行业" />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormTextArea width="xl" name="location" label="单位地点" placeholder="请输入单位地点" />
      </ProForm.Group>
    </ModalForm>
  );
};

export default listEdit;



