<!-- 产品档案 -->
<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" width="550px" @ok="handleSubmit">
    <BasicForm @register="registerForm" @submit="handleSubmit" style="margin-top: 26px" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref,onMounted } from 'vue';
  //引入依赖
  import { useForm, BasicForm, FormSchema } from '/@/components/Form';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { saveOrUpdateDict } from '../api/productCassification.api';
  import { defHttp } from '/@/utils/http/axios';
  const emit = defineEmits(['register', 'success']); //定义emit
  const isUpdate = ref(true); //判断编辑还是新增
  const rowId = ref('');//获取主键
  let classOption = ref([])
  //获取表单数据
  const [registerModal, { closeModal, setModalProps }] = useModalInner(
    async (data) => {
      // 重置表单
      await resetFields();
      setModalProps({ confirmLoading: false});
      isUpdate.value = !!data?.isUpdate;     
      getOptions(isUpdate,data.record)
      if (unref(isUpdate)) {
      rowId.value = data.record.id;
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
    }
  )
  function getOptions(isUpdate,data) {
    defHttp
        .get({ url: 'baseCode/baseProductClass/list'}, { isTransformResponse: false })
        .then((res) => {
            if (res.success) {
              var option = []
              res.result.records.forEach(element => {
                  var obj = {
                    label: element.name,
                    value: element.id
                  };
                  option.push(obj)
              });  
              classOption.value = [] 
              if(unref(isUpdate)){  //编辑
                var row = JSON.parse(JSON.stringify(data))
                option.map(item=>{
                  if(item.label!=row.parentId){
                    classOption.value.push(item)
                  }
                })
              }else{
                classOption.value = option
              }
            }
        })
        .finally(() => {
            // loading.value = false;
        });
  }
  //获取title
  const getTitle = computed(() => {
    return (!unref(isUpdate) ? '新增产品分类(add)' : '编辑产品分类(edit)');
  })
  //自定义表单字段
  const formSchemas: FormSchema[] = [
    {
      //标题名称
      label: '上级分类(parent)',
      //字段
      field: 'parentId',
      //组件 支持组件详见 components/Form/src/types/index.ts 中的 ComponentType
      component: 'JSelectInput',
      componentProps:{
        options: classOption,
      },
    },
    {
      label: '编码(code)',
      field: 'code',
      component: 'Input',
      // required: true,
      componentProps:{
        AutoComplete:'off',
        placeholder:'请输入,为空则自动生成'
      },
    },
    {
      label: '名称(name)',
      field: 'name',
      component: 'Input',
      required: true,
      componentProps:{
        AutoComplete:'off'
      },
    },
    {
      label: '毛利率(gross margin)',
      field: 'grossMargin',
      component: 'Input',
      componentProps:{
        AutoComplete:'off',
        addonAfter:"%",
      },
    },
    {
      label: '税率(tax rate)',
      field: 'taxRate',
      component: 'Input',
      componentProps:{
        AutoComplete:'off',
        addonAfter:"%",
      },
    },
    {
      label: '',
      field: 'id',
      component: 'Input',
      show: false
    },
  ];
  /**
   * BasicForm绑定注册;
   * useForm 是整个框架的核心用于表单渲染，里边封装了很多公共方法;
   * 支持（schemas: 渲染表单列，autoSubmitOnEnter：回车提交,submitButtonOptions：自定义按钮文本和图标等方法）；
   * 平台通过此封装，简化了代码，支持自定义扩展;
   */
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    //注册表单列
    schemas: formSchemas,
    //回车提交
    autoSubmitOnEnter: true,
    //不显示重置按钮
    showResetButton: false,
    showSubmitButton:false,
    labelCol: { style: { width: '150px'} },
    labelAlign:'right'
    //查询列占比 24代表一行 取值范围 0-24
  });

  /**
   * 点击提交按钮的value值
   * @param values
   */

  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdateDict(values, isUpdate.value);
      
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  
</script>
