import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { SelectProps } from '#/adapter/form';
import { getPostList } from '#/api/system/post/post';
import { getDictOptions } from '#/utils/dict';
import { getUserList } from '#/api/system/user/user';
import { querybaseApilist } from '#/api/system/tasksettings/tasktemplate';
import { queryKnowledgeCategory } from '#/api/knowledge/category';
import { queryKnowledgeContentlist } from '#/api/knowledge/content';
import { getPopupContainer } from '@vben/utils';
// 字典标识常量
const DICT_KEYS = {
  // 任务类型字典标识
  TASK_TYPE: 'task_type',
  //表单类型
  FORM_TYPE: 'wf_form_type',
  //任务频率
  TASK_FREQUENCY: 'task_frequency',
};

// 获取执行岗位列表
let positionsOptions = [] as any[];
//任务负责人
let PersoninchargeOptions = [] as any[];
//任务排斥
let TaskExclusionOptions = [] as any[];

const getPositionsList = async () => {
  const { rows } = await getPostList({
    pageNum: 1,
    pageSize: 100, // 设置足够大的分页大小以获取所有岗位
  });
  positionsOptions = rows.map((item: any) => ({
    label: item.postName,
    value: item.postId,
  }));
};

// 初始化岗位数据
getPositionsList().catch(console.error);

const deptTreefn = async () => {
  const res = await getUserList({
    pageNum: 1,
    pageSize: 100, // 设置足够大的分页大小以获取所有用户
  });
  PersoninchargeOptions = res.rows.map((item: any) => ({
    label: item.userName,
    value: item.userId,
  }));
};
deptTreefn();
const TaskExclusionOptionsfn = async () => {
  const res = await querybaseApilist({
    pageNum: 1,
    pageSize: 100, // 设置足够大的分页大小以获取所有用户
  });
  TaskExclusionOptions = res.rows.map((item: any) => ({
    label: item.taskName,
    value: item.taskName,
  }));
};
TaskExclusionOptionsfn();
// 获取任务类型字典选项
const getTaskTypeOptions = () => getDictOptions(DICT_KEYS.TASK_TYPE);
// 获取表单类型字典选项
const getFormTypeOptions = () => getDictOptions(DICT_KEYS.FORM_TYPE);
// 获取任务频率字典选项
const getTaskFrequencyOptions = () => getDictOptions(DICT_KEYS.TASK_FREQUENCY);

// 模拟任务负责人数据
export const mockResponsibles = [
  { label: '张三', value: '张三' },
  { label: '李四', value: '李四' },
  { label: '王五', value: '王五' },
  { label: '赵六', value: '赵六' },
  { label: '孙七', value: '孙七' },
  { label: '周八', value: '周八' },
];

// 模拟已创建任务数据
export const mockCreatedTasks = [
  { label: '日常巡检任务', value: '日常巡检任务' },
  { label: '安全培训任务', value: '安全培训任务' },
  { label: '财务报表提交', value: '财务报表提交' },
  { label: '市场调研任务', value: '市场调研任务' },
  { label: '人事档案更新', value: '人事档案更新' },
];

// 模拟标准指引数据
export const mockGuidelines = [
  { label: '日常巡检标准指引', value: '日常巡检标准指引' },
  { label: '安全操作手册', value: '安全操作手册' },
  { label: '财务报表填写规范', value: '财务报表填写规范' },
  { label: '市场调研流程', value: '市场调研流程' },
  { label: '人事管理规定', value: '人事管理规定' },
];

// 通用Select组件配置函数
const createSearchSelectConfig = (options: any[], placeholder: string) => ({
  allowClear: true,
  placeholder,
  showSearch: true,
  filterOption: (input: string, option: any) =>
    (option?.label || '').toLowerCase().includes(input.toLowerCase()),
  options,
});

// 通用RadioGroup组件配置函数
const createRadioConfig = (
  options: { label: string; value: string }[],
  defaultValue?: string,
) => ({
  options,
  defaultValue,
});

