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

import { getSupplierSimpleList } from '#/api/srm/supplier';

import { z } from '#/adapter/form';

import { markRaw } from 'vue';

import OrderAllocationField from './modules/order-allocation-field.vue';

/** 表单类型 */
export type FormType = 'create' | 'detail' | 'edit';

function round2(value: number) {
  return Math.round((value + Number.EPSILON) * 100) / 100;
}

/** 新增/修改的表单 */
export function useFormSchema(
  orderRemainInvoicePrice?: Ref<number | undefined>,
  formType?: Ref<FormType>,
): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'no',
      label: '来票编号',
      component: 'Input',
      rules: 'required',
      dependencies: {
        triggerFields: ['id'],
        disabled: (values) => !!values.id,
      },
      componentProps: {
        placeholder: '请输入来票编号',
        maxLength: 32,
      },
    },
    {
      fieldName: 'supplierName',
      label: '供应商',
      component: 'Input',
      componentProps: {
        placeholder: '选择采购订单后自动带出',
        disabled: true,
      },
    },
    {
      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',
      description: () =>
        orderRemainInvoicePrice?.value != null
          ? `所选采购订单未开票金额合计：${Number(orderRemainInvoicePrice.value).toFixed(2)} 元`
          : '',
      componentProps: {
        class: '!w-full',
        placeholder: '请输入来票金额',
        min: 0,
        precision: 2,
      },
      dependencies: {
        triggerFields: ['orderAllocations'],
        componentProps: () => ({
          class: '!w-full',
          placeholder: '请输入来票金额',
          min: 0,
          max: orderRemainInvoicePrice?.value ?? undefined,
          precision: 2,
        }),
        rules: () => {
          const max = orderRemainInvoicePrice?.value;
          if (max != null) {
            return z
              .number({ message: '请输入来票金额' })
              .min(0, '来票金额不能小于 0')
              .max(max, `来票金额不能大于未开票金额 ${Number(max).toFixed(2)}`);
          }
          return z
            .number({ message: '请输入来票金额' })
            .min(0, '来票金额不能小于 0');
        },
      },
    },
    {
      fieldName: 'invoiceTime',
      label: '来票日期',
      component: 'DatePicker',
      rules: 'required',
      componentProps: {
        placeholder: '请选择来票日期',
        showTime: false,
        valueFormat: 'YYYY-MM-DD',
        format: 'YYYY-MM-DD',
      },
    },
    {
      fieldName: 'orderAllocations',
      label: '采购订单',
      component: markRaw(OrderAllocationField),
      formItemClass: 'md:col-span-2',
      dependencies: {
        triggerFields: ['id', 'price'],
        componentProps: (values, form) => ({
          invoicePrice: values.price,
          // 编辑时把本张来票已分摊的金额退回订单，重新选择订单时未开票金额按其他来票计算
          invoiceId: values.id ? Number(values.id) : undefined,
          disabled: formType?.value === 'detail',
          // 分摊行变化：带出供应商名称（同一供应商）与未开票金额合计
          onChange: (rows: Array<Record<string, any>>) => {
            const supplierNames = [
              ...new Set(
                rows
                  .map((row) => row.supplierName)
                  .filter((name): name is string => !!name),
              ),
            ];
            form.setFieldValue('supplierName', supplierNames.join('、'));
            if (orderRemainInvoicePrice) {
              orderRemainInvoicePrice.value = round2(
                rows.reduce((sum, row) => sum + Number(row.remainPrice ?? 0), 0),
              );
            }
          },
        }),
      },
    },
    {
      fieldName: 'blobIds',
      label: '发票附件',
      component: 'FileUpload',
      componentProps: {
        valueKey: 'id',
        maxNumber: 10,
        multiple: true,
        accept: ['jpg', 'jpeg', 'png', 'pdf'],
        helpText: '支持jpg、jpeg、png、pdf格式，单个文件不超过50MB',
      },
      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: 'supplierId',
      label: '供应商',
      component: 'ApiSelect',
      componentProps: {
        placeholder: '请选择供应商',
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label', // 按供应商名称手输过滤
        api: getSupplierSimpleList,
        labelField: 'name',
        valueField: 'id',
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
  return [
    {
      title: '来票编号',
      field: 'no',
      minWidth: 160,
      fixed: 'left',
      slots: { default: 'no' },
    },
    {
      title: '供应商',
      field: 'supplierName',
      minWidth: 150,
    },
    {
      title: '采购订单编号',
      field: 'orderNos',
      minWidth: 220,
      slots: { default: 'orderNo' },
    },
    {
      title: '发票号码',
      field: 'invoiceNo',
      minWidth: 150,
    },
    {
      title: '来票金额（元）',
      field: 'price',
      minWidth: 150,
      formatter: 'formatAmount2',
    },
    {
      title: '来票日期',
      field: 'invoiceTime',
      minWidth: 150,
      formatter: 'formatDateTime',
    },
    {
      title: '备注',
      field: 'remark',
      minWidth: 150,
    },
    {
      title: '附件',
      field: 'attachmentList',
      minWidth: 100,
      fixed: 'right',
      slots: { default: 'attachment' },
    },
    {
      title: '操作',
      field: 'actions',
      minWidth: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
