import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CustomerApi } from '#/api/license/customer';

import { ref } from 'vue';

import { useAccess } from '@vben/access';

import { z } from '#/adapter/form';
import {
  isCustomerCodeUnique,
  isCustomerNameUnique,
} from '#/api/license/customer';
import { getAreaTree } from '#/api/system/area';
import { $t } from '#/locales';
import { DICT_TYPE, getDictOptions, getRangePickerDefaultProps } from '#/utils';

const { hasAccessByRoles } = useAccess();

export const formData = ref<CustomerApi.Customer>();
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'name',
      label: $t('customer.customerName'),
      component: 'Input',
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', [$t('customer.customerName')]))
        .max(
          60,
          $t('ui.formRules.maxLength', [$t('customer.customerName'), 60]),
        )
        .refine(
          async (value: string) => {
            return await isCustomerNameUnique(value, formData.value?.id);
          },
          (value) => ({
            message: $t('ui.formRules.alreadyExists', [
              $t('customer.customerName'),
              value,
            ]),
          }),
        ),
    },
    {
      fieldName: 'code',
      label: $t('customer.customerSn'),
      component: 'InputNumber',
      rules: z
        .number({
          message: $t('ui.formRules.required', [$t('customer.customerSn')]),
        })
        .min(
          1000,
          $t('ui.formRules.range', [$t('customer.customerSn'), 1000, 9999]),
        )
        .max(
          9999,
          $t('ui.formRules.range', [$t('customer.customerSn'), 1000, 9999]),
        )
        .refine(
          async (value: number) => {
            return await isCustomerCodeUnique(value, formData.value?.id);
          },
          (value) => ({
            message: $t('ui.formRules.alreadyExists', [
              $t('customer.customerSn'),
              value,
            ]),
          }),
        )
        // .nullable()
        .refine(
          (value: null | number) => {
            return value;
          },
          { message: $t('ui.formRules.required', [$t('customer.customerSn')]) },
        ),
    },
    {
      fieldName: 'type',
      label: $t('customer.customerType'),
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.LIC_CUSTOMER_TYPE, 'number'),
      },
    },
    {
      fieldName: 'contacts',
      label: $t('customer.contacts'),
      rules: 'required',
      component: 'Input',
      dependencies: {
        triggerFields: ['id'],
        show: (values) => !values.id || hasAccessByRoles(['business']),
      },
    },
    {
      fieldName: 'areaIds',
      label: $t('customer.area'),
      rules: 'selectRequired',
      component: 'ApiCascader',
      componentProps: {
        api: getAreaTree,
        expandTrigger: 'hover',
        changeOnSelect: true,
        fieldNames: {
          label: 'name',
          value: 'id',
          children: 'children',
        },
        showSearch: true,
      },
    },
    {
      fieldName: 'role',
      label: $t('customer.role'),
      component: 'Input',
      dependencies: {
        triggerFields: ['id'],
        show: (values) => !values.id || hasAccessByRoles(['business']),
      },
    },
    {
      fieldName: 'phone',
      label: $t('customer.phone'),
      component: 'Input',
      dependencies: {
        triggerFields: ['id'],
        show: (values) => !values.id || hasAccessByRoles(['business']),
      },
    },
    {
      fieldName: 'email',
      label: $t('customer.email'),
      component: 'Input',
      rules: z.string().email().or(z.literal('')).optional(),
    },
    {
      fieldName: 'remark',
      label: $t('customer.remarks'),
      component: 'Textarea',
      formItemClass: 'col-span-2',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'name',
      label: $t('customer.customerName'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'type',
      label: $t('customer.customerType'),
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.LIC_CUSTOMER_TYPE, 'number'),
      },
    },
    {
      fieldName: 'code',
      label: $t('customer.customerSn'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'contacts',
      label: $t('customer.contacts'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'createTime',
      label: $t('customer.creationTime'),
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<CustomerApi.Customer>['columns'] {
  return [
    {
      field: 'name',
      title: $t('customer.customerName'),
      minWidth: 120,
    },
    {
      field: 'code',
      title: $t('customer.customerSn'),
      minWidth: 120,
    },
    {
      field: 'type',
      title: $t('customer.customerType'),
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.LIC_CUSTOMER_TYPE },
      },
    },
    {
      field: 'contacts',
      title: $t('customer.contacts'),
      minWidth: 120,
      visible: hasAccessByRoles(['business']),
    },
    {
      field: 'areaNames',
      title: $t('customer.area'),
      minWidth: 120,
    },
    {
      field: 'role',
      title: $t('customer.role'),
      minWidth: 120,
      visible: hasAccessByRoles(['business']),
    },
    {
      field: 'phone',
      title: $t('customer.phone'),
      minWidth: 120,
      visible: hasAccessByRoles(['business']),
    },
    {
      field: 'email',
      title: $t('customer.email'),
      minWidth: 120,
    },
    {
      field: 'remark',
      title: $t('customer.remarks'),
      minWidth: 120,
    },
    {
      field: 'createTime',
      title: $t('customer.creationTime'),
      minWidth: 120,
      formatter: 'formatDateTime',
    },
    {
      field: 'operation',
      title: $t('customer.operation'),
      minWidth: 200,
      align: 'center',
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 客户导入的表单 */
export function useImportFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'file',
      label: '客户数据',
      component: 'Upload',
      rules: 'required',
      help: '仅允许导入 xls、xlsx 格式文件',
    },
    {
      fieldName: 'updateSupport',
      label: '是否覆盖',
      component: 'Switch',
      componentProps: {
        checkedChildren: '是',
        unCheckedChildren: '否',
      },
      rules: z.boolean().default(false),
      help: '是否更新已经存在的客户数据',
    },
  ];
}
