<script lang="ts" setup>
import type { ProductEntity } from '@vben/types';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import { useVbenForm, z } from '#/adapter/form';
import { getDictListApi } from '#/api/dict';
import {
  addProductApi,
  editProductApi,
  getProductDetailApi,
} from '#/api/product';
import { getScqyListApi } from '#/api/scqy';
import { getCustomerListApi } from '#/api/user';

// 定义 props
const props = defineProps<{
  defaultMerchantId?: string | string[];
}>();

const emit = defineEmits(['finish']);
const data = ref();
const formType = ref<'create' | 'detail' | 'edit'>('create');
const channelOptions = ref<{ label: string; value: string }[]>([]);
const scqyOptions = ref<{ label: string; value: string }[]>([]);
const jjlxOptions = ref<{ label: string; value: string }[]>([]);
const cplbOptions = ref<{ label: string; value: string }[]>([]);

// 获取经销商列表
const fetchChannelOptions = async () => {
  try {
    // 确保清空之前的选项
    channelOptions.value = [];

    const response = await getCustomerListApi({
      'usersnature.value': '经销商',
      pageindex: 1,
      rows: 100,
    });

    // 从response.Data中获取数据
    if (response && response.Data && Array.isArray(response.Data)) {
      channelOptions.value = response.Data.map((item: any) => ({
        label: item.usersname || '未命名经销商',
        value: item.usersid || '',
      })).filter((item: any) => item.value);
    }
  } catch (error) {
    console.error('获取经销商列表失败', error);
  }
};

// 获取生产企业列表
const fetchScqyOptions = async () => {
  try {
    // 确保清空之前的选项
    scqyOptions.value = [];

    const response = await getScqyListApi({
      pageindex: 1,
      rows: 100,
    });

    // 从response.Data中获取数据
    if (response && response.Data && Array.isArray(response.Data)) {
      scqyOptions.value = response.Data.map((item: any) => ({
        label: item.scqyinfomc || '未命名生产企业',
        value: item.scqyinfoid || '',
      })).filter((item: any) => item.value);
    }
  } catch (error) {
    console.error('获取生产企业列表失败', error);
  }
};

const fetchDictOptions = async () => {
  try {
    const [jjlxRes, cplbRes] = await Promise.all([
      getDictListApi({ groupname: 'product_jjlx', rows: 999, pageindex: 1 }),
      getDictListApi({ groupname: 'product_cplb', rows: 999, pageindex: 1 }),
    ]);

    jjlxOptions.value = (jjlxRes.Data || []).map((item: any) => ({
      label: item.title,
      value: item.substance,
    }));
    cplbOptions.value = (cplbRes.Data || []).map((item: any) => ({
      label: item.title,
      value: item.substance,
    }));
  } catch (error) {
    console.error('获取字典数据失败', error);
  }
};

const titleMap = {
  create: '新增产品',
  detail: '产品详情',
  edit: '编辑产品',
} as const;

const getTitle = computed(() => titleMap[formType.value]);

