import type { VbenFormApi, VbenFormSchema } from "#/adapter/form";
import type { VxeTableGridOptions } from "#/adapter/vxe-table";

import { h } from 'vue';

import { CommonStatusEnum, DICT_TYPE } from "#/packages/constants/src";
import { getDictOptions } from "#/packages/effects/hooks/src";

import { z } from '#/adapter/form';
import { generateAutoCode } from '#/api/mes/md/autocode/record';
import { MesAutoCodeRuleCode } from '@vben/constants';
import { getUnitPage } from '#/api/mdm/unit';
import { getWarehouseSimpleList } from '#/api/mes/wm/warehouse';

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

// 缓存单位列表
let unitListCache: any[] | null = null;
let unitListPromise: Promise<any[]> | null = null;

// 缓存仓库列表
let warehouseListCache: any[] | null = null;
let warehouseListPromise: Promise<any[]> | null = null;

/** 获取单位列表（带缓存） */
async function getUnitListCached() {
  if (unitListCache) {
    return unitListCache;
  }
  if (unitListPromise) {
    return unitListPromise;
  }
  unitListPromise = getUnitPage({ pageNo: 1, pageSize: 100, status: 0 }).then((res) => {
    unitListCache = res.list || [];
    return unitListCache;
  }).finally(() => {
    unitListPromise = null;
  });
  return unitListPromise;
}

/** 获取仓库列表（带缓存） */
async function getWarehouseListCached() {
  if (warehouseListCache) {
    return warehouseListCache;
  }
  if (warehouseListPromise) {
    return warehouseListPromise;
  }
  warehouseListPromise = getWarehouseSimpleList().then((res) => {
    warehouseListCache = res || [];
    return warehouseListCache;
  }).finally(() => {
    warehouseListPromise = null;
  });
  return warehouseListPromise;
}

/** 清除单位列表缓存 */
export function clearUnitListCache() {
  unitListCache = null;
  warehouseListCache = null;
}

/** 新增/修改的表单 */
export function useFormSchema(formApi?: VbenFormApi): VbenFormSchema[] {
  return [
    {
      component: "Input",
      fieldName: "id",
      dependencies: {
        triggerFields: [""],
        show: () => false,
      },
    },
    {
      component: "Input",
      fieldName: "code",
      label: "品种编码",
      componentProps: {
        maxLength: 64,
        placeholder: "请输入品种编码",
      },
      rules: z.string().min(1, '品种编码不能为空').max(64),
      suffix: () =>
        h(
          Button,
          {
            type: 'default',
            onClick: async () => {
              const code = await generateAutoCode(
                MesAutoCodeRuleCode.MD_ITEM_CODE,
              );
              await formApi?.setFieldValue('code', code);
            },
          },
          { default: () => '生成' },
        ),
    },
    {
      component: "Input",
      fieldName: "name",
      label: "品种名称",
      componentProps: {
        placeholder: "请输入品种名称",
      },
      rules: "required",
    },
    {
      component: "Input",
      fieldName: "specification",
      label: "规格型号",
      componentProps: {
        placeholder: "请输入规格型号",
      },
    },
    {
      component: "ApiSelect",
      fieldName: "unitMeasureId",
      label: "计量单位",
      rules: "required",
      formItemClass: "col-span-1",
      componentProps: {
        placeholder: "请选择计量单位",
        allowClear: true,
        api: getUnitListCached,
        labelField: "name",
        valueField: "id",
      },
    },
    {
      component: 'ApiSelect',
      fieldName: 'warehouseId',
      label: '默认仓库',
      componentProps: {
        placeholder: '请选择默认仓库',
        allowClear: true,
        api: getWarehouseListCached,
        labelField: 'name',
        valueField: 'id',
        onChange: async (value: number | undefined) => {
          const code = value
            ? ((await getWarehouseListCached()).find((w: any) => w.id === value)?.code || '')
            : '';
          formApi?.setFieldValue('warehouseCode', code);
        },
      },
    },
    {
      component: 'Input',
      fieldName: 'warehouseCode',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      component: "RadioGroup",
      fieldName: "status",
      label: "状态",
      componentProps: {
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, "number"),
        buttonStyle: "solid",
        optionType: "button",
      },
      rules: z.number().default(CommonStatusEnum.ENABLE),
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: "code",
      label: "品种编码",
      component: "Input",
      componentProps: {
        placeholder: "请输入品种编码",
        allowClear: true,
      },
    },
    {
      fieldName: "name",
      label: "品种名称",
      component: "Input",
      componentProps: {
        placeholder: "请输入品种名称",
        allowClear: true,
      },
    },
    {
      fieldName: "status",
      label: "状态",
      component: "Select",
      componentProps: {
        placeholder: "请选择状态",
        allowClear: true,
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, "number"),
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions["columns"] {
  return [
    { type: "checkbox", width: 40 },
    {
      field: "code",
      title: "品种编码",
      minWidth: 120,
    },
    {
      field: "name",
      title: "品种名称",
      minWidth: 180,
    },
    {
      field: "specification",
      title: "规格型号",
      minWidth: 150,
    },
    {
      field: "unitMeasureName",
      title: "单位",
      minWidth: 80,
    },
    {
      field: "warehouseName",
      title: "默认仓库",
      minWidth: 100,
    },
    {
      field: "createTime",
      title: "创建时间",
      minWidth: 180,
      formatter: "formatDateTime",
    },
    {
      field: "status",
      title: "状态",
      width: 80,
      fixed: "right",
      cellRender: {
        name: "CellDict",
        props: { type: DICT_TYPE.COMMON_STATUS },
      },
    },
    {
      title: "操作",
      width: 180,
      fixed: "right",
      slots: { default: "actions" },
    },
  ];
}
