import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn, VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ProjectApi } from '#/api/license/project';
import type { SystemUserApi } from '#/api/system/user';

import { ref } from 'vue';

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

import { z } from '#/adapter/form';
import { getCustomerList } from '#/api/license/customer';
import {
  isProjectCodeUnique,
  isProjectNameUnique,
} from '#/api/license/project';
import { getSimpleUserList } from '#/api/system/user';
import { $t } from '#/locales';
import { DICT_TYPE, getDictOptions, getRangePickerDefaultProps } from '#/utils';

const userList = ref<SystemUserApi.User[]>();

const getUserList = async () => {
  userList.value = await getSimpleUserList();
  userList.value = userList.value.filter((item) => item.nickname !== '管理员'); // 过滤掉系统用户
};

getUserList();

const { hasAccessByCodes } = useAccess();

export const formData = ref<ProjectApi.Project>();
/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'name',
      label: $t('project.name'),
      component: 'Input',
      rules: z
        .string()
        .min(1, $t('ui.formRules.required', [$t('project.name')]))
        .max(60, $t('ui.formRules.maxLength', [$t('project.name'), 60]))
        .refine(
          async (value: string) => {
            return await isProjectNameUnique(value, formData.value?.id);
          },
          (value) => ({
            message: $t('ui.formRules.alreadyExists', [
              $t('project.name'),
              value,
            ]),
          }),
        ),
    },
    {
      fieldName: 'code',
      label: $t('project.code'),
      component: 'InputNumber',
      rules: z
        .number({ message: $t('ui.formRules.required', [$t('project.code')]) })
        .min(1000, $t('ui.formRules.range', [$t('project.code'), 1000, 9999]))
        .max(9999, $t('ui.formRules.range', [$t('project.code'), 1000, 9999]))
        .refine(
          async (value: number) => {
            return await isProjectCodeUnique(value, formData.value?.id);
          },
          (value) => ({
            message: $t('ui.formRules.alreadyExists', [
              $t('project.code'),
              value,
            ]),
          }),
        )
        .refine(
          (value: null | number) => {
            return value;
          },
          { message: $t('ui.formRules.required', [$t('project.code')]) },
        ),
    },
    {
      fieldName: 'customerId',
      label: $t('project.belongCustomer'),
      rules: 'selectRequired',
      component: 'ApiSelect',
      componentProps: {
        api: async () => {
          const data = await getCustomerList();
          return data.map((item) => ({
            // label: `${item.name}（${item.code}）`,
            label: item.name,
            value: item.id,
          }));
        },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.label.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      fieldName: 'contractCode',
      label: $t('project.contractCode'),
      rules: z.string().min(1, '注意：没有合同编号的情况下填0'),
      component: 'Input',
      help: '没有合同编号的情况下填0',
      componentProps: {
        placeholder: '请输入，没有合同编号的填0',
      },
    },
    {
      fieldName: 'businessStatus',
      label: $t('project.businessStatus'),
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.LIC_BUSINESS_STATUS, 'number'),
      },
    },
    {
      fieldName: 'status',
      label: $t('project.status'),
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.LIC_PROJECT_STATUS, 'number'),
      },
    },
    {
      fieldName: 'businessOwner',
      label: $t('project.businessOwner'),
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: userList,
        allowClear: true,
        showSearch: true,
        fieldNames: { label: 'nickname', value: 'id' },
        filterOption: (input: string, option: any) => {
          return option.nickname.toLowerCase().includes(input.toLowerCase());
        },
      },
    },
    {
      fieldName: 'customerOwner',
      label: $t('project.customerOwner'),
      rules: 'required',
      component: 'Input',
    },
    {
      fieldName: 'technicalOwnerA',
      label: $t('project.technicalOwnerA'),
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: userList,
        allowClear: true,
        showSearch: true,
        fieldNames: { label: 'nickname', value: 'id' },
        filterOption: (input: string, option: any) => {
          return option.nickname.toLowerCase().includes(input.toLowerCase());
        },
      },
    },
    {
      fieldName: 'technicalOwnerB',
      label: $t('project.technicalOwnerB'),
      component: 'Select',
      componentProps: {
        options: userList,
        allowClear: true,
        showSearch: true,
        fieldNames: { label: 'nickname', value: 'id' },
        filterOption: (input: string, option: any) => {
          return option.nickname.toLowerCase().includes(input.toLowerCase());
        },
      },
    },
    // {
    //   fieldName: 'technicalOwnerC',
    //   label: $t('project.technicalOwnerC'),
    //   component: 'Select',
    //   componentProps: {
    //     options: userList,
    //     allowClear: true,
    //     showSearch: true,
    //     fieldNames: { label: 'nickname', value: 'id' },
    //     filterOption: (input: string, option: any) => {
    //       return option.nickname.toLowerCase().includes(input.toLowerCase());
    //     },
    //   },
    // },
    {
      fieldName: 'startTime',
      label: $t('project.startTime'),
      component: 'DatePicker',
      rules: 'selectRequired',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'x',
      },
    },
    {
      fieldName: 'endTime',
      label: $t('project.endTime'),
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'x',
      },
    },
    {
      fieldName: 'envInfo',
      label: $t('project.envInfo'),
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.LIC_ENV_INFO, 'number'),
      },
    },
    {
      fieldName: 'operatingSystem',
      label: $t('project.operatingSystem'),
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.LIC_OPERATING_SYSTEM, 'number'),
      },
    },
    {
      fieldName: 'softwareVersion',
      label: $t('project.softwareVersion'),
      rules: 'selectRequired',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.LIC_SOFTWARE_VERSION, 'number'),
      },
    },
    {
      fieldName: 'remark',
      label: $t('project.remarks'),
      component: 'Textarea',
      formItemClass: 'col-span-2',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'serialNo',
      label: 'SN',
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'customerId',
      label: $t('project.belongCustomer'),
      component: 'ApiSelect',
      componentProps: {
        api: async () => {
          const data = await getCustomerList();
          return data.map((item) => ({
            // label: `${item.name}（${item.code}）`,
            label: item.name,
            value: item.id,
          }));
        },
        showSearch: true,
        filterOption: (input: string, option: any) =>
          option.label.toLowerCase().includes(input.toLowerCase()),
      },
    },
    {
      fieldName: 'status',
      label: $t('project.status'),
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.LIC_PROJECT_STATUS, 'number'),
      },
    },
    {
      fieldName: 'technicalOwner',
      label: $t('project.technicalOwner'),
      component: 'Select',
      componentProps: {
        options: userList,
        allowClear: true,
        showSearch: true,
        fieldNames: { label: 'nickname', value: 'id' },
        filterOption: (input: string, option: any) => {
          return option.nickname.toLowerCase().includes(input.toLowerCase());
        },
      },
    },
    {
      fieldName: 'businessStatus',
      label: $t('project.businessStatus'),
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.LIC_BUSINESS_STATUS, 'number'),
      },
    },
    {
      fieldName: 'name',
      label: $t('project.name'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'code',
      label: $t('project.code'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'contractCode',
      label: $t('project.contractCode'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'businessOwner',
      label: $t('project.businessOwner'),
      component: 'Select',
      componentProps: {
        options: userList,
        allowClear: true,
        showSearch: true,
        fieldNames: { label: 'nickname', value: 'id' },
        filterOption: (input: string, option: any) => {
          return option.nickname.toLowerCase().includes(input.toLowerCase());
        },
      },
    },
    {
      fieldName: 'customerOwner',
      label: $t('project.customerOwner'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    // {
    //   fieldName: 'startTime',
    //   label: $t('project.startTime'),
    //   component: 'RangePicker',
    //   componentProps: {
    //     ...getRangePickerDefaultProps(),
    //     allowClear: true,
    //   },
    // },
    // {
    //   fieldName: 'endTime',
    //   label: $t('project.endTime'),
    //   component: 'RangePicker',
    //   componentProps: {
    //     ...getRangePickerDefaultProps(),
    //     allowClear: true,
    //   },
    // },
    // {
    //   fieldName: 'envInfo',
    //   label: $t('project.envInfo'),
    //   component: 'Input',
    //   componentProps: {
    //     allowClear: true,
    //   },
    // },
    {
      fieldName: 'createTime',
      label: $t('project.creationTime'),
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(
  onActionClick?: OnActionClickFn<ProjectApi.Project>,
): VxeTableGridOptions<ProjectApi.Project>['columns'] {
  return [
    {
      field: 'customerName',
      title: $t('customer.customerName'),
      minWidth: 120,
    },
    {
      field: 'name',
      title: $t('project.name'),
      minWidth: 120,
    },
    {
      field: 'code',
      title: $t('project.code'),
      minWidth: 120,
      visible: false,
    },
    {
      field: 'startTime',
      title: $t('project.startTime'),
      minWidth: 120,
      formatter: 'formatDate',
    },
    {
      field: 'contractCode',
      title: $t('project.contractCode'),
      minWidth: 120,
    },
    {
      field: 'serialNo',
      title: 'SN',
      minWidth: 120,
    },
    {
      field: 'businessStatus',
      title: $t('project.businessStatus'),
      minWidth: 120,
      visible: false,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.LIC_BUSINESS_STATUS },
      },
    },
    {
      field: 'status',
      title: $t('project.status'),
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.LIC_PROJECT_STATUS },
      },
    },
    {
      field: 'businessOwnerName',
      title: $t('project.businessOwner'),
      minWidth: 120,
    },
    {
      field: 'customerOwner',
      title: $t('project.customerOwner'),
      visible: false,
      minWidth: 120,
    },
    {
      field: 'technicalOwnerAName',
      title: $t('project.technicalOwnerA'),
      minWidth: 120,
    },
    {
      field: 'technicalOwnerBName',
      title: $t('project.technicalOwnerB'),
      minWidth: 120,
    },
    // {
    //   field: 'technicalOwnerCName',
    //   title: $t('project.technicalOwnerC'),
    //   minWidth: 120,
    // },
    {
      field: 'endTime',
      title: $t('project.endTime'),
      visible: false,
      minWidth: 120,
      formatter: 'formatDate',
    },
    {
      field: 'envInfo',
      title: $t('project.envInfo'),
      visible: false,
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.LIC_ENV_INFO },
      },
    },
    {
      field: 'operatingSystem',
      title: $t('project.operatingSystem'),
      visible: false,
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.LIC_OPERATING_SYSTEM },
      },
    },
    {
      field: 'softwareVersion',
      title: $t('project.softwareVersion'),
      visible: false,
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.LIC_SOFTWARE_VERSION },
      },
    },
    {
      field: 'remark',
      title: $t('project.remarks'),
      visible: false,
      minWidth: 120,
    },
    {
      field: 'commentNum',
      title: $t('project.commentNum'),
      minWidth: 90,
    },
    {
      field: 'applyCount',
      title: $t('license.applyCount'),
      minWidth: 120,
    },
    {
      field: 'updateTime',
      title: $t('project.updateTime'),
      minWidth: 130,
      sortable: true,
      formatter: 'formatDateTime',
    },
    {
      field: 'createTime',
      title: $t('project.creationTime'),
      minWidth: 130,
      formatter: 'formatDateTime',
    },
    {
      field: 'operation',
      title: $t('project.operation'),
      minWidth: 200,
      align: 'center',
      fixed: 'right',
      headerAlign: 'center',
      showOverflow: false,
      cellRender: {
        attrs: {
          nameField: 'name',
          nameTitle: $t('project.project'),
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          {
            code: 'edit',
            show: hasAccessByCodes(['license:project:update']),
          },
          {
            code: 'progress',
            text: $t('project.progress'),
            show: hasAccessByCodes(['license:project:comment']),
          },
          {
            code: 'delete',
            show: hasAccessByCodes(['license:project:delete']),
          },
        ],
      },
    },
  ];
}

/** 项目导入的表单 */
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: '是否更新已经存在的项目数据',
    },
  ];
}
