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

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 { hasAccessByCodes } = useAccess();

// const userList = await getSimpleUserList();

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()
        .min(2000, $t('ui.formRules.range', [$t('project.code'), 2000, 9999]))
        .max(9999, $t('ui.formRules.range', [$t('project.code'), 2000, 9999]))
        .refine(
          async (value: number) => {
            return await isProjectCodeUnique(value, formData.value?.id);
          },
          (value) => ({
            message: $t('ui.formRules.alreadyExists', [
              $t('project.code'),
              value,
            ]),
          }),
        )
        .nullable()
        .refine(
          (value: null | number) => {
            return value;
          },
          { message: $t('ui.formRules.required', [$t('project.code')]) },
        ),
    },
    {
      fieldName: 'customerId',
      label: $t('project.belongCustomer'),
      rules: 'required',
      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: 'required',
      component: 'Input',
    },
    {
      fieldName: 'businessStatus',
      label: $t('project.businessStatus'),
      rules: 'required',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.LIC_BUSINESS_STATUS, 'number'),
      },
    },
    {
      fieldName: 'status',
      label: $t('project.status'),
      rules: 'required',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.LIC_PROJECT_STATUS, 'number'),
      },
    },
    {
      fieldName: 'businessOwner',
      label: $t('project.businessOwner'),
      rules: 'required',
      component: 'Input',
    },
    {
      fieldName: 'customerOwner',
      label: $t('project.customerOwner'),
      rules: 'required',
      component: 'Input',
    },
    {
      fieldName: 'technicalOwnerA',
      label: $t('project.technicalOwnerA'),
      rules: 'required',
      component: 'Input',
    },
    {
      fieldName: 'technicalOwnerB',
      label: $t('project.technicalOwnerB'),
      component: 'Input',
    },
    {
      fieldName: 'technicalOwnerC',
      label: $t('project.technicalOwnerC'),
      component: 'Input',
    },
    {
      fieldName: 'startTime',
      label: $t('project.startTime'),
      component: 'DatePicker',
      rules: 'required',
      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: 'required',
      component: 'Input',
    },
    // {
    //   fieldName: 'envFileId',
    //   label: $t('project.envInfoFile'),
    //   component: 'Input',
    // },
    {
      fieldName: 'remark',
      label: $t('project.remarks'),
      component: 'Textarea',
      formItemClass: 'col-span-2',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      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: 'businessStatus',
      label: $t('project.businessStatus'),
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.LIC_BUSINESS_STATUS, 'number'),
      },
    },
    {
      fieldName: 'businessOwner',
      label: $t('project.businessOwner'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'customerOwner',
      label: $t('project.customerOwner'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'technicalOwnerA',
      label: $t('project.technicalOwnerA'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'technicalOwnerB',
      label: $t('project.technicalOwnerB'),
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
    },
    {
      fieldName: 'technicalOwnerC',
      label: $t('project.technicalOwnerC'),
      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: 'status',
      label: $t('project.status'),
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.LIC_PROJECT_STATUS, 'number'),
      },
    },
    {
      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: 'name',
      title: $t('project.name'),
      minWidth: 120,
    },
    {
      field: 'code',
      title: $t('project.code'),
      minWidth: 120,
      visible: false,
    },
    {
      field: 'customerName',
      title: $t('project.belongCustomer'),
      minWidth: 120,
    },
    {
      field: 'startTime',
      title: $t('project.startTime'),
      minWidth: 120,
      formatter: 'formatDate',
    },
    {
      field: 'contractCode',
      title: $t('project.contractCode'),
      minWidth: 120,
    },
    {
      field: 'sn',
      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: 'businessOwner',
      title: $t('project.businessOwner'),
      minWidth: 120,
    },
    {
      field: 'customerOwner',
      title: $t('project.customerOwner'),
      visible: false,
      minWidth: 120,
    },
    {
      field: 'technicalOwnerA',
      title: $t('project.technicalOwnerA'),
      minWidth: 120,
    },
    {
      field: 'technicalOwnerB',
      title: $t('project.technicalOwnerB'),
      minWidth: 120,
    },
    {
      field: 'technicalOwnerC',
      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,
    },
    {
      field: 'remark',
      title: $t('project.remarks'),
      visible: false,
      minWidth: 120,
    },
    {
      field: 'createTime',
      title: $t('project.creationTime'),
      visible: false,
      minWidth: 120,
      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:update']),
          },
          {
            code: 'delete',
            show: hasAccessByCodes(['license:project:delete']),
          },
        ],
      },
    },
  ];
}
