import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CustomerApi } from '#/api/license/customer';
import type { LicenseApi } from '#/api/license/license';
import type { ProjectApi } from '#/api/license/project';
import type { DescriptionItemSchema } from '#/components/description';

import { h, ref } from 'vue';

import { formatDate, formatDateTime } from '@vben/utils';

import dayjs, { Dayjs } from 'dayjs';

import { z } from '#/adapter/form';
import { getCustomerList } from '#/api/license/customer';
import { isLicenseSnUnique } from '#/api/license/license';
import { getProjectList } from '#/api/license/project';
import { getLicenseAdminList, getSimpleUserList } from '#/api/system/user';
import { DictTag } from '#/components/dict-tag';
import { $t } from '#/locales';
import { DICT_TYPE, getDictOptions, getRangePickerDefaultProps } from '#/utils';

const customerList = ref<CustomerApi.Customer[]>([]);
const projectList = ref<ProjectApi.Project[]>([]);
export const formData = ref<LicenseApi.License>();

/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'customerId',
      label: $t('license.customer'),
      rules: 'selectRequired',
      component: 'Select',
      dependencies: {
        triggerFields: ['id'],
        disabled: (values) => !!values.id,
        componentProps: async () => {
          customerList.value = await getCustomerList();

          return {
            options: customerList,
          };
        },
      },
      componentProps: {
        options: customerList,
        allowClear: true,
        fieldNames: { label: 'name', value: 'id' },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.name.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      fieldName: 'projectId',
      label: $t('license.project'),
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: projectList,
        allowClear: true,
        fieldNames: { label: 'name', value: 'id' },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.name.toLowerCase().includes(input.toLowerCase()),
      },
      dependencies: {
        componentProps: async (values) => {
          projectList.value = await (values.id
            ? getProjectList({
                customerId: values.customerId,
              })
            : getProjectList({
                customerId: values.customerId,
              }));

          if (!values.id) {
            const hasProject = projectList.value.find((project) => {
              return project.id === values.projectId;
            });
            if (!hasProject) {
              values.projectId = undefined;
            }
          }

          return {
            options: projectList,
          };
        },
        triggerFields: ['customerId', 'id'],
        disabled: (values) => !!values.id,
      },
    },
    {
      fieldName: 'serialNo',
      label: 'SN',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      dependencies: {
        trigger(values, form) {
          if (values.id) {
            return;
          }
          const project = projectList.value.find((project) => {
            return project.id === values.projectId;
          });
          const customerCode = customerList.value.find((customer) => {
            return customer.id === values.customerId;
          })?.code;
          form.setFieldValue(
            'serialNo',
            project?.serialNo ?? `${customerCode || ''}${project?.code || ''}`,
          );
        },
        // 只有指定的字段改变时，才会触发
        triggerFields: ['customerId', 'projectId', 'id'],
      },
      rules: z.string().refine(
        async (value: string) => {
          return await isLicenseSnUnique(value, formData.value?.id);
        },
        (value) => ({
          message: $t('ui.formRules.alreadyExists', ['SN', value]),
        }),
      ),
    },
    {
      fieldName: 'expiryDate',
      label: $t('license.expiryDate'),
      rules: 'selectRequired',
      component: 'DatePicker',
      componentProps: {
        // showTime: true,
        format: 'YYYY-MM-DD',
        valueFormat: 'x',
        disabledDate: (current: Dayjs) => {
          // Can not select days before today and today
          return current && current < dayjs().startOf('day');
        },
        presets: [
          { label: '七天', value: dayjs().add(+7, 'd') },
          { label: '一个月', value: dayjs().add(+1, 'month') },
          { label: '三个月', value: dayjs().add(+3, 'month') },
          { label: '半年', value: dayjs().add(+6, 'month') },
          { label: '一年', value: dayjs().add(+1, 'year') },
          { label: '三年', value: dayjs().add(+3, 'year') },
          { label: '永久', value: dayjs('2099-12-31') },
        ],
      },
    },
    {
      fieldName: 'approver',
      label: $t('license.approver'),
      component: 'ApiSelect',
      rules: 'selectRequired',
      help: $t('license.licenseAdminHelp'),
      componentProps: {
        allowClear: true,
        api: async () => {
          const data = await getLicenseAdminList();
          return data.map((item) => ({
            label: item.nickname,
            value: item.id,
          }));
        },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.label.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      fieldName: 'neCodeList',
      label: $t('license.neList'),
      component: '',
      formItemClass: 'col-span-2 items-baseline',
      modelPropName: 'modelValue',
      rules: z.array(z.object({})),
    },
    {
      fieldName: 'userNumber',
      label: $t('license.userNumber'),
      component: 'InputNumber',
      componentProps: {
        min: 10,
      },
      rules: z
        .number()
        .multipleOf(10, '用户数必须是10的倍数')
        .nullable()
        .optional(),
    },
    {
      fieldName: 'ranNumber',
      label: $t('license.ranNumber'),
      component: 'InputNumber',
      componentProps: {
        min: 0,
      },
    },
    {
      fieldName: 'remark',
      label: $t('license.remark'),
      component: 'Textarea',
      formItemClass: 'col-span-2',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'serialNo',
      label: 'SN',
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'customerId',
      label: $t('license.customer'),
      component: 'ApiSelect',
      componentProps: {
        api: async () => {
          customerList.value = await getCustomerList();
          return customerList.value;
        },
        allowClear: true,
        fieldNames: { label: 'name', value: 'id' },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.name.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      fieldName: 'applicant',
      label: $t('license.applicant'),
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        api: async () => {
          const data = await getSimpleUserList();
          return data.map((item) => ({
            label: item.nickname,
            value: item.id,
          }));
        },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.label.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      fieldName: 'approver',
      label: $t('license.approver'),
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        api: async () => {
          const data = await getLicenseAdminList();
          return data.map((item) => ({
            label: item.nickname,
            value: item.id,
          }));
        },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.label.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      fieldName: 'status',
      label: $t('license.status'),
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.LIC_LICENSE_STATUS, 'number'),
      },
    },
    {
      fieldName: 'expiryDate',
      label: $t('license.expiryDate'),
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        showTime: false,
        allowClear: true,
      },
    },
    {
      fieldName: 'applicationTime',
      label: $t('license.applicationTime'),
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<LicenseApi.License>['columns'] {
  return [
    {
      field: 'customerName',
      title: $t('customer.customerName'),
      minWidth: 120,
    },
    {
      field: 'projectName',
      title: $t('project.name'),
      minWidth: 120,
    },
    {
      field: 'serialNo',
      title: 'SN',
      minWidth: 120,
    },
    {
      field: 'expiryDate',
      title: $t('license.expiryDate'),
      minWidth: 120,
      formatter: 'formatDate',
    },
    {
      field: 'userNumber',
      title: $t('license.userNumber'),
      minWidth: 120,
    },
    {
      field: 'ranNumber',
      title: $t('license.ranNumber'),
      minWidth: 120,
    },
    {
      field: 'applicantName',
      title: $t('license.applicant'),
      minWidth: 120,
    },
    {
      field: 'approverName',
      title: $t('license.approver'),
      minWidth: 120,
    },
    {
      field: 'status',
      title: $t('license.status'),
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.LIC_LICENSE_STATUS },
      },
    },
    {
      field: 'remark',
      title: $t('license.remark'),
      visible: false,
      minWidth: 120,
    },
    {
      field: 'applicationTime',
      title: $t('license.applicationTime'),
      minWidth: 120,
      formatter: 'formatDateTime',
    },
    {
      field: 'applyCount',
      title: $t('license.applyCount'),
      minWidth: 120,
    },
    {
      field: 'operation',
      title: $t('license.operation'),
      minWidth: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 详情页的字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      field: 'customerName',
      label: $t('customer.customerName'),
    },
    {
      field: 'projectName',
      label: $t('project.name'),
    },
    {
      field: 'serialNo',
      label: 'SN',
    },
    {
      field: 'expiryDate',
      label: $t('license.expiryDate'),
      content: (data) => {
        if (data.oldLicense && data.oldLicense.expiryDate !== data.expiryDate) {
          const after = h(
            'span',
            {
              style: {
                color: 'red',
              },
            },
            ` → ${formatDate(data.expiryDate)}`,
          );
          return h('div', {}, [
            formatDate(data.oldLicense.expiryDate) as string,
            after,
          ]);
        }
        return formatDate(data?.expiryDate) as string;
      },
    },
    {
      field: 'userNumber',
      label: $t('license.userNumber'),
      content: (data) => {
        if (data.oldLicense && data.oldLicense.userNumber !== data.userNumber) {
          const after = h(
            'span',
            {
              style: {
                color: 'red',
              },
            },
            ` → ${data.userNumber ?? ''}`,
          );
          return h('div', {}, [data.oldLicense.userNumber, after]);
        }
        return data.userNumber;
      },
    },
    {
      field: 'ranNumber',
      label: $t('license.ranNumber'),
      content: (data) => {
        if (data.oldLicense && data.oldLicense.ranNumber !== data.ranNumber) {
          const after = h(
            'span',
            {
              style: {
                color: 'red',
              },
            },
            ` → ${data.ranNumber ?? ''}`,
          );
          return h('div', {}, [data.oldLicense.ranNumber, after]);
        }
        return data.ranNumber;
      },
    },
    {
      field: 'applicantName',
      label: $t('license.applicant'),
    },
    {
      field: 'applicationTime',
      label: $t('license.applicationTime'),
      content: (data) => {
        return formatDateTime(data?.applicationTime) as string;
      },
    },
    {
      field: 'approverName',
      label: $t('license.approverName'),
      hidden: (data) => data.status !== 3,
    },
    {
      field: 'status',
      label: $t('license.status'),
      content: (data) => {
        return h(DictTag, {
          type: DICT_TYPE.LIC_LICENSE_STATUS,
          value: data.status,
        });
      },
    },
    {
      field: 'remark',
      label: $t('license.remark'),
      hidden: (data) => !data.remark,
    },
  ];
}

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