import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AftersalesTicketApi } from '#/api/aftersales/ticket';

import { h } from 'vue';

import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';

import { Button, Tag } from 'ant-design-vue';

import { z } from '#/adapter/form';
import { getSimpleUserList } from '#/api/system/user';
import { getDeptList } from '#/api/system/dept';
import { handleTree } from '#/packages/utils/src';

/** 表单类型 */
export type TicketFormType = 'create' | 'detail' | 'update';

/** 问题类型选项 */
const ISSUE_TYPE_OPTIONS = [
  { label: '一般问题', value: 1 },
  { label: '维修问题', value: 2 },
  { label: '退货问题', value: 3 },
];

/** 严重程度选项 */
const SEVERITY_LEVEL_OPTIONS = [
  { label: '轻微', value: 0 },
  { label: '一般', value: 1 },
  { label: '严重', value: 2 },
  { label: '致命', value: 3 },
];

function isHeaderReadonly(formType: TicketFormType): boolean {
  return formType === 'detail';
}

/** 工单表单 */
export function useTicketFormSchema(formType: TicketFormType): VbenFormSchema[] {
  const readonly = isHeaderReadonly(formType);
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'status',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'name',
      label: '工单主题',
      component: 'Input',
      componentProps: {
        placeholder: '请输入工单主题',
      },
      rules: 'required',
    },
    {
      fieldName: 'customerName',
      label: '客户',
      component: 'Input',
      componentProps: {
        placeholder: '请输入客户',
      },
      rules: 'required',
    },
    {
      fieldName: 'contactName',
      label: '联系人',
      component: 'Input',
      componentProps: {
        placeholder: '请输入联系人',
      },
    },
    {
      fieldName: 'handlerUserId',
      label: '处理人',
      component: 'ApiSelect',
      componentProps: {
        api: getSimpleUserList,
        labelField: 'nickname',
        valueField: 'id',
        showSearch: true,
        filterOption: (input: string, option: any) =>
          `${option?.label ?? ''}`.toLowerCase().includes(input.toLowerCase()) ||
          `${option?.value ?? ''}`.includes(input),
        allowClear: true,
        placeholder: '请选择处理人（可搜索昵称）',
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'contractId',
      label: '合同编号',
      component: 'Input',
      componentProps: {
        placeholder: '请输入合同编号',
      },
    },
    {
      fieldName: 'issueDescription',
      label: '问题描述',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请输入问题描述',
        rows: 3,
      },
    },
    {
      fieldName: 'issueType',
      label: '问题类型',
      component: 'Select',
      componentProps: {
        options: ISSUE_TYPE_OPTIONS,
        placeholder: '请选择问题类型',
      },
      dependencies: {
        triggerFields: ['status'],
        show: () => !readonly || formType === 'detail',
      },
    },
    {
      fieldName: 'issueCategory',
      label: '问题分类',
      component: 'Input',
      componentProps: {
        placeholder: '请输入问题分类（如外观缺陷、功能故障）',
      },
    },
    {
      fieldName: 'severityLevel',
      label: '严重程度',
      component: 'Select',
      componentProps: {
        options: SEVERITY_LEVEL_OPTIONS,
        placeholder: '请选择严重程度',
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请输入备注',
        rows: 3,
      },
    },
    {
      fieldName: 'blobIds',
      label: '附件',
      component: 'FileUpload',
      componentProps: {
        valueKey: 'id',
        maxNumber: 10,
        multiple: true,
        disabled: readonly,
      },
      formItemClass: 'col-span-3',
    },
  ];
}

/** 工单列表搜索表单 */
export function useTicketGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'no',
      label: '工单单号',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入工单单号',
      },
    },
    {
      fieldName: 'name',
      label: '工单主题',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入工单主题',
      },
    },
    {
      fieldName: 'customerName',
      label: '客户',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入客户',
      },
    },
    {
      fieldName: 'status',
      label: '工单状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.AFTERSALE_TICKET_STATUS, 'number'),
        placeholder: '请选择工单状态',
      },
    },
    {
      fieldName: 'issueType',
      label: '问题类型',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: ISSUE_TYPE_OPTIONS,
        placeholder: '请选择问题类型',
      },
    },
  ];
}

