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

import { erpPriceMultiply } from '#/packages/utils/src';

import { z } from '#/adapter/form';
import { getSimpleBusinessList } from '#/api/crm/business';
import { getSimpleContactList } from '#/api/crm/contact';
import { getItemPage } from '#/api/mdm/item';
import { getSimpleUserList } from '#/api/system/user';
import { useUserStore } from '#/packages/stores/src';
import CrmCustomerSelect from '#/components/crm-customer-select.vue';

import { markRaw } from 'vue';

/** 报价单状态 */
export const QUOTATION_STATUS = {
  DRAFT: 0, // 草稿
  CONVERTED: 10, // 已转合同
};

/** 新增/修改的表单 */
export function useFormSchema(): VbenFormSchema[] {
  const userStore = useUserStore();
  return [
    {
      component: 'Input',
      fieldName: 'id',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'no',
      label: '报价单号',
      component: 'Input',
      componentProps: {
        placeholder: '保存时自动生成',
        disabled: true,
      },
    },
    {
      fieldName: 'name',
      label: '报价单名称',
      component: 'Input',
      rules: 'required',
      componentProps: {
        placeholder: '请输入报价单名称',
      },
    },
    {
      fieldName: 'ownerUserId',
      label: '负责人',
      component: 'ApiSelect',
      componentProps: {
        api: getSimpleUserList,
        labelField: 'nickname',
        valueField: 'id',
      },
      defaultValue: userStore.userInfo?.id,
      rules: 'required',
    },
    {
      fieldName: 'customerId',
      label: '客户名称',
      component: markRaw(CrmCustomerSelect),
      rules: 'required',
      componentProps: {
        placeholder: '请选择客户',
      },
    },
    {
      fieldName: 'businessId',
      label: '商机名称',
      component: 'Select',
      componentProps: {
        options: [],
        placeholder: '请选择商机',
        allowClear: true,
      },
      dependencies: {
        triggerFields: ['customerId'],
        disabled: (values) => !values.customerId,
        async componentProps(values) {
          if (!values.customerId) {
            return { options: [], placeholder: '请选择客户' };
          }
          const res = await getSimpleBusinessList();
          const list = res.filter((item) => item.customerId === values.customerId);
          return {
            options: list.map((item) => ({ label: item.name, value: item.id })),
            placeholder: '请选择商机',
          };
        },
      },
    },
    {
      fieldName: 'contactId',
      label: '联系人',
      component: 'Select',
      componentProps: {
        options: [],
        placeholder: '请选择联系人',
        allowClear: true,
      },
      dependencies: {
        triggerFields: ['customerId'],
        disabled: (values) => !values.customerId,
        async componentProps(values) {
          if (!values.customerId) {
            return { options: [], placeholder: '请选择客户' };
          }
          const res = await getSimpleContactList();
          const list = res.filter((item) => item.customerId === values.customerId);
          return {
            options: list.map((item) => ({ label: item.name, value: item.id })),
            placeholder: '请选择联系人',
          };
        },
      },
    },
    {
      fieldName: 'quotationTime',
      label: '报价日期',
      component: 'DatePicker',
      rules: 'required',
      componentProps: {
        showTime: false,
        format: 'YYYY-MM-DD',
        valueFormat: 'x',
        placeholder: '请选择报价日期',
      },
    },
    {
      fieldName: 'validUntil',
      label: '有效期至',
      component: 'DatePicker',
      componentProps: {
        showTime: false,
        format: 'YYYY-MM-DD',
        valueFormat: 'x',
        placeholder: '请选择有效期',
      },
    },
    {
      fieldName: 'taxRate',
      label: '税率(%)',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        max: 100,
        precision: 2,
        placeholder: '请输入税率',
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注',
        rows: 3,
      },
    },
    {
      fieldName: 'items',
      label: '产品清单',
      component: 'Input',
      formItemClass: 'col-span-3',
    },
    {
      fieldName: 'totalProductPrice',
      label: '物料总金额',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        precision: 2,
        disabled: true,
      },
      rules: z.number().min(0).optional().default(0),
    },
    {
      fieldName: 'discountPercent',
      label: '整单折扣（%）',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        precision: 2,
        placeholder: '请输入折扣',
      },
      rules: z.number().min(0).max(100).optional().default(0),
    },
    {
      fieldName: 'totalPrice',
      label: '折扣后金额',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        precision: 2,
        disabled: true,
      },
      dependencies: {
        triggerFields: ['totalProductPrice', 'discountPercent'],
        trigger(values, form) {
          const discountPrice =
            erpPriceMultiply(values.totalProductPrice, values.discountPercent / 100) ?? 0;
          form.setFieldValue('totalPrice', values.totalProductPrice - discountPrice);
        },
      },
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'no',
      label: '报价单号',
      component: 'Input',
      componentProps: {
        placeholder: '请输入报价单号',
        allowClear: true,
      },
    },
    {
      fieldName: 'name',
      label: '报价单名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入报价单名称',
        allowClear: true,
      },
    },
    {
      fieldName: 'customerId',
      label: '客户',
      component: markRaw(CrmCustomerSelect),
      componentProps: {
        placeholder: '请选择客户',
        allowClear: true,
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        placeholder: '请选择状态',
        allowClear: true,
        options: [
          { label: '草稿', value: 0 },
          { label: '已转合同', value: 10 },
        ],
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
  return [
    {
      type: 'checkbox',
      width: 50,
      fixed: 'left',
    },
    {
      field: 'no',
      title: '报价单号',
      minWidth: 180,
      fixed: 'left',
    },
    {
      field: 'name',
      title: '报价单名称',
      minWidth: 160,
      fixed: 'left',
    },
    {
      field: 'customerName',
      title: '客户名称',
      minWidth: 120,
    },
    {
      field: 'businessName',
      title: '商机名称',
      minWidth: 130,
    },
    {
      field: 'totalPrice',
      title: '报价金额（元）',
      minWidth: 140,
      formatter: 'formatAmount2',
    },
    {
      field: 'quotationTime',
      title: '报价日期',
      minWidth: 120,
      formatter: 'formatDateTime',
    },
    {
      field: 'validUntil',
      title: '有效期至',
      minWidth: 120,
      formatter: 'formatDateTime',
    },
    {
      field: 'status',
      title: '状态',
      minWidth: 100,
      slots: { default: 'status' },
    },
    {
      field: 'contractNo',
      title: '关联合同',
      minWidth: 150,
    },
    {
      field: 'ownerUserName',
      title: '负责人',
      minWidth: 120,
    },
    {
      field: 'createTime',
      title: '创建时间',
      minWidth: 180,
      formatter: 'formatDateTime',
    },
    {
      title: '操作',
      width: 260,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 产品明细表格列 */
export function useItemColumns(): VxeTableGridOptions['columns'] {
  return [
    { type: 'seq', title: '序号', minWidth: 50, fixed: 'left' },
    {
      field: 'itemId',
      title: '产品名称',
      minWidth: 200,
      slots: { default: 'itemId' },
    },
    {
      field: 'itemSpecification',
      title: '规格型号',
      minWidth: 120,
    },
    {
      field: 'itemUnitName',
      title: '单位',
      minWidth: 80,
    },
    {
      field: 'itemUnitName2',
      title: '辅单位1',
      minWidth: 80,
    },
    {
      field: 'itemUnitName3',
      title: '辅单位2',
      minWidth: 80,
    },
    {
      field: 'itemPrice',
      title: '原价（元）',
      minWidth: 100,
      formatter: 'formatAmount2',
    },
    {
      field: 'quotationPrice',
      title: '报价（元）',
      minWidth: 100,
      slots: { default: 'quotationPrice' },
    },
    {
      field: 'count',
      title: '数量',
      minWidth: 100,
      slots: { default: 'count' },
    },
    {
      field: 'totalPrice',
      title: '合计',
      minWidth: 100,
      formatter: 'formatAmount2',
    },
    {
      title: '操作',
      width: 50,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}