<template>
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="ConfigMaterialInfoForm">
          <a-row  class="card-class">
						<a-col :span="8" hidden>
							<a-form-item label="一级分类" v-bind="validateInfos.categoryId" id="ConfigMaterialInfoForm-categoryId" name="categoryId">
                <j-dict-select-tag type='list' v-model:value="formData.categoryId" dictCode="nu_config_material_category,category_name,id,iz_enabled = 0 and del_flag = 0" placeholder="请选择一级分类"  @change="formData.typeId = null , formData.medicationId = null" disabled/>
							</a-form-item>
						</a-col>
						<a-col :span="8" hidden>
							<a-form-item label="二级分类" v-bind="validateInfos.typeId" id="ConfigMaterialInfoForm-typeId" name="typeId">
                <j-dict-select-tag type='list' v-model:value="formData.typeId" :dictCode="`nu_config_material_type,type_name,id,category_id = ${formData.categoryId || -1} and iz_enabled = 0 and del_flag = 0 `" placeholder="请选择二级分类" @change="formData.medicationId = null" disabled  />
							</a-form-item>
						</a-col>
						<a-col :span="8" hidden>
							<a-form-item label="三级分类" v-bind="validateInfos.medicationId" id="ConfigMaterialInfoForm-medicationId" name="medicationId">
                <j-dict-select-tag type='list' v-model:value="formData.medicationId" :dictCode="`nu_config_material_medication,medication_name,id,type_id = ${formData.typeId || -1} and iz_enabled = 0 and del_flag = 0`" placeholder="请选择三级分类"  disabled />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物料名称" v-bind="validateInfos.materialName" id="ConfigMaterialInfoForm-materialName" name="materialName">
								<a-input v-model:value="formData.materialName" placeholder="请输入物料名称" maxlength="20"  ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物料编码" v-bind="validateInfos.materialNo" id="ConfigMaterialInfoForm-materialNo" name="materialNo">
								<a-input v-model:value="formData.materialNo" :placeholder="disabled?'':`请输入物料编码`" maxlength="20"  ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="规格型号" v-bind="validateInfos.specificationModel" id="ConfigMaterialInfoForm-specificationModel" name="specificationModel">
								<a-input v-model:value="formData.specificationModel" placeholder="请输入规格型号" maxlength="20"  ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8" >
							<a-form-item label="品牌型号" v-bind="validateInfos.brandType" id="ConfigMaterialInfoForm-brandType" name="brandType">
								<a-input v-model:value="formData.brandType" maxlength="100" :placeholder="disabled?'':`请输入品牌型号`" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8" >
							<a-form-item label="生产厂家" v-bind="validateInfos.manufacturer" id="ConfigMaterialInfoForm-manufacturer" name="manufacturer">
								<a-input v-model:value="formData.manufacturer" maxlength="100" :placeholder="disabled?'':`请输入生产厂家`" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="是否启用" v-bind="validateInfos.izEnabled" id="ConfigMaterialInfoForm-izEnabled" name="izEnabled">
                <j-dict-select-tag type='radio' v-model:value="formData.izEnabled" dictCode="iz_enabled" placeholder="请选择是否启用"  />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物料图片" v-bind="validateInfos.materialImg" id="ConfigMaterialInfoForm-materialImg" name="materialImg">
								<j-image-upload :fileMax="1" bizPath="wlpicPath" :value="formData.materialImg?formData.materialImg:(opeMediaAddress + defaultPrePic)" ></j-image-upload>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物料标识" v-bind="validateInfos.materialIdent" id="ConfigMaterialInfoForm-materialIdent" name="materialIdent">
								<j-image-upload :fileMax="1" bizPath="wlbsPath" :value="formData.materialIdent?formData.materialIdent:(opeMediaAddress + defaultPrePic)" ></j-image-upload>
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } 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 JSwitch from '/@/components/Form/src/jeecg/components/JSwitch.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../ConfigMaterialInfo.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
  
const opeMediaAddress = import.meta.env.VITE_OPE_MEDIA_ADDRESS
const defaultPrePic = import.meta.env.VITE_DEFAULT_NULL_PIC//证件照默认图片
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    categoryId: '',   
    typeId: '',   
    medicationId: '',   
    materialName: '',   
    materialNo: '',   
    specificationModel: '',   
    salesUnitPrice: undefined,
    referenceUnitPrice: undefined,
    materialUnits: '',   
    multiUnitSwitch: '1',   
    oneUnit: '',   
    oneUnitProportion: undefined,
    oneUnitPrice: undefined,
    twoUnit: '',   
    twoUnitProportion: undefined,
    twoUnitPrice: undefined,
    multiUnitType: '3',   
    izEnabled: 'Y',   
    suppliers: '',   
    materialImg: '',   
    materialIdent: '',   
    upperLimit: undefined,
    lowerLimit: undefined,
    sdwdhbl:'1',
    izYbbx:'',
    izJgyh:'',
    tagType:'',
    brandType:'',
    manufacturer:'',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 9 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 15 } });
  const labelCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 18 } });
  const labelCol3 = ref<any>({ xs: { span: 24 }, sm: { span: 3 } });
  const wrapperCol3 = ref<any>({ xs: { span: 24 }, sm: { span: 21 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    });
  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 getRemark(){
  var remark = '';
  if(formData.oneUnitPrice && formData.twoUnitPrice){
    if(parseFloat(formData.oneUnitPrice) < parseFloat(formData.twoUnitPrice) && parseFloat(formData.oneUnitProportion) > parseFloat(formData.twoUnitProportion)){
      remark = remark + '温馨提示：二级单位价格高于一级单位价格，但是二级单位兑换比例小于一级单位兑换比例，兑换比例请自行换算成最小对应比例，请检查！'
    }
  }
  return remark;
}

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

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      if(disabled.value === true){
        console.log("🚀 ~ 11111111:", 1111)
        Object.keys(validatorRules).forEach(key => {
          delete validatorRules[key];
        });
        console.log("🚀 ~ edit ~ validatorRules:", validatorRules)
      }else{
        Object.assign(validatorRules, {materialName: [{ required: true, message: '请输入物料名称!'},],
        specificationModel: [{ required: true, message: '请输入规格型号!'},],
        materialNo: [{ required: true, message: '请输入物料编码!'},],
  
});
      }
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  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.oneUnitProportion:", model.oneUnitProportion)
    console.log("🚀 ~ submitForm ~ model.oneUnitPrice:", model.oneUnitPrice)
    if(model.oneUnit  || model.oneUnitPrice  || model.oneUnitProportion ){
      if(!model.oneUnit || !model.oneUnitPrice || !model.oneUnitProportion ){
        createMessage.warning("一级单位、一级单位兑换比例、一级单位价格不能为空！");
        return;
      }
    }
    if(model.twoUnit || model.twoUnitPrice  || model.twoUnitProportion  ){
      if(!model.twoUnit || !model.twoUnitPrice  || !model.twoUnitProportion){
        createMessage.warning("二级单位、二级单位兑换比例、二级单位价格不能为空！");
        return;
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


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

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
  
.card-class {
  padding-top: 24px;
  padding-bottom: 24px;
  padding-left: 14px;
  padding-right: 14px;
  // background-color: rgba(255, 255, 255, 0.9);
  background-color: #fcfdff;
  border-radius: 10px;
  // box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 12px;
  margin-bottom: 14px;

}
</style>
