import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { LicenseApi } from '#/api/license/license';

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

import { getCustomerList } from '#/api/license/customer';
import { getProjectList } from '#/api/license/project';
import { getLicenseAdminList, getSimpleUserList } from '#/api/system/user';
import { $t } from '#/locales';
import { DICT_TYPE, getDictOptions, getRangePickerDefaultProps } from '#/utils';

const { hasAccessByCodes } = useAccess();
let projectList = await getProjectList({});
const customerList = await getCustomerList();

/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'customerId',
      label: $t('license.customer'),
      rules: 'required',
      component: 'Select',
      componentProps: {
        options: customerList,
        fieldNames: { label: 'name', value: 'id' },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.label.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      fieldName: 'projectId',
      label: $t('license.project'),
      rules: 'required',
      component: 'Select',
      componentProps: {
        options: projectList,
        fieldNames: { label: 'name', value: 'id' },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.label.toLowerCase().includes(input.toLowerCase()),
      },
      dependencies: {
        componentProps: async (values) => {
          projectList = await getProjectList({
            customerId: values.customerId,
          });
          const hasProject = projectList.find((project) => {
            return project.id === values.projectId;
          });
          if (!hasProject) {
            values.projectId = '';
          }
          return {
            options: projectList,
          };
        },
        triggerFields: ['customerId'],
      },
    },
    {
      fieldName: 'sn',
      label: 'sn',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      dependencies: {
        trigger(values, form) {
          const projectCode = projectList.find((project) => {
            return project.id === values.projectId;
          })?.code;
          const customerCode = customerList.find((customer) => {
            return customer.id === values.customerId;
          })?.code;
          form.setFieldValue('sn', `${customerCode || ''}${projectCode || ''}`);
        },
        // 只有指定的字段改变时，才会触发
        triggerFields: ['customerId', 'projectId'],
      },
    },
    {
      fieldName: 'expirationTime',
      label: $t('license.expirationTime'),
      rules: 'required',
      component: 'DatePicker',
      componentProps: {
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'x',
      },
    },
    {
      fieldName: 'neSwitch',
      label: $t('license.neSwitch'),
      component: 'CheckboxGroup',
      formItemClass: 'col-span-2',
      modelPropName: 'modelValue',
    },
    // {
    //   fieldName: 'baseStationNum',
    //   label: $t('license.baseStationNum'),
    //   component: 'InputNumber',
    //   componentProps: {
    //     min: 0,
    //   },
    // },
    {
      fieldName: 'activationCode',
      label: $t('license.activationCode'),
      component: 'Textarea',
      formItemClass: 'col-span-2',
    },
    // {
    //   fieldName: 'licenseContent',
    //   label: $t('license.licenseContent'),
    //   component: 'Textarea',
    // },
    // {
    //   fieldName: 'applicant',
    //   label: $t('license.applicant'),
    //   component: 'Select',
    //   componentProps: {
    //     options: [],
    //   },
    // },
    {
      fieldName: 'approver',
      label: $t('license.approver'),
      component: 'ApiSelect',
      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: 'userNum',
      label: $t('license.userNum'),
      component: 'InputNumber',
      componentProps: {
        min: 0,
      },
    },
    // {
    //   fieldName: 'status',
    //   label: $t('license.status'),
    //   component: 'Select',
    //   componentProps: {
    //     options: getDictOptions(DICT_TYPE.LIC_LICENSE_STATUS, 'number'),
    //     buttonStyle: 'solid',
    //     optionType: 'button',
    //   },
    // },
    {
      fieldName: 'remark',
      label: $t('license.remark'),
      component: 'Textarea',
      formItemClass: 'col-span-2',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'customerId',
      label: $t('license.customer'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'projectId',
      label: $t('license.project'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'sn',
      label: 'sn',
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'expirationTime',
      label: $t('license.expirationTime'),
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
    {
      fieldName: 'neSwitch',
      label: $t('license.neSwitch'),
      component: 'Select',
      componentProps: {
        allowClear: true,
        mode: 'multiple',
        options: getDictOptions(DICT_TYPE.LIC_NE_SWITCH, 'number'),
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.label.toLowerCase().includes(input.toLowerCase()),
      },
    },
    // {
    //   fieldName: 'userNum',
    //   label: $t('license.userNum'),
    //   component: 'Input',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
    // {
    //   fieldName: 'baseStationNum',
    //   label: $t('license.baseStationNum'),
    //   component: 'Input',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
    // {
    //   fieldName: 'activationCode',
    //   label: $t('license.activationCode'),
    //   component: 'Input',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
    // {
    //   fieldName: 'licenseContent',
    //   label: $t('license.licenseContent'),
    //   component: 'Input',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
    {
      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: 'remark',
    //   label: $t('license.remark'),
    //   component: 'Input',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
    {
      fieldName: 'createTime',
      label: $t('license.creationTime'),
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(
  onActionClick?: OnActionClickFn<LicenseApi.License>,
): VxeTableGridOptions<LicenseApi.License>['columns'] {
  return [
    {
      field: 'customerName',
      title: $t('license.customer'),
      minWidth: 120,
    },
    {
      field: 'projectName',
      title: $t('license.project'),
      minWidth: 120,
    },
    {
      field: 'sn',
      title: 'sn',
      minWidth: 120,
    },
    {
      field: 'expirationTime',
      title: $t('license.expirationTime'),
      minWidth: 120,
      formatter: 'formatDateTime',
    },
    {
      field: 'neSwitch',
      title: $t('license.neSwitch'),
      minWidth: 120,
      cellRender: {
        name: 'CellDictGroup',
        props: { type: DICT_TYPE.LIC_NE_SWITCH },
      },
    },
    {
      field: 'userNum',
      title: $t('license.userNum'),
      minWidth: 120,
    },
    // {
    //   field: 'baseStationNum',
    //   title: $t('license.baseStationNum'),
    //   minWidth: 120,
    // },
    {
      field: 'activationCode',
      title: $t('license.activationCode'),
      minWidth: 120,
    },
    {
      field: 'licenseContent',
      title: $t('license.licenseContent'),
      minWidth: 120,
    },
    {
      field: 'applicant',
      title: $t('license.applicant'),
      minWidth: 120,
    },
    {
      field: 'approver',
      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'),
      minWidth: 120,
    },
    {
      field: 'createTime',
      title: $t('license.creationTime'),
      minWidth: 120,
      formatter: 'formatDateTime',
    },
    {
      field: 'operation',
      title: $t('license.operation'),
      minWidth: 200,
      align: 'center',
      fixed: 'right',
      headerAlign: 'center',
      showOverflow: false,
      cellRender: {
        attrs: {
          nameField: 'id',
          nameTitle: 'License',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          {
            code: 'edit',
            show: hasAccessByCodes(['license:license:update']),
          },
          {
            code: 'delete',
            show: hasAccessByCodes(['license:license:delete']),
          },
        ],
      },
    },
  ];
}