/** 工单列表字段 */
export function useTicketGridColumns(): VxeTableGridOptions<AftersalesTicketApi.Ticket>['columns'] {
  return [
    {
      field: 'no',
      title: '工单单号',
      minWidth: 180,
      slots: { default: 'no' },
    },
    {
      field: 'name',
      title: '工单主题',
      minWidth: 180,
    },
    {
      field: 'customerName',
      title: '客户',
      minWidth: 150,
    },
    {
      field: 'issueType',
      title: '问题类型',
      width: 100,
      slots: { default: 'issueType' },
    },
    {
      field: 'severityLevel',
      title: '严重程度',
      width: 100,
      slots: { default: 'severityLevel' },
    },
    {
      field: 'status',
      title: '工单状态',
      width: 100,
      slots: { default: 'status' },
    },
    {
      field: 'ownerUserName',
      title: '负责人',
      minWidth: 100,
    },
    {
      field: 'handlerUserName',
      title: '处理人',
      minWidth: 100,
    },
    {
      field: 'createTime',
      title: '创建时间',
      width: 180,
      formatter: 'formatDate',
    },
    {
      title: '操作',
      width: 240,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 工单明细行表格字段 */
export function useTicketItemGridColumns(
  editable: boolean,
): VxeTableGridOptions<AftersalesTicketApi.TicketItem>['columns'] {
  return [
    {
      field: 'itemNo',
      title: '明细单号',
      minWidth: 170,
    },
    {
      field: 'itemCode',
      title: '物料编码',
      minWidth: 120,
    },
    {
      field: 'itemName',
      title: '物料名称',
      minWidth: 140,
    },
    {
      field: 'batchCode',
      title: '批次号',
      minWidth: 120,
    },
    {
      field: 'saleQuantity',
      title: '销售数量',
      width: 100,
    },
    {
      field: 'returnQuantity',
      title: '退货数量',
      width: 100,
    },
    {
      field: 'needRepair',
      title: '需要维修',
      width: 90,
      slots: { default: 'needRepair' },
    },
    {
      field: 'needReturn',
      title: '需要退货',
      width: 90,
      slots: { default: 'needReturn' },
    },
    {
      field: 'deptName',
      title: '部门',
      minWidth: 120,
    },
    {
      field: 'reasonType',
      title: '原因类型',
      width: 120,
      slots: { default: 'reasonType' },
    },
    {
      field: 'reason',
      title: '具体原因',
      minWidth: 160,
    },
    ...(editable
      ? [
          {
            title: '操作',
            width: 120,
            fixed: 'right',
            slots: { default: 'itemActions' },
          } as const,
        ]
      : []),
  ];
}

/** 工单明细行表单 */
export function useTicketItemFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'itemName',
      label: '物料',
      component: 'Input',
      componentProps: {
        placeholder: '请输入物料',
      },
      rules: 'required',
    },
    {
      fieldName: 'batchCode',
      label: '批次',
      component: 'Input',
      componentProps: {
        placeholder: '请输入批次',
      },
    },
    {
      fieldName: 'saleQuantity',
      label: '销售数量',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        placeholder: '请输入销售数量',
        precision: 2,
      },
      rules: 'required',
    },
    {
      fieldName: 'returnQuantity',
      label: '退货数量',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        placeholder: '请输入退货数量',
        precision: 2,
      },
    },
    {
      fieldName: 'needRepair',
      label: '需要维修',
      component: 'Switch',
      rules: z.boolean().default(false),
    },
    {
      fieldName: 'needReturn',
      label: '需要退货',
      component: 'Switch',
      rules: z.boolean().default(false),
    },
    {
      fieldName: 'deptId',
      label: '部门',
      component: 'ApiTreeSelect',
      componentProps: {
        api: async () => handleTree(await getDeptList()),
        labelField: 'name',
        valueField: 'id',
        childrenField: 'children',
        placeholder: '请选择部门',
        treeDefaultExpandAll: true,
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'reasonType',
      label: '原因类型',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.AFTERSALE_REASON_TYPE, 'number'),
        placeholder: '请选择原因类型',
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'reason',
      label: '具体原因',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请输入具体原因',
        rows: 2,
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请输入备注',
        rows: 2,
      },
    },
  ];
}
