import type { VbenFormApi, VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { AftersalesTicketApi } from '#/api/aftersales/ticket';
import type { ErpSaleOrderApi } from '#/api/erp/sale/order';

import { h, markRaw } 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 CrmCustomerSelect from '#/components/crm-customer-select.vue';
import { ErpSaleOrderSelect } from '#/views/erp/sale/order/components';
import { MdItemSelect } from '#/views/mes/md/item/components';
import { WmBatchSelect } from '#/views/wls/batch/components';
import { UserSelect } from '#/views/system/user/components';

/** 表单类型 */
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,
  formApi?: VbenFormApi,
  onSaleOrderChange?: (order: Record<string, unknown> | undefined) => void,
): 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: 'saleOrderId',
      label: '销售订单号',
      component: markRaw(ErpSaleOrderSelect),
      componentProps: {
        placeholder: '请选择销售订单',
        outStatus: 3,
        onChange: (item: Record<string, unknown> | undefined) => {
          if (formApi) {
            formApi.setFieldValue('saleOrderNo', item?.no ?? '');
            if (item?.customerId) {
              formApi.setFieldValue('customerId', item.customerId);
            }
          }
          onSaleOrderChange?.(item);
        },
      },
    },
    {
      fieldName: 'saleOrderNo',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'customerId',
      label: '客户',
      component: markRaw(CrmCustomerSelect),
      componentProps: {
        placeholder: '请选择客户',
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'contactId',
      label: '联系人',
      component: 'Input',
      componentProps: {
        placeholder: '请输入联系人',
      },
    },
    {
      fieldName: 'handlerUserId',
      label: '处理人',
      component: markRaw(UserSelect),
      componentProps: {
        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: 'customerId',
      label: '客户',
      component: markRaw(CrmCustomerSelect),
      componentProps: {
        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: 'saleOrderNo',
      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: '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' },
    },
    ...(editable
      ? [
          {
            title: '操作',
            width: 120,
            fixed: 'right',
            slots: { default: 'itemActions' },
          } as const,
        ]
      : []),
  ];
}

/** 工单明细行表单 */
export function useTicketItemFormSchema(
  clientId?: number,
  salesOrderCode?: string,
  orderItems?: ErpSaleOrderApi.SaleOrderItem[],
  formApi?: VbenFormApi,
): VbenFormSchema[] {
  const hasOrderItems = orderItems && orderItems.length > 0;
  return [
    {
      fieldName: 'itemId',
      label: '物料',
      component: hasOrderItems ? 'Select' : markRaw(MdItemSelect),
      componentProps: hasOrderItems
        ? {
            placeholder: '请选择物料',
            options: orderItems!.map((oi) => ({
              label: `${oi.productName || ''} (${oi.productBarCode || oi.productId})`,
              value: oi.productId,
            })),
            showSearch: true,
            onChange: (value: number) => {
              const oi = orderItems!.find((o) => o.productId === value);
              if (oi && formApi) {
                formApi.setValues({
                  itemName: oi.productName,
                  itemCode: oi.productBarCode || '',
                  saleQuantity: oi.count,
                  batchCode: oi.batchCode || '',
                });
              }
            },
          }
        : {
            placeholder: '请选择物料',
          },
      rules: 'selectRequired',
    },
    {
      fieldName: 'itemCode',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    {
      fieldName: 'itemName',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    ...(hasOrderItems
      ? [
          {
            fieldName: 'batchCode',
            label: '批次',
            component: 'Input',
            componentProps: {
              disabled: true,
              placeholder: '自动从订单带入',
            },
          },
        ]
      : [
          {
            fieldName: 'batchId',
            label: '批次',
            component: markRaw(WmBatchSelect),
            componentProps: {
              clientId,
              placeholder: '请选择批次',
              salesOrderCode,
            },
            dependencies: {
              triggerFields: ['itemId'],
              componentProps: (values: Record<string, unknown>) => ({
                clientId,
                itemId: values.itemId,
                placeholder: '请选择批次',
                salesOrderCode,
              }),
            },
          },
        ]),
    {
      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: 'remark',
      label: '备注',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请输入备注',
        rows: 2,
      },
    },
  ];
}
