import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { useUserStore } from '@vben/stores';

import { getContractSimpleList } from '#/api/crm/contract';
import { getSimpleUserList } from '#/api/system/user';
import CrmCustomerSelect from '#/components/crm-customer-select.vue';

import { markRaw } from 'vue';

/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  const userStore = useUserStore();
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'no',
      label: '开票编号',
      component: 'Input',
      componentProps: {
        placeholder: '保存时自动生成',
        disabled: true,
      },
    },
    {
      fieldName: 'ownerUserId',
      label: '负责人',
      component: 'ApiSelect',
      rules: 'required',
      dependencies: {
        triggerFields: ['id'],
        disabled: (values) => !!values.id,
      },
      componentProps: {
        api: getSimpleUserList,
        labelField: 'nickname',
        valueField: 'id',
        placeholder: '请选择负责人',
        allowClear: true,
      },
      defaultValue: userStore.userInfo?.id,
    },
    {
      fieldName: 'customerId',
      label: '客户名称',
      component: markRaw(CrmCustomerSelect),
      rules: 'required',
      componentProps: (_values, form) => ({
        placeholder: '请选择客户',
        onChange: () => {
          form.setFieldValue('contractId', undefined);
          form.setFieldValue('price', undefined);
        },
      }),
      dependencies: {
        triggerFields: ['id'],
        disabled: (values) => !!values.id,
      },
    },
    {
      fieldName: 'contractId',
      label: '合同名称',
      component: 'Select',
      rules: 'required',
      dependencies: {
        triggerFields: ['customerId'],
        disabled: (values) => !values.customerId || !!values.id,
        async componentProps(values, form) {
          if (!values.customerId) {
            return {
              options: [],
              placeholder: '请先选择客户',
            };
          }
          const contracts = await getContractSimpleList(values.customerId);
          const approvedContracts = contracts.filter(
            (item) => item.auditStatus === 20,
          );
          return {
            options: approvedContracts.map((item) => {
              const remain =
                (item.totalPrice ?? 0) - (item.totalInvoicePrice ?? 0);
              return {
                label: `${item.name}（¥${item.totalPrice ?? 0}，可开票 ¥${remain.toFixed(2)}）`,
                value: item.id,
              };
            }),
            placeholder: '请选择合同',
            onChange: () => {
              form.setFieldValue('price', undefined);
            },
          } as any;
        },
      },
    },
    {
      fieldName: 'invoiceType',
      label: '发票类型',
      component: 'Select',
      rules: 'required',
      componentProps: {
        options: getDictOptions(DICT_TYPE.CRM_INVOICE_TYPE, 'number'),
        placeholder: '请选择发票类型',
      },
    },
    {
      fieldName: 'invoiceNo',
      label: '发票号码',
      component: 'Input',
      componentProps: {
        placeholder: '请输入发票号码',
        allowClear: true,
      },
    },
    {
      fieldName: 'invoiceTitle',
      label: '发票抬头',
      component: 'Input',
      componentProps: {
        placeholder: '请输入发票抬头',
        allowClear: true,
      },
    },
    {
      fieldName: 'price',
      label: '开票金额（元）',
      component: 'InputNumber',
      rules: 'required',
      componentProps: {
        class: '!w-full',
        placeholder: '请输入开票金额',
        min: 0,
        precision: 2,
      },
    },
    {
      fieldName: 'invoiceTime',
      label: '开票日期',
      component: 'DatePicker',
      rules: 'required',
      componentProps: {
        placeholder: '请选择开票日期',
        showTime: false,
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD',
      },
    },
    {
      fieldName: 'blobIds',
      label: '发票附件',
      component: 'FileUpload',
      componentProps: {
        valueKey: 'id',
        maxNumber: 10,
        multiple: true,
        accept: ['jpg', 'jpeg', 'png', 'pdf'],
        helpText: '支持jpg、jpeg、png、pdf格式，单个文件不超过2MB',
      },
      formItemClass: 'md:col-span-2',
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注',
        rows: 4,
      },
      formItemClass: 'md:col-span-2',
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'no',
      label: '开票编号',
      component: 'Input',
      componentProps: {
        placeholder: '请输入开票编号',
        allowClear: true,
      },
    },
    {
      fieldName: 'customerId',
      label: '客户',
      component: markRaw(CrmCustomerSelect),
      componentProps: {
        placeholder: '请选择客户',
        allowClear: true,
      },
    },
  ];
}

export function useGridColumns(): VxeTableGridOptions['columns'] {
  return [
    {
      title: '开票编号',
      field: 'no',
      minWidth: 160,
      fixed: 'left',
      slots: { default: 'no' },
    },
    {
      title: '客户名称',
      field: 'customerName',
      minWidth: 150,
      slots: { default: 'customerName' },
    },
    {
      title: '合同编号',
      field: 'contract',
      minWidth: 160,
      slots: { default: 'contractNo' },
    },
    {
      title: '发票类型',
      field: 'invoiceType',
      minWidth: 120,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.CRM_INVOICE_TYPE },
      },
    },
    {
      title: '发票号码',
      field: 'invoiceNo',
      minWidth: 150,
    },
    {
      title: '开票金额（元）',
      field: 'price',
      minWidth: 150,
      formatter: 'formatAmount2',
    },
    {
      title: '剩余可回款金额（含审批中）',
      field: 'remainingInvoicePrice',
      minWidth: 180,
      formatter: 'formatAmount2',
    },
    {
      title: '开票日期',
      field: 'invoiceTime',
      minWidth: 150,
      formatter: 'formatDateTime',
    },
    {
      title: '备注',
      field: 'remark',
      minWidth: 150,
    },
    {
      title: '负责人',
      field: 'ownerUserName',
      minWidth: 150,
    },
    {
      title: '所属部门',
      field: 'ownerUserDeptName',
      minWidth: 150,
    },
    {
      title: '更新时间',
      field: 'updateTime',
      minWidth: 150,
      formatter: 'formatDateTime',
    },
    {
      title: '创建时间',
      field: 'createTime',
      minWidth: 150,
      formatter: 'formatDateTime',
    },
    {
      title: '创建人',
      field: 'creatorName',
      minWidth: 150,
    },
    {
      title: '附件',
      field: 'attachmentList',
      minWidth: 100,
      fixed: 'right',
      slots: { default: 'attachment' },
    },
    {
      title: '审批状态',
      field: 'auditStatus',
      minWidth: 100,
      fixed: 'right',
      slots: { default: 'auditStatus' },
    },
    {
      title: '操作',
      field: 'actions',
      minWidth: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