// 判断是否有默认的经销商ID
const hasDefaultMerchantId = computed(() => {
  return (
    props.defaultMerchantId &&
    (Array.isArray(props.defaultMerchantId)
      ? props.defaultMerchantId.length > 0
      : props.defaultMerchantId)
  );
});

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    labelWidth: 140,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  wrapperClass: 'grid-cols-1 lg:grid-cols-2',
  schema: [
    // { title: '产品名称', field: 'productsname' },
    // { title: '产品类别', field: 'productscategory' },
    // { title: '产品原价', field: 'productsprice' },
    // { title: '产品型号', field: 'productsmodel' },
    // { title: '产品sn号', field: 'productssn' },
    // { title: '品目', field: 'productspm' },
    // { title: '一级分类', field: 'productsfl1' },
    // { title: '二级分类', field: 'productsfl2' },
    // { title: '分档名称', field: 'productsfdmc' },
    // { title: '分档编号', field: 'productsfdbh' },
    // { title: '中央补贴金额', field: 'productszybt' },
    // { title: '特殊县中央补贴金额', field: 'productstsxzybt' },
    // { title: '机具类型', field: 'productsjjlx' },
    {
      component: 'Select',
      fieldName: 'productsjjlx',
      label: '机具类型',
      componentProps: {
        placeholder: '请选择机具类型',
        allowClear: true,
        options: jjlxOptions,
      },
      rules: z.string().min(1, { message: '请选择机具类型' }),
    },
    {
      component: 'Input',
      fieldName: 'productsname',
      label: '产品名称',
      componentProps: {
        placeholder: '请输入产品名称',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入产品名称' }),
    },
    {
      component: 'Select',
      fieldName: 'productscategory',
      label: '产品类别',
      componentProps: {
        placeholder: '请选择产品类别',
        allowClear: true,
        options: cplbOptions,
      },
      rules: z.string().min(1, { message: '请选择产品类别' }),
    },
    {
      component: 'Select',
      fieldName: 'productsfl1',
      label: '一级分类',
      componentProps: {
        placeholder: '请选择一级分类',
        allowClear: true,
        options: cplbOptions,
      },
      rules: z.string().min(1, { message: '请输入一级分类' }),
    },
    {
      component: 'Input',
      fieldName: 'productsmodel',
      label: '产品型号',
      componentProps: {
        placeholder: '请输入产品型号',
        allowClear: true,
      },
      rules: z.string().min(1, { message: '请输入产品型号' }),
    },
    // {
    //   component: 'Input',
    //   fieldName: 'productssn',
    //   label: '产品SN号',
    //   componentProps: {
    //     placeholder: '请输入产品SN号',
    //     allowClear: true,
    //   },
    //   rules: z.string().min(1, { message: '请输入产品SN号' }),
    // },
    // {
    //   component: 'Input',
    //   fieldName: 'productspm',
    //   label: '品目',
    //   componentProps: {
    //     placeholder: '请输入品目',
    //     allowClear: true,
    //   },
    //   rules: z.string().min(1, { message: '请输入品目' }),
    // },
    {
      component: 'Select',
      fieldName: 'productsmerchantid',
      label: '关联经销商',
      componentProps: {
        placeholder: '请选择关联经销商',
        options: channelOptions,
        multiple: true,
        collapseTags: true,
        collapseTagsTooltip: true,
        clearable: true,
        filterable: true,
        noDataText: '暂无经销商数据',
        loading: false,
        style: { width: '100%' },
      },
      rules: z.array(z.string()).min(1, { message: '请选择关联经销商' }),
      // 使用dependencies控制字段显示
      dependencies: {
        triggerFields: ['productsname'], // 依赖产品名称字段来触发重新计算
        show: () => !hasDefaultMerchantId.value, // 当没有默认值时才显示该字段
      },
    },
    {
      component: 'Select',
      fieldName: 'productsscqyid',
      label: '关联生产企业',
      componentProps: {
        placeholder: '请选择关联生产企业',
        options: scqyOptions,
        clearable: true,
        filterable: true,
        noDataText: '暂无生产企业数据',
        loading: false,
        style: { width: '100%' },
      },
      rules: z.string().min(1, { message: '请选择关联生产企业' }),
    },
    // {
    //   component: 'Input',
    //   fieldName: 'productsfl2',
    //   label: '二级分类',
    //   componentProps: {
    //     placeholder: '请输入二级分类',
    //     allowClear: true,
    //   },
    //   // rules: z.string().min(1, { message: '请输入二级分类' }),
    // },
    // {
    //   component: 'Input',
    //   fieldName: 'productsfdmc',
    //   label: '分档名称',
    //   componentProps: {
    //     placeholder: '请输入分档名称',
    //     allowClear: true,
    //   },
    //   rules: z.string().min(1, { message: '请输入分档名称' }),
    // },
    // {
    //   component: 'Input',
    //   fieldName: 'productsfdbh',
    //   label: '分档编号',
    //   componentProps: {
    //     placeholder: '请输入分档编号',
    //     allowClear: true,
    //   },
    //   rules: z.string().min(1, { message: '请输入分档编号' }),
    // },
    {
      component: 'InputNumber',
      fieldName: 'productsprice',
      label: '产品原价',
      componentProps: {
        placeholder: '请输入产品原价',
        min: 0,
        precision: 2,
      },
      rules: z.number().min(0, { message: '请输入正确的产品原价' }),
    },
    {
      component: 'InputNumber',
      fieldName: 'productszybt',
      label: '中央补贴',
      componentProps: {
        placeholder: '请输入中央补贴金额',
        min: 0,
        precision: 2,
      },
      rules: z.number().min(0, { message: '请输入正确的中央补贴金额' }),
    },
    {
      component: 'InputNumber',
      fieldName: 'productstsxzybt',
      label: '特殊县中央补贴',
      componentProps: {
        placeholder: '请输入特殊县中央补贴金额',
        min: 0,
        precision: 2,
      },
      rules: z.number().min(0, { message: '请输入正确的特殊县中央补贴金额' }),
    },
  ],
});

const [Modal, modalApi] = useVbenModal({
  class: 'w-7/12',
  onCancel() {
    modalApi.close();
  },
  async onConfirm() {
    // 校验输入的数据
    const validate = await baseFormApi.validate();
    if (!validate.valid) {
      return;
    }

    try {
      // 处理多选值的转换
      const formValues = { ...validate.values };
      if (Array.isArray(formValues.productsmerchantid)) {
        formValues.productsmerchantid = formValues.productsmerchantid.join(',');
      }

      // 调用新增或编辑接口
      const apiMap = {
        create: () => addProductApi(formValues as ProductEntity),
        edit: () =>
          editProductApi({
            ...formValues,
            'productsid.value': data.value.row.productsid,
          } as any),
      };

      if (formType.value === 'detail') {
        modalApi.close();
        return;
      }

      await apiMap[formType.value]();
      ElMessage.success('操作成功');

      emit('finish');
      modalApi.close();
    } catch {}
  },
  async onOpenChange(isOpen) {
    if (isOpen) {
      data.value = modalApi.getData();
      formType.value = data.value.formType;

      baseFormApi.setState({
        commonConfig: { disabled: formType.value === 'detail' },
      });

      // 获取经销商列表和生产企业列表
      await Promise.all([
        fetchChannelOptions(),
        fetchScqyOptions(),
        fetchDictOptions(),
      ]);

      // 如果有默认的经销商ID，设置默认值
      if (hasDefaultMerchantId.value && data.value.formType === 'create') {
        // 设置默认值
        baseFormApi.setValues({
          productsmerchantid: '', // 设置为空的目的，是在接下来的经销商关联时，再去选择关联，而不是直接就进行关联
        });
      }

      if (data.value.formType === 'create') {
        return;
      }

      try {
        modalApi.setState({ loading: true });
        const detailData = await getProductDetailApi({
          productsid: data.value.row.productsid,
        });

        // 处理多选值的转换
        if (detailData.productsmerchantid) {
          detailData.productsmerchantid =
            detailData.productsmerchantid.split(',');
        }

        baseFormApi.setValues(detailData);
      } catch (error) {
        console.error('获取产品详情失败', error);
      }

      modalApi.setState({ loading: false });
    }
  },
});

// 暴露modalApi供外部调用
defineExpose({
  modalApi,
});
</script>

<template>
  <Modal :title="getTitle">
    <BaseForm />
  </Modal>
</template>
