import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesCalScheduleDetailApi } from '#/api/mes/cal/scheduleDetail';

import { getPlanPage } from '#/api/mes/cal/plan';
import { getTeamList } from '#/api/mes/cal/team';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';

/** 下拉选项 */
export interface OptionItem {
  label: string;
  value: number;
}

/** 来源：自动生成 */
export const SOURCE_AUTO = 1;
/** 来源：人工调整 */
export const SOURCE_MANUAL = 2;

/** 违规类型描述 */
export const issueTypeMap: Record<number, string> = {
  1: '单日疑似连续工时超长',
  2: '相邻班次间休息不足',
};

/** 排班计划选项缓存（搜索表单与列表名称回显共用） */
let planOptionsCache: OptionItem[] | undefined;

export async function fetchPlanOptions(): Promise<OptionItem[]> {
  if (planOptionsCache) {
    return planOptionsCache;
  }
  const page = await getPlanPage({ pageNo: 1, pageSize: 100 });
  planOptionsCache = page.list.map((item) => ({
    label: item.name!,
    value: item.id!,
  }));
  return planOptionsCache;
}

/** 班组选项缓存 */
let teamOptionsCache: OptionItem[] | undefined;

export async function fetchTeamOptions(): Promise<OptionItem[]> {
  if (teamOptionsCache) {
    return teamOptionsCache;
  }
  const list = await getTeamList();
  teamOptionsCache = list.map((item) => ({
    label: item.name!,
    value: item.id!,
  }));
  return teamOptionsCache;
}

/** 员工选项缓存 */
let userOptionsCache: OptionItem[] | undefined;

export async function fetchUserOptions(): Promise<OptionItem[]> {
  if (userOptionsCache) {
    return userOptionsCache;
  }
  const list = await getSimpleUserList();
  userOptionsCache = list.map((item) => ({
    label: item.nickname!,
    value: item.id!,
  }));
  return userOptionsCache;
}

/** 生成排班明细的表单 */
export function useGenerateFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'planId',
      label: '排班计划',
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        api: fetchPlanOptions,
        optionFilterProp: 'label',
        placeholder: '请选择排班计划',
        showSearch: true,
      },
      rules: 'selectRequired',
      help: '按该计划下的班组排班展开为员工级明细，重复生成会先清理旧明细',
    },
  ];
}

/** 人工调整排班明细的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'shiftId',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'shiftName',
      label: '班次名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入班次名称',
      },
      rules: 'required',
    },
    {
      fieldName: 'startTime',
      label: '开始时间',
      component: 'TimePicker',
      componentProps: {
        class: '!w-full',
        format: 'HH:mm',
        placeholder: '请选择开始时间',
        valueFormat: 'HH:mm',
      },
      rules: 'required',
    },
    {
      fieldName: 'endTime',
      label: '结束时间',
      component: 'TimePicker',
      componentProps: {
        class: '!w-full',
        format: 'HH:mm',
        placeholder: '请选择结束时间',
        valueFormat: 'HH:mm',
      },
      rules: 'required',
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注',
        rows: 3,
      },
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'planId',
      label: '排班计划',
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        api: fetchPlanOptions,
        optionFilterProp: 'label',
        placeholder: '请选择排班计划',
        showSearch: true,
      },
    },
    {
      fieldName: 'teamId',
      label: '班组',
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        api: fetchTeamOptions,
        optionFilterProp: 'label',
        placeholder: '请选择班组',
        showSearch: true,
      },
    },
    {
      fieldName: 'userId',
      label: '员工',
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        api: fetchUserOptions,
        optionFilterProp: 'label',
        placeholder: '请选择员工',
        showSearch: true,
      },
    },
    {
      fieldName: 'day',
      label: '日期',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<MesCalScheduleDetailApi.Detail>['columns'] {
  return [
    {
      field: 'day',
      title: '日期',
      minWidth: 120,
      formatter: 'formatDate',
    },
    {
      field: 'planId',
      title: '排班计划',
      minWidth: 150,
      slots: { default: 'planId' },
    },
    {
      field: 'teamId',
      title: '班组',
      minWidth: 120,
      slots: { default: 'teamId' },
    },
    {
      field: 'userId',
      title: '员工',
      minWidth: 100,
      slots: { default: 'userId' },
    },
    { field: 'shiftName', title: '班次名称', minWidth: 110 },
    { field: 'startTime', title: '开始时间', width: 100 },
    { field: 'endTime', title: '结束时间', width: 100 },
    {
      field: 'source',
      title: '来源',
      width: 110,
      slots: { default: 'source' },
    },
    { field: 'remark', title: '备注', minWidth: 140 },
    {
      title: '操作',
      width: 180,
      fixed: 'right',
      slots: {
        default: 'actions',
      },
    },
  ];
}
