<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="ConfigMaterialMedicationForm">
          <a-row>
						<a-col :span="24" >
							<a-form-item label="迁移至几级" v-bind="validateInfos.qycj" id="ConfigMaterialMedicationForm-qycj" name="qycj">
								<j-dict-select-tag type='radio' v-model:value="formData.qycj" dictCode="multiUnitType"  allow-clear/>
							</a-form-item>
						</a-col>
						<a-col :span="24" v-show="formData.qycj=='1' || formData.qycj=='0'" >
							<a-form-item label="一级分类" v-bind="validateInfos.categoryId" id="ConfigMaterialMedicationForm-categoryId" name="categoryId">
								<j-dict-select-tag type='radio' v-model:value="formData.categoryId" dictCode="nu_config_material_category,category_name,id,iz_enabled = 0 and del_flag = 0" placeholder="请选择一级分类"  allow-clear/>
							</a-form-item>
						</a-col>
						<a-col :span="24" v-show="formData.qycj=='0'"  >
							<a-form-item label="二级分类" v-bind="validateInfos.typeId" id="ConfigMaterialMedicationForm-typeId" name="typeId">
								<j-dict-select-tag type='radio' v-model:value="formData.typeId" :dictCode="`nu_config_material_type,type_name,id,iz_enabled = 0 and del_flag = 0 and category_id = ${formData.categoryId || -1}`" placeholder="请选择二级分类"  allow-clear/>
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
    <a-modal v-model:visible="visible" title="迁移失败" width="400px">
      <div style="padding: 20px;">
      <p style="font-size: 16px;">您当前的分类包含下级，不能迁移至三级分类，请您重新选择，或者请先将下级分类迁移至别的层级后再进行次操作</p>
      </div>
      <template #footer>
        <a-button @click="visible = false">取消</a-button>
      </template>
    </a-modal>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted,onUnmounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../ConfigMaterialMedication.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import { e } from 'unocss';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const visible = ref<boolean>(false);
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    categoryId: '',   
    typeId: '',   
    qycj: '',
    levle: '',
    sfyxj: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    qycj: [{ required: true, message: '请选择您要迁入到第几层级!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add(record) {
    edit(record);
  }

  /**
   * 编辑
   */
  function edit(record) {
    console.log("🚀 ~ edit ~ record:", record)
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
      formData.categoryId = record.categoryId;
      if(record.levle == '1'){
        formData.qycj = '2';
      }else if(record.levle == '2'){
        formData.qycj = '1';
      }else if(record.levle == '3'){
        formData.qycj = '0';
      }
        console.log("🚀 ~ edit ~ formData:", formData)
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    console.log("🚀 ~ submitForm ~ model:", model)
    confirmLoading.value = false;
    if(model.qycj == '2'){//迁移到一级
      model.categoryId = "";
      model.typeId = "";
    }else if(model.qycj == '1'){//迁移到二级
      model.typeId = "";
      if(!model.categoryId){
          createMessage.success("请选择一级分类!");
          return;
      }
    }else{
      if(model.sfyxj == '1'){
        visible.value = true;
        return;
      }
      if(!model.categoryId){
          createMessage.success("请选择一级分类!");
          return;
      }
      if(!model.typeId){
          createMessage.success("请选择二级分类!");
          return;
      }
    }
    defHttp.post({ url: '/invoicing/configMaterialMedication/editQianyi', params: model }).then((res) => { 
      emit('ok');
    });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
