<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import { useVbenForm } from '#/adapter/form';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';
import { plantsProductList } from '#/api/property/productManagement';
import { getDictOptions } from '#/utils/dict';
const emit = defineEmits<{ reload: [data: any], editReload: [data: any] }>();

const isUpdate = ref(false);
const isAdd = ref(false);
const isView = ref(false);
const title = computed(() => {
  if(isAdd.value){
    return $t('pages.common.add');
  }else if(isView.value){
    return '查看';
  }else{
    return $t('pages.common.edit');
  }
});

// 缓存清洁服务数据
let plantListData: any[] = [];
const detailIndex = ref<number>();//传index对应详情的某条数据,对该条数据进行编辑修改

// 新增：接收已选产品id
const selectedIds = ref<any[]>([]);

// 添加数量最大值
const productNumMax = ref<any>(0);

const detailSchema = [
  {
    label: '产品名称',
    fieldName: 'plantName',
    component: 'ApiSelect',
    componentProps: {
      disabled: isView,
      api: async () => {
        const res = await plantsProductList({state:1,inventory:0});
        plantListData = res.rows || [];
        // 过滤掉已选产品
        const filtered = plantListData.filter(item => !selectedIds.value.includes(item.id));
        return { ...res, rows: filtered };
      },
      resultField: 'rows',
      labelField: 'plantName',
      valueField: 'id',
      onChange: async (value: string) => {
        // 找到选中的服务数据
        const selectedService = plantListData.find(item => item.id === value);
        if (selectedService) {
          // 自动填充其他字段
          await formApi.setValues({
            plantCode: selectedService.plantCode,
            inventory: selectedService.inventory,
            plantType: selectedService.plantType,
            imgPath: selectedService.imgPath,
            specification: selectedService.specification,
            rent: selectedService.rent,
            state: selectedService.state,
            remark: selectedService.remark,
          });
          // 更新最大数量
          productNumMax.value = selectedService.inventory || 0;
        }
      },
    },
    rules: 'required',
  },
  {
    label: '产品库存',
    fieldName: 'inventory',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    rules: 'required',
  },
  {
    label: '添加数量',
    fieldName: 'productNum',
    component: 'InputNumber',
    componentProps: {
      min: 1,
      max:  productNumMax,
      disabled: isView,
    },
    rules: 'required',
  },
  {
    label: '产品编号',
    fieldName: 'plantCode',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    rules: 'required',
  },
  {
    label: '产品分类',
    fieldName: 'plantType',
    component: 'Select',
    componentProps: {
      disabled: true,
      options: getDictOptions('pro_product_classification'),
    },
  },
  // {
  //   label: '图片',
  //   fieldName: 'imgPath',
  //   component: 'InputNumber',
  //   componentProps: {
  //     disabled: true,
  //   },
  // },
  {
    label: '规格',
    fieldName: 'specification',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    rules: 'required',
  },
  {
    label: '租金',
    fieldName: 'rent',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    rules: 'required',
  },

  {
    label: '状态',
    fieldName: 'state',
    component: 'Select',
    componentProps: {
      disabled: true,
      options: [
        { label: '上架', value: '1' },
        { label: '下架', value: '0' },
      ],
    },
    rules: 'required',
  },
    {
    label: '备注',
    fieldName: 'remark',
    component: 'Input',
    componentProps: {
      disabled: true,
    },
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    labelWidth: 120,
    componentProps: {
      class: 'w-full',
    },
  },
  schema: detailSchema,
  showDefaultActions: false,
});

// 监听inventory变化，更新productNumMax
watch(async () => {
  const values = await formApi.getValues();
  return values.inventory;
}, async (newInventory) => {
  if (newInventory) {
    productNumMax.value = newInventory;
    // 如果当前productNum大于新的库存，则设置为库存值
    const values = await formApi.getValues();
    const currentProductNum = values.productNum;
    if (currentProductNum && currentProductNum > newInventory) {
      formApi.setFieldValue('productNum', newInventory);
    }
  }
}, { immediate: true });

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    const data = modalApi.getData();
    detailIndex.value = data.index;
    // 新增：弹窗打开时同步 selectedIds
    selectedIds.value = data.selectedIds || [];
   if(data.readonly){
    //不存在detailIndex.value时表示查看
     isView.value = true;
    } else if(data.add){
    //modalApi.getData()为空时表示添加
      isAdd.value = true;
    }else{
    //表示编辑
     isUpdate.value = true;
    }
    // TODO: 获取详情数据
    await formApi.setValues(data);
    await markInitialized();
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    // 获取选中的产品
    const selectedService = plantListData.find(item => item.id === data.plantName);
    if (selectedService) {
      data.plantName = selectedService.plantName;
      data.productId = selectedService.id
    }
    if (isUpdate.value) {
      data.index = detailIndex.value;
      emit('editReload', data);
    }else if(isAdd.value){
      emit('reload', data);
    }
    handleClosed()
    await markInitialized();
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  isAdd.value = false;
  isView.value = false;
  isUpdate.value = false;
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title">
    <BasicForm >
    </BasicForm>
  </BasicModal>
</template>
<style scoped>
/* 使用 :deep() 穿透 scoped 样式，影响子组件 */
:deep(.ant-input[disabled]),
:deep(.ant-input-number-disabled .ant-input-number-input),
:deep(.ant-select-disabled .ant-select-selection-item) {
  /* 设置一个更深的颜色，可以自己调整 */
  color: rgba(0, 0, 0, 0.65) !important;
  /* 有些浏览器需要这个来覆盖默认颜色 */
  -webkit-text-fill-color: rgba(0, 0, 0, 0.65) !important;
}
</style>
