import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn, 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 { useAccess } from '@vben/access';
import { downloadFileFromBlobPart, formatDateTime } from '@vben/utils';

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

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, DictTagGroup } from '#/components/dict-tag';
import { $t } from '#/locales';
import { DICT_TYPE, getDictOptions, getRangePickerDefaultProps } from '#/utils';

const { hasAccessByCodes } = useAccess();
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: 'required',
      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: 'projectId',
      label: $t('license.project'),
      rules: 'required',
      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 getProjectList({
            customerId: values.customerId,
          });
          const hasProject = projectList.value.find((project) => {
            return project.id === values.projectId;
          });
          if (!hasProject) {
            values.projectId = '';
          }
          return {
            options: projectList,
          };
        },
        triggerFields: ['customerId'],
      },
    },
    {
      fieldName: 'serialNo',
      label: 'SN',
      component: 'Input',
      componentProps: {
        disabled: true,
      },
      dependencies: {
        trigger(values, form) {
          const projectCode = projectList.value.find((project) => {
            return project.id === values.projectId;
          })?.code;
          const customerCode = customerList.value.find((customer) => {
            return customer.id === values.customerId;
          })?.code;
          form.setFieldValue(
            'serialNo',
            `${customerCode || ''}${projectCode || ''}`,
          );
        },
        // 只有指定的字段改变时，才会触发
        triggerFields: ['customerId', 'projectId'],
      },
      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: 'required',
      component: 'DatePicker',
      componentProps: {
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'x',
      },
    },
    {
      fieldName: 'neList',
      label: $t('license.neList'),
      component: 'CheckboxGroup',
      formItemClass: 'col-span-2',
      modelPropName: 'modelValue',
    },
    {
      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: 'userNumber',
      label: $t('license.userNumber'),
      component: 'InputNumber',
      componentProps: {
        min: 0,
      },
    },
    {
      fieldName: 'ranNumber',
      label: $t('license.ranNumber'),
      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',
    },
    {
      fieldName: 'approver',
      label: $t('license.approver'),
      component: 'ApiSelect',
      rules: 'required',
      help: $t('license.licenseAdminHelp'),
      dependencies: {
        triggerFields: [''],
        show: () => formData.value?.action === 1,
      },
      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()),
      },
    },
  ];
}

/** 列表的搜索表单 */
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: 'projectId',
    //   label: $t('license.project'),
    //   component: 'Input',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
    {
      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(),
        allowClear: true,
      },
    },
    {
      fieldName: 'neList',
      label: $t('license.neList'),
      component: 'Select',
      componentProps: {
        allowClear: true,
        mode: 'multiple',
        options: getDictOptions(DICT_TYPE.LIC_NE_LIST, 'number'),
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.label.toLowerCase().includes(input.toLowerCase()),
      },
    },
    // {
    //   fieldName: 'userNumber',
    //   label: $t('license.userNumber'),
    //   component: 'Input',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
    // {
    //   fieldName: 'ranNumber',
    //   label: $t('license.ranNumber'),
    //   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: 'applicationTime',
      label: $t('license.applicationTime'),
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
    // {
    //   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: 'serialNo',
      title: 'SN',
      minWidth: 120,
    },
    {
      field: 'expiryDate',
      title: $t('license.expiryDate'),
      minWidth: 120,
      formatter: 'formatDateTime',
    },
    {
      field: 'neList',
      title: $t('license.neList'),
      minWidth: 120,
      cellRender: {
        name: 'CellDictGroup',
        props: { type: DICT_TYPE.LIC_NE_LIST },
      },
    },
    {
      field: 'userNumber',
      title: $t('license.userNumber'),
      minWidth: 120,
    },
    {
      field: 'ranNumber',
      title: $t('license.ranNumber'),
      minWidth: 120,
    },
    {
      field: 'activationCode',
      title: $t('license.activationCode'),
      visible: false,
      minWidth: 120,
    },
    // {
    //   field: 'licenseContent',
    //   visible: false,
    //   title: $t('license.licenseContent'),
    //   minWidth: 120,
    // },
    {
      field: 'applicantName',
      title: $t('license.applicant'),
      minWidth: 120,
    },
    {
      field: 'applicationTime',
      title: $t('license.applicationTime'),
      minWidth: 120,
      visible: false,
      formatter: 'formatDateTime',
    },
    {
      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: '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: 'serialNo',
          nameTitle: 'License',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          // {
          //   code: 'edit',
          //   show: hasAccessByCodes(['license:license:update']),
          // },
          {
            code: 'apply',
            text: $t('license.apply'),
            show: (values: LicenseApi.License) => {
              return (
                hasAccessByCodes(['license:license:apply']) &&
                values.status === 0
              );
            },
          },
          {
            code: 'generate',
            text: $t('license.generate'),
            show: (values: LicenseApi.License) => {
              return (
                hasAccessByCodes(['license:license:generate']) &&
                values.status === 1
              );
            },
          },
          {
            code: 'download',
            text: $t('license.download'),
            show: (values: LicenseApi.License) => {
              return values.status === 2;
            },
          },
          {
            code: 'delete',
            show: hasAccessByCodes(['license:license:delete']),
          },
        ],
      },
    },
  ];
}

/** 详情页的字段 */
export function useDetailSchema(): DescriptionItemSchema[] {
  return [
    {
      field: 'customerName',
      label: $t('license.customer'),
    },
    {
      field: 'projectName',
      label: $t('license.project'),
    },
    {
      field: 'serialNo',
      label: 'SN',
    },
    {
      field: 'expiryDate',
      label: $t('license.expiryDate'),
      content: (data) => {
        return formatDateTime(data?.expiryDate) as string;
      },
    },
    {
      field: 'neList',
      label: $t('license.neList'),
      content: (data) => {
        return h(DictTagGroup, {
          type: DICT_TYPE.LIC_NE_LIST,
          value: data.neList,
        });
      },
    },
    {
      field: 'userNumber',
      label: $t('license.userNumber'),
    },
    {
      field: 'ranNumber',
      label: $t('license.ranNumber'),
    },
    {
      field: 'applicantName',
      label: $t('license.applicant'),
    },
    {
      field: 'applicationTime',
      label: $t('license.applicationTime'),
      content: (data) => {
        return formatDateTime(data?.applicationTime) as string;
      },
    },
    {
      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'),
    },
    {
      field: 'fileUrl',
      label: $t('license.licenseFile'),
      hidden: (data) => data.status !== 2,
      content: (data) => {
        const fileName = `${data.fileUrl?.slice(
          Math.max(0, data.fileUrl.lastIndexOf('/') + 1),
          data.fileUrl.lastIndexOf('_'),
        )}.ini`;
        // 创建下载链接
        const link = h(
          'span',
          {
            style: {
              marginRight: '15px',
            },
          },
          fileName,
        );

        // 创建下载按钮
        const button = h(
          Button,
          {
            onClick: async () => {
              const res = await fetch(data.fileUrl);
              if (!res.ok) {
                message.error($t('license.downloadFailed'));
                return;
              }
              const blob = await res.blob();

              downloadFileFromBlobPart({ fileName, source: blob });
            },
            type: 'primary',
          },
          $t('license.download'),
        );

        // 包裹容器
        return h(
          'div',
          {
            style: {
              display: 'flex',
              alignItems: 'center',
            },
          },
          [link, button],
        );
      },
    },
  ];
}
