import type { FormSchemaGetter } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { getDictOptions } from '#/utils/dict';
import { selectAllSysStation,selectAllSysAreaList } from '#/api/system/infoEntry/stationInfo/stationInfo';
import { getFileUploadConfig } from '#/components/upload';
import { requestClient } from '#/api/request';

// 获取片区列表
const getAreaList = async () => {
  try {
    const resp = await selectAllSysAreaList();
    console.log('获取片区列表成功:', resp);
    const data = resp || [];
    return Array.isArray(data)
      ? data.map((item: any) => ({
          label: item.areaName,
          value: item.id.toString(),
        }))
      : [];
  } catch (error) {
    console.error('获取片区列表失败:', error);
    return [];
  }
};

// 获取油站列表
const getStationList = async () => {
  try {
    const resp = await selectAllSysStation();
    const data = resp || [];
    return Array.isArray(data)
      ? data.map((item: any) => ({
          label: item.stationName,
          value: item.id.toString(),
        }))
      : [];
  } catch (error) {
    console.error('获取油站列表失败:', error);
    return [];
  }
};

// 获取执行人列表
const getExecutorList = async (stationId: string) => {
  try {
    if (!stationId) {
      console.error('stationId 不能为空');
      return [];
    }
    const resp = await requestClient.get('/system/user/stationList', {
      params: {
        postId: 3,
        stationId: stationId,
      },
    });
    const data = resp || [];
    console.log('获取执行人列表成功:', data);
    return Array.isArray(data)
      ? data.map((item: any) => ({
          label: item.userName,
          value: item.userId.toString(),
        }))
      : [];
  } catch (error) {
    console.error('获取执行人列表失败:', error);
    return [];
  }
};

export const querySchema: FormSchemaGetter = () => [
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择任务类型',
      options: [
        { label: '系统任务', value: 'system' },
        { label: '手动任务', value: 'manual' },
      ],
    },
    fieldName: 'type',
    label: '任务类型',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      placeholder: '请选择片区',
      api: getAreaList,
    },
    fieldName: 'areaId',
    label: '片区',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      placeholder: '请选择油站',
      api: getStationList,
    },
    fieldName: 'stationId',
    label: '油站',
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
    },
    fieldName: 'enterTime',
    label: '录入时间',
  },
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择任务状态',
      //  0-按时完成, 1-逾期完成
      options: [
        { label: '按时完成', value: '0' },
        { label: '逾期完成', value: '1' },
      ],
    },
    fieldName: 'completionStatus',
    label: '任务状态',
  },
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择评论状态',
      options: [
        { label: '已评论', value: '1' },
        { label: '未评论', value: '0' },
      ],
    },
    fieldName: 'isComment',
    label: '评论',
  },
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择判定结果',
      options: getDictOptions('judgment_result'),
    },
    fieldName: 'judgmentResult',
    label: '判定结果',
  },
];

export const columns: VxeGridProps['columns'] = [
  {
    type: 'checkbox',
    width: 80,
  },
  {
    title: '客户投诉问题',
    fixed: 'left',
    field: 'complaintProblem',
    minWidth: 150,
  },
  {
    title: '投诉渠道',
    field: 'complaintChannelName',
    minWidth: 130,
  },
  {
    title: '投诉类型',
    field: 'complaintTypeName',
    minWidth: 130,
  },
  {
    title: '执行人',
    field: 'executorIdName',
    minWidth: 130,
  },
  {
    title: '岗位',
    field: 'position',
    minWidth: 130,
  },
  {
    title: '评论',
    field: 'isComment',
    minWidth: 130,
    formatter: (params: { cellValue: string | number }) => {
      return params.cellValue === 1 ? '已评论' : '未评论';
    },
  },
  {
    title: '判定结果',
    field: 'judgmentResultName',
    minWidth: 130,
  },
  {
    title: '任务状态',
    field: 'completionStatus',
    minWidth: 130,
    formatter: (params: { cellValue: number }) => {
      return params.cellValue === 0 ? '按时完成' : '逾期完成';
    },
  },
  {
    title: '截止时间',
    field: 'deadline',
    minWidth: 150,
  },
  {
    title: '处理时间',
    field: 'processTime',
    minWidth: 150,
  },
  {
    field: 'action',
    fixed: 'right',
    slots: { default: 'action' },
    title: '操作',
    width: 200,
  },
];