export const queryFormSchema: FormSchemaGetter = () => [
  {
    component: 'Input',
    fieldName: 'taskName',
    label: '任务名称',
    componentProps: {
      placeholder: '请输入任务名称',
    },
  },
  {
    component: 'Select',
    fieldName: 'taskType',
    label: '任务类型',
    componentProps: {
      allowClear: true,
      placeholder: '请选择任务类型',
      options: getTaskTypeOptions(),
    },
  },
  {
    component: 'Select',
    fieldName: 'taskResponsible',
    label: '任务负责人',
    componentProps: createSearchSelectConfig(
      mockResponsibles,
      '请选择任务负责人',
    ),
  },
  {
    component: 'Select',
    fieldName: 'executivePost',
    label: '执行岗位',
    componentProps: createSearchSelectConfig(
      positionsOptions,
      '请选择执行岗位',
    ),
  },
  {
    component: 'Select',
    fieldName: 'taskFrequency',
    label: '任务频率',
    componentProps: {
      allowClear: true,
      placeholder: '请选择任务频率',
      options: [
        { label: '每天一次', value: '每天一次' },
        { label: '每周一次', value: '每周一次' },
        { label: '每月一次', value: '每月一次' },
        { label: '每两月一次', value: '每两月一次' },
        { label: '每三月一次', value: '每三月一次' },
        { label: '每六月一次', value: '每六月一次' },
        { label: '每年一次', value: '每年一次' },
      ],
    },
  },
  {
    component: 'Select',
    fieldName: 'status',
    label: '状态',
    componentProps: {
      allowClear: true,
      placeholder: '请选择状态',
      options: [
        { label: '关闭', value: '关闭' },
        { label: '启用', value: '启用' },
      ],
    },
  },
  {
    component: 'Select',
    fieldName: 'taskLevel',
    label: '任务级别',
    componentProps: {
      allowClear: true,
      placeholder: '请选择任务级别',
      options: [
        { label: '低', value: '低' },
        { label: '中', value: '中' },
        { label: '高', value: '高' },
      ],
    },
  },
  {
    component: 'Select',
    fieldName: 'formType',
    label: '表单类型',
    componentProps: {
      allowClear: true,
      placeholder: '请选择表单类型',
      options: [
        { label: '确认任务', value: '确认任务' },
        { label: '拍照任务', value: '拍照任务' },
        { label: '检查任务', value: '检查任务' },
        { label: '表单任务', value: '表单任务' },
        { label: '上传附件任务', value: '上传附件任务' },
      ],
    },
  },
  {
    component: 'Select',
    fieldName: 'timedDistribution',
    label: '定时分发',
    componentProps: {
      allowClear: true,
      placeholder: '请选择定时分发',
      options: [
        { label: '否', value: '否' },
        { label: '是', value: '是' },
      ],
    },
  },
  {
    component: 'Select',
    fieldName: 'taskSource',
    label: '任务来源',
    componentProps: {
      allowClear: true,
      placeholder: '请选择任务来源',
      options: [
        { label: '默认', value: '默认' },
        { label: '新增', value: '新增' },
      ],
    },
  },
];
export const tableColumns: VxeGridProps['columns'] = [
  {
    type: 'checkbox',
    width: 80,
  },
  {
    field: 'taskName',
    title: '任务名称',
    minWidth: 150,
  },
  {
    field: 'taskTypeName',
    title: '任务类型',
    minWidth: 120,
  },
  {
    field: 'formTypeName',
    title: '表单类型',
    minWidth: 120,
  },
  {
    field: 'taskLeader',
    title: '任务负责人',
    minWidth: 120,
  },
  {
    field: 'executePositionName',
    title: '执行岗位',
    minWidth: 120,
  },
  {
    field: 'taskFrequency',
    title: '任务频率',
    minWidth: 120,
  },
  {
    field: 'status',
    title: '状态',
    minWidth: 100,
    slots: { default: 'status' },
  },
  {
    field: 'timedDistribution',
    title: '定时分发',
    minWidth: 100,
    slots: { default: 'timedDistribution' },
  },
  // {
  //   field: 'taskSource',
  //   title: '任务来源',
  //   minWidth: 100,
  // },
  // {
  //   field: 'operator',
  //   title: '操作人',
  //   minWidth: 120,
  // },
  // {
  //   field: 'operationTime',
  //   title: '操作时间',
  //   minWidth: 180,
  // },
  {
    field: 'action',
    fixed: 'right',
    slots: { default: 'action' },
    title: '操作',
    width: 300,
  },
];

