import { h } from 'vue';

// import { useUserStore } from '@vben/stores';
import { getPopupContainer } from '@vben/utils';

import { queryExecutorList } from '#/api/schedule/index';
import { selectAllSysStation } from '#/api/system/infoEntry/stationInfo/stationInfo';
import { getPostList } from '#/api/system/post/post';
import { querybaseApilist } from '#/api/system/tasksettings/tasktemplate';
import { getFileUploadConfig } from '#/components/upload/config';
import { getDictOptions } from '#/utils/dict';

// const userStore = useUserStore();
// 字典标识常量
const DICT_KEYS = {
  // 任务类型字典标识
  TASK_TYPE: 'task_type',
  WF_FORM_TYPE: 'wf_form_type',
  FORMT_TYPE: 'form_type',
};
// 获取任务类型字典选项
const getTaskTypeOptions = () => getDictOptions(DICT_KEYS.TASK_TYPE);
// console.log('任务类型',getTaskTypeOptions());
// const getFormTypeOptions = () => getDictOptions(DICT_KEYS.WF_FORM_TYPE); // 表单类型
// const getSubFormTypeOptions = () => getDictOptions(DICT_KEYS.FORMT_TYPE); // 表单子类型

let getPostListOptions = [] as any; // 执行岗位下拉
let getUserListOptions = [] as any; // 执行人下拉
const getPostListfn = async () => {
  const { rows } = await getPostList({
    pageSize: 10_000,
  });
  getPostListOptions = rows.map((item: any) => ({
    label: item.postName,
    value: item.postId,
    type: item.type,
  }));
};

let templateList = [] as any; // 任务模板下拉