// 抽屉表单schema
export const drawerFormSchema: FormSchemaGetter = () => [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      placeholder: '请选择投诉油站',
      api: getStationList,
    },
    fieldName: 'stationId',
    label: '投诉油站',
    rules: 'required',
  },
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择投诉渠道',
      options: getDictOptions('complaint_channel'),
    },
    fieldName: 'complaintChannel',
    label: '投诉渠道',
    rules: 'required',
  },
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择类型',
      options: getDictOptions('complaint_type'),
    },
    fieldName: 'complaintType',
    label: '类型',
    rules: 'required',
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择投诉时间',
      style: {
        width: '100%',
      },
    },
    fieldName: 'complaintTime',
    label: '投诉时间',
    rules: 'required',
  },
  {
    component: 'Input',
    componentProps: {
      placeholder: '请输入投诉问题',
      maxlength: 500,
      type: 'textarea',
      showWordLimit: true,
    },
    fieldName: 'complaintProblem',
    label: '投诉问题',
    rules: 'required',
  },
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'attachmentImages',
  },
  {
    component: 'Upload',
    fieldName: 'attachmentImagesUrl',
    label: '图片',
    componentProps: (row: any) => {
      return {
        ...getFileUploadConfig(
          '.jpg,.jpeg,.png,.gif',
          'picture-card',
          5,
          '/common/upload',
        ),
        onSuccess: (res: any) => {
          // 图片上传成功处理
        },
      };
    },
    renderComponentContent: () => {
      return {
        default: () => '点击上传',
      };
    },
  },
  {
    component: 'Select',
    componentProps: {
      placeholder: '请选择判定结果',
      options: getDictOptions('judgment_result'),
    },
    fieldName: 'judgmentResult',
    label: '判定结果',
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择开始时间',
      style: {
        width: '100%',
      },
    },
    fieldName: 'startTime',
    label: '开始时间',
  },
  {
    component: 'DatePicker',
    componentProps: {
      type: 'datetime',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      placeholder: '请选择截止时间',
      style: {
        width: '100%',
      },
    },
    fieldName: 'deadline',
    label: '截止时间',
    rules: 'required',
  },
  {
    component: 'ApiSelect',
    componentProps: (form: any) => {
      return {
        placeholder: '请选择执行人',
        api: () => getExecutorList(form.stationId || ''),
        params: {
          stationId: form.stationId || '',
        },
      };
    },
    dependencies: {
      show: () => true,
      triggerFields: ['stationId'],
    },
    fieldName: 'executorId',
    label: '执行人',
  }
];

// 图片处理逻辑
export const formatAttachmentImages = (detailData: any) => {
  if (!detailData.attachmentImagesUrl) {
    return [];
  }
  
  // 处理数组格式
  if (Array.isArray(detailData.attachmentImagesUrl)) {
    return detailData.attachmentImagesUrl.map((url: string, index: number) => ({
      name: detailData.attachmentImages?.split(',')[index] || `图片${index + 1}`,
      url,
      status: 'success',
      uid: Date.now() + index,
    }));
  }
  
  // 处理字符串格式
  if (typeof detailData.attachmentImagesUrl === 'string') {
    return [{
      name: detailData.attachmentImagesUrl.split('/').pop() || '未知图片',
      url: detailData.attachmentImagesUrl,
      status: 'success',
      uid: Date.now(),
    }];
  }
  
  return [];
};