// 定义通用的是/否选项
const yesNoOptions = [
  { label: '是', value: '1' },
  { label: '否', value: '0' },
];

// 定义表单类型选项
const formTypeOptions = [
  { label: '确认任务', value: '确认任务' },
  { label: '拍照任务', value: '拍照任务' },
  { label: '检查任务', value: '检查任务' },
  { label: '表单任务', value: '表单任务' },
  { label: '上传附件任务', value: '上传附件任务' },
];

export const drawerFormSchema: FormSchemaGetter = () => [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
  },
  {
    component: 'Select',
    fieldName: 'executivePost',
    label: '执行岗位',
    componentProps: createSearchSelectConfig(
      positionsOptions,
      '请选择执行岗位',
    ),
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'taskName',
    label: '任务名称',
    componentProps: {
      placeholder: '请输入任务名称',
      maxlength: 100,
    },
    rules: 'required',
  },
  {
    component: 'Select',
    fieldName: 'taskType',
    label: '任务类型',
    componentProps: {
      placeholder: '请选择任务类型',
      options: getTaskTypeOptions(),
    },
    rules: 'required',
  },
  {
    component: 'Select',
    fieldName: 'taskResponsible',
    label: '任务负责人',
    componentProps: {
      placeholder: '请选择任务负责人',
      options: PersoninchargeOptions,
    },
  },
  {
    component: 'Select',
    fieldName: 'formType',
    label: '表单类型',
    componentProps: {
      placeholder: '请选择表单类型',
      options: getFormTypeOptions(),
    },
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    fieldName: 'canAuthorize',
    label: '可授权',
    componentProps: createRadioConfig(yesNoOptions, '1'),
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    fieldName: 'needScore',
    label: '评分',
    componentProps: createRadioConfig(yesNoOptions, '1'),
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    fieldName: 'mustDo',
    label: '必做',
    componentProps: createRadioConfig(yesNoOptions, '1'),
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    fieldName: 'executiveMode',
    label: '执行方式',
    componentProps: createRadioConfig([
      { label: '人工', value: '1' },
      { label: '自动', value: '0' },
    ]),
  },
  {
    component: 'Select',
    fieldName: 'taskFrequency',
    label: '任务频率',
    componentProps: {
      placeholder: '请选择任务频率',
      options: getTaskFrequencyOptions(),
      // defaultValue: '每天一次',
    },
    rules: 'required',
  },
  {
    component: 'DatePicker',
    fieldName: 'startTime',
    label: '开始时间',
    componentProps: {
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择开始时间',
    },
    rules: 'required',
  },
  {
    component: 'DatePicker',
    fieldName: 'deadline',
    label: '截止日期',
    componentProps: {
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择截止日期',
    },
    rules: 'required',
  },
  {
    component: 'DatePicker',
    fieldName: 'planTime',
    label: '计划时间',
    componentProps: {
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择计划时间',
    },
    rules: 'required',
  },
  {
    component: 'InputNumber',
    fieldName: 'invalidDays',
    label: '失效天数',
    componentProps: {
      placeholder: '请输入失效天数',
      min: 0,
    },
    rules: 'required',
  },
  {
    component: 'InputNumber',
    fieldName: 'intervalDays',
    label: '间隔天数',
    componentProps: {
      placeholder: '请输入间隔天数',
      min: 0,
    },
    rules: 'required',
  },
  {
    component: 'InputNumber',
    fieldName: 'warningTime',
    label: '预警时间',
    componentProps: {
      placeholder: '请输入预警时间',
      min: 0,
    },
  },
  {
    component: 'Select',
    fieldName: 'taskLevel',
    label: '任务级别',
    componentProps: {
      placeholder: '请选择任务级别',
      options: [
        { label: '低', value: '0' },
        { label: '中', value: '1' },
        { label: '高', value: '2' },
      ],
    },
  },
  {
    component: 'Select',
    fieldName: 'taskExclusion',
    label: '任务排斥',
    componentProps: {
      placeholder: '请选择任务排斥',
      options: TaskExclusionOptions,
    },
  },
  {
    component: 'Input',
    fieldName: 'taskIcon',
    label: '任务图标',
    componentProps: {
      placeholder: '请输入任务图标',
    },
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'taskDescription',
    label: '任务描述',
    componentProps: {
      placeholder: '请输入任务描述',
      rows: 10,
    },
    // 使用自定义插槽渲染Tinymce编辑器
    slot: 'taskDescription',
  },
  {
    component: 'ApiTreeSelect',
    fieldName: 'standardGuideline',
    label: '标准指引',
    componentProps: {
      placeholder: '请选择标准指引',
      api: async () => {
        try {
          const res = await queryKnowledgeCategory();
          if (res?.rows && res.rows.length > 0) {
            // 使用Promise.all等待所有异步操作完成
            const treeData = await Promise.all(
              res.rows.map(async (item) => {
                let children = [];
                try {
                  // 获取子项数据
                  const childrenRes = await queryKnowledgeContentlist(item.id);
                  if (childrenRes?.data && childrenRes.data.length > 0) {
                    children = childrenRes.data.map((childItem) => ({
                      ...childItem,
                      label: childItem.title,
                      value: childItem.id,
                      // 确保与valueField一致
                      id: childItem.id,
                    }));
                  }
                } catch (error) {
                  console.error('获取子项数据失败:', error);
                }

                return {
                  ...item,
                  label: item.name || item.title,
                  value: item.id,
                  // 确保与valueField一致
                  id: item.id,
                  children: children,
                };
              }),
            );

            console.log('最终树形数据:', treeData);
            return treeData;
          }
        } catch (error) {
          console.error('获取分类数据失败:', error);
        }

        console.log('没有数据返回');
        return [];
      },
      getPopupContainer,
      labelField: 'label',
      valueField: 'id',
      childrenField: 'children',
      checkStrictly: true,
      // mode: 'multiple',
      // options: mockGuidelines,
    },
  },

  // {
  //       component: 'ApiTreeSelect',
  //       componentProps: {
  //         api: async () => {
  //           return await deptTree();
  //         },
  //         getPopupContainer,
  //         labelField: 'label',
  //         valueField: 'id',
  //         childrenField: 'children',
  //         checkStrictly: true,
  //       },
  //       rules: 'selectRequired',
  //       fieldName: 'deptId',
  //       label: '所属部门',
  //     },

  {
    component: 'Upload',
    fieldName: 'attachment',
    label: '附件',
    // 注意：该组件的详细实现已在taskTemplate-drawer.vue中通过插槽自定义
    // 这里仅保留基本配置，实际渲染由插槽控制
    componentProps: {
      // 基础配置
      action: '#',
      multiple: true,
    },
  },
  {
    component: 'RadioGroup',
    fieldName: 'status',
    label: '任务状态',
    componentProps: {
      options: [
        { label: '启用', value: '0' },
        { label: '关闭', value: '1' },
      ],
      defaultValue: '启用',
    },
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    fieldName: 'timedDistribution',
    label: '定时分发',
    componentProps: {
      options: [
        { label: '是', value: '1' },
        { label: '否', value: '0' },
      ],
      defaultValue: '是',
    },
    rules: 'required',
  },
  // {
  //   component: 'Select',
  //   fieldName: 'archiveList',
  //   label: '归档列表',
  //   componentProps: {
  //     placeholder: '请选择归档列表',
  //     showSearch: true,
  //     filterOption: (input, option) =>
  //       (option?.label || '').toLowerCase().includes(input.toLowerCase()),
  //     // 模拟归档列表数据
  //     options: [
  //       { label: '日常巡检归档', value: '日常巡检归档' },
  //       { label: '安全检查归档', value: '安全检查归档' },
  //       { label: '财务报表归档', value: '财务报表归档' },
  //       { label: '市场调研归档', value: '市场调研归档' },
  //       { label: '人事档案归档', value: '人事档案归档' },
  //     ],
  //   },
  //   rules: 'required',
  // },
];