const getUserListfn = async () => {
  const res = await queryExecutorList({});
  getUserListOptions = res.map((item: any, index: number) => ({
    label: `${item.userName}-${item.postName}-${item.stationName}`,
    value: index.toString(),
    data: item,
  }));
};
getPostListfn();
getUserListfn();
// 新建油站任务
export const drawerFormSchema: any = (type: any) => [
  {
    component: 'Select',
    fieldName: 'executePosition',
    label: '执行岗位',
    rules: 'required',
    componentProps: () => {
      const options =
        type === 3
          ? getPostListOptions.filter((item: any) => item.type === 'management')
          : getPostListOptions.filter((item: any) =>
              ['headquarters', 'region'].includes(item.type),
            );
      return {
        placeholder: '请选择执行岗位',
        allowClear: true,
        options,
      };
    },
  },
  {
    component: 'Input',
    fieldName: 'executorIds',
    label: '执行人名称',
    dependencies: {
      show: false,
      disabled: true,
      trigger(values: any, form: any) {
        const ids =
          values.executors?.map((item: any) => {
            const info = getUserListOptions.find((i: any) => i.value === item);
            return info?.data || '';
          }) || [];

        form.setFieldValue('executorIds', ids);
      },

      triggerFields: ['executors'],
    },
  },
  {
    component: 'ApiSelect',
    componentProps: {
      getPopupContainer,
      api: async () => {
        const data = await selectAllSysStation({
          isAll: true,
        });
        return data;
      },
      multiple: true,
      labelField: 'stationName',
      valueField: 'id',
    },

    fieldName: 'stationId',
    label: '场站',
    rules: 'required',
    dependencies: {
      show: () => {
        return type !== 3;
      },
      required: () => {
        return type !== 3;
      },
      disabled: false,
      triggerFields: ['stationId'],
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'executors',
    label: '执行人名称',
    rules: 'required',
    componentProps: (data: any, formApi: any) => {
      const options =
        type === 3
          ? getUserListOptions.filter((item: any) => item.data.postId === 3)
          : getUserListOptions;
      return {
        placeholder: '请选择执行人',
        clearable: true,
        multiple: true,
        options,
        labelField: 'label',
        immediate: true,
        valueField: 'value',
        onBlur: () => {
          const values = data.executors;
          const ids =
            values?.map((item: any) => {
              const info = getUserListOptions.find(
                (i: any) => i.value === item,
              );
              return info?.data || '';
            }) || [];
          formApi.setFieldValue('executorIds', ids);
        },
      };
    },
  },
  {
    component: 'RadioGroup',
    fieldName: 'formType',
    label: '任务名称',
    rules: 'required',
    defaultValue: 'photo',
    componentProps: (data: any, formApi: any) => {
      const options =
        type === 3
          ? [
              { value: 'photo', label: '新增拍照任务' },
              { value: '3', label: '选择任务模板' },
            ]
          : [
              { value: 'photo', label: '新增拍照任务' },
              { value: 'inspection', label: '新增检查任务' },
              { value: '3', label: '选择任务模板' },
            ];
      return {
        placeholder: '请选择任务名称',
        allowClear: true,
        options,
        onChange: (values: any) => {
          // console.log('values', data, formApi, values);
          if (values !== '3') {
            formApi.setFieldValue('templateId', '');
          }
        },
      };
    },
  },
  {
    component: 'Input',
    fieldName: 'taskName',
    label: '',
    componentProps: {
      placeholder: '请输入任务名称',
      maxlength: 100,
    },
    dependencies: {
      show: (values: any) => values.formType !== '3',
      triggerFields: ['formType'],
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'templateId',
    label: '',
    componentProps: {
      placeholder: '请选择任务模板',
      api: async () => {
        const { rows } = await querybaseApilist({
          status: 0,
          pageNum: 1,
          pageSize: 1000,
        });
        templateList = rows;
        return rows;
      },
      labelField: 'taskName',
      valueField: 'id',
    },
    dependencies: {
      show: (values: any) => values.formType === '3',
      triggerFields: ['formType'],
    },
  },
  {
    component: 'DatePicker',
    fieldName: 'startTime',
    label: '开始时间',
    rules: 'required',
    componentProps: {
      placeholder: '请选择开始时间',
      type: 'datetime',
      showTime: true,
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
  },
  {
    component: 'DatePicker',
    fieldName: 'endTime',
    label: '截止时间',
    rules: 'required',
    componentProps: {
      placeholder: '请选择截止时间',
      showTime: true,
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      type: 'datetime',
    },
  },
  // {
  //   component: 'Select',
  //   fieldName: 'formType',
  //   label: '表单类型',
  //   rules: 'required',
  //   componentProps: {
  //     placeholder: '请选择表单类型',
  //     allowClear: true,
  //     options: getFormTypeOptions(),
  //   },
  // },
  // {
  //   component: 'Select',
  //   fieldName: 'subFormType',
  //   label: '表单子类型',
  //   rules: 'required',
  //   componentProps: {
  //     placeholder: '请选择表单子类型',
  //     allowClear: true,
  //     options: getSubFormTypeOptions(),
  //   },
  // },
  {
    component: 'Select',
    fieldName: 'taskType',
    label: '任务类型',
    rules: 'selectRequired',
    componentProps: {
      placeholder: '请选择任务类型',
      allowClear: true,
      options: getTaskTypeOptions(),
    },
    dependencies: {
      disabled(values: any) {
        const temp = templateList.find(
          (item: any) => item.id === values.templateId,
        );
        return !!temp?.taskType;
      },
      trigger(values: any, form: any) {
        const temp = templateList.find(
          (item: any) => item.id === values.templateId,
        );
        if (temp) {
          form.setFieldValue('taskType', temp?.taskType);
        } else {
          form.setFieldValue('taskType', '');
        }
      },
      triggerFields: ['templateId'],
    },
  },
  {
    component: 'Input',
    fieldName: 'ccReceivers',
    label: '抄送人',
    dependencies: {
      show: false,
      // disabled: true,
      // trigger(values: any, form: any) {
      //   const ids =
      //     values.executors?.map((item: any) => {
      //       const info = getUserListOptions.find((i: any) => i.value === item);
      //       return info?.data || '';
      //     }) || [];

      //   form.setFieldValue('executorIds', ids);
      // },

      triggerFields: ['executors'],
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'ccReceiversName',
    label: '抄送人',
    rules: 'required',
    componentProps: (data: any, formApi: any) => {
      return {
        placeholder: '请选择抄送人',
        clearable: true,
        multiple: true,
        options: getUserListOptions,
        labelField: 'label',
        immediate: true,
        valueField: 'value',
        onBlur: () => {
          const values = data.ccReceiversName;
          // const ids =
          //   values?.map((item: any) => {
          //     const info = getUserListOptions.find(
          //       (i: any) => i.value === item,
          //     );
          //     return info?.data || '';
          //   }) || [];
          formApi.setFieldValue('ccReceivers', values.join(','));
        },
      };
    },
  },
  {
    component: 'Input',
    fieldName: 'description',
    label: '任务描述',
    componentProps: {
      type: 'textarea',
      placeholder: '请输入任务描述',
      maxlength: 500,
      showWordLimit: true,
      rows: 4,
    },
    dependencies: {
      disabled(values: any) {
        const temp = templateList.find(
          (item: any) => item.id === values.templateId,
        );
        return !!temp?.description;
      },
      trigger(values: any, form: any) {
        const temp = templateList.find(
          (item: any) => item.id === values.templateId,
        );
        if (temp) {
          form.setFieldValue('description', temp?.description || '');
        } else {
          form.setFieldValue('description', '');
        }
      },
      triggerFields: ['templateId'],
    },
  },
  {
    component: 'Upload',
    fieldName: 'attachments',
    label: '附件',
    componentProps: (row: any) => {
      return {
        ...getFileUploadConfig(
          '.png,.jpg,.jpeg,.gif,.pdf,.doc,.docx,.xls,.xlsx',
          'text',
          5,
        ),
        onSuccess: (res: any) => {
          if (res.code === 200) {
            // 处理上传成功后的逻辑
            if (!row.attachments) {
              row.attachments = [];
            }
            return res.data.fileName;
          }
          return Promise.reject(res);
        },
        // onRemove: (file: any) => {
        //   // 处理文件移除逻辑
        //   if (row.attachments) {
        //     row.attachments = row.attachments.filter(
        //       (item: any) => item.url !== file.url,
        //     );
        //   }
        // },
      };
    },
    renderComponentContent: () => {
      return {
        default: () =>
          h(
            'div',
            {
              class: 'flex items-center justify-center',
            },
            [
              h(
                'ElIcon',
                { class: 'el-upload__icon' },
                { default: () => h('Plus', { size: '18' }) },
              ),
              h(
                'div',
                {
                  class: 'el-upload__text',
                },
                [
                  h('div', {}, '上传附件'),
                  h(
                    'div',
                    { class: 'text-xs text-gray-500' },
                    '最多上传5个附件，支持png、jpg、jpeg、gif、pdf、doc、docx、xls、xlsx格式',
                  ),
                ],
              ),
            ],
          ),
      };
    },
  },
];