export const formActions = [
  {
    type: 'button',
    text: '查询',
    submit: true,
    buttonProps: { type: 'primary' },
  },
  { type: 'button', text: '重置', reset: true },
  {
    type: 'button',
    text: '导出',
    buttonProps: { type: 'primary', ghost: true },
  },
];

export const mockData = [
  {
    id: '1',
    taskName: '日常巡检任务',
    taskType: '运营',
    formType: '检查任务',
    taskResponsible: '张三',
    executivePost: '巡检员',
    taskFrequency: '每天一次',
    status: '启用',
    timedDistribution: '是',
    taskSource: '新增',
    operator: '系统管理员',
    operationTime: '2023-10-01 10:00:00',
    // 示例附件数据
    attachment: [
      {
        name: '设备巡检记录表.xlsx',
        url: '#',
        size: 204800,
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        uid: '1622547135000_1',
        status: 'success',
      },
      {
        name: '巡检操作规范.pdf',
        url: '#',
        size: 153600,
        type: 'application/pdf',
        uid: '1622547135000_2',
        status: 'success',
      },
    ],
    taskDescription: '这是一个日常巡检任务，需要检查设备运行状态和环境安全。',
    archiveList: '日常巡检归档',
  },
  {
    id: '2',
    taskName: '安全培训任务',
    taskType: '安全',
    formType: '表单任务',
    taskResponsible: '李四',
    executivePost: '安全员',
    taskFrequency: '每月一次',
    status: '启用',
    timedDistribution: '是',
    taskSource: '新增',
    operator: '系统管理员',
    operationTime: '2023-10-02 14:30:00',
    // 示例附件数据
    attachment: [
      {
        name: '安全培训教材.pdf',
        url: '#',
        size: 307200,
        type: 'application/pdf',
        uid: '1622547135000_3',
        status: 'success',
      },
      {
        name: '培训签到表.xlsx',
        url: '#',
        size: 51200,
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        uid: '1622547135000_4',
        status: 'success',
      },
    ],
    taskDescription: '这是一个安全培训任务，需要组织员工进行安全知识学习。',
    archiveList: '安全检查归档',
  },
  {
    id: '3',
    taskName: '财务报表提交',
    taskType: '财务',
    formType: '上传附件任务',
    taskResponsible: '王五',
    executivePost: '财务人员',
    taskFrequency: '每月一次',
    status: '启用',
    timedDistribution: '否',
    taskSource: '默认',
    operator: '系统管理员',
    operationTime: '2023-10-03 09:15:00',
    // 示例附件数据
    attachment: [
      {
        name: '财务报表模板.xlsx',
        url: '#',
        size: 102400,
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        uid: '1622547135000_5',
        status: 'success',
      },
    ],
    taskDescription: '这是一个财务报表提交任务，需要按时提交月度财务报表。',
    archiveList: '财务报表归档',
  },
  {
    id: '4',
    taskName: '市场调研任务',
    taskType: '市场',
    formType: '表单任务',
    taskResponsible: '赵六',
    executivePost: '市场专员',
    taskFrequency: '每周一次',
    status: '启用',
    timedDistribution: '是',
    taskSource: '新增',
    operator: '系统管理员',
    operationTime: '2023-10-04 16:45:00',
  },
  {
    id: '5',
    taskName: '人事档案更新',
    taskType: '人事',
    formType: '确认任务',
    taskResponsible: '孙七',
    executivePost: '人事专员',
    taskFrequency: '每三月一次',
    status: '关闭',
    timedDistribution: '是',
    taskSource: '默认',
    operator: '系统管理员',
    operationTime: '2023-10-05 11:20:00',
  },
  {
    id: '6',
    taskName: '合规检查任务',
    taskType: '合规',
    formType: '检查任务',
    taskResponsible: '周八',
    executivePost: '合规专员',
    taskFrequency: '每六月一次',
    status: '启用',
    timedDistribution: '否',
    taskSource: '新增',
    operator: '系统管理员',
    operationTime: '2023-10-06 15:10:00',
  },
];
