<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="ConfigMaterialInfoForm">
          <a-row>
						<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="请选择一级分类"  allow-clear @change="formData.typeId = null , formData.medicationId = null" />
							</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"  allow-clear />
							</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="请选择三级分类"  allow-clear />
							</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"  allow-clear ></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="请输入货品编码" maxlength="20"  allow-clear ></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"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="销售单价" v-bind="validateInfos.salesUnitPrice" id="ConfigMaterialInfoForm-salesUnitPrice" name="salesUnitPrice">
								<a-input v-model:value="formData.salesUnitPrice" placeholder="请输入销售单价" maxlength="10" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="参考单价" v-bind="validateInfos.referenceUnitPrice" id="ConfigMaterialInfoForm-referenceUnitPrice" name="referenceUnitPrice">
								<a-input v-model:value="formData.referenceUnitPrice" placeholder="请输入参考单价" maxlength="10" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="货品单位" v-bind="validateInfos.materialUnits" id="ConfigMaterialInfoForm-materialUnits" name="materialUnits">
								<a-input v-model:value="formData.materialUnits" placeholder="请输入货品单位"  maxlength="10" allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="多单位开关" v-bind="validateInfos.multiUnitSwitch" id="ConfigMaterialInfoForm-multiUnitSwitch" name="multiUnitSwitch">
                <j-dict-select-tag type='radio' v-model:value="formData.multiUnitSwitch" dictCode="multiUnitSwitch" placeholder="请选择多单位开关"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="多单位采购单位" v-bind="validateInfos.multiUnitType" id="ConfigMaterialInfoForm-multiUnitType" name="multiUnitType">
                <j-dict-select-tag type='radio' v-model:value="formData.multiUnitType" dictCode="multiUnitType" placeholder="请选择多单位默认采购"  allow-clear />
							</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="请选择是否启用"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="8" v-if="formData.multiUnitSwitch == '1'">
							<a-form-item label="二级单位" v-bind="validateInfos.oneUnit" id="ConfigMaterialInfoForm-oneUnit" name="oneUnit">
								<a-input v-model:value="formData.oneUnit" placeholder="请输入二级单位"  maxlength="10" allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8" v-if="formData.multiUnitSwitch == '1'">
							<a-form-item label="二级单位兑换比例" v-bind="validateInfos.oneUnitProportion" id="ConfigMaterialInfoForm-oneUnitProportion" name="oneUnitProportion">
								<a-input-number v-model:value="formData.oneUnitProportion" maxlength="10" placeholder="请输入二级单位兑换比例" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8" v-if="formData.multiUnitSwitch == '1'">
							<a-form-item label="二级单位价格" v-bind="validateInfos.oneUnitPrice" id="ConfigMaterialInfoForm-oneUnitPrice" name="oneUnitPrice">
								<a-input-number v-model:value="formData.oneUnitPrice" maxlength="10" placeholder="请输入二级单位价格" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8" v-if="formData.multiUnitSwitch == '1'">
							<a-form-item label="一级单位" v-bind="validateInfos.twoUnit" id="ConfigMaterialInfoForm-twoUnit" name="twoUnit">
								<a-input v-model:value="formData.twoUnit" placeholder="请输入一级单位" maxlength="10"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8" v-if="formData.multiUnitSwitch == '1'">
							<a-form-item label="一级单位兑换比例" v-bind="validateInfos.twoUnitProportion" id="ConfigMaterialInfoForm-twoUnitProportion" name="twoUnitProportion">
								<a-input-number v-model:value="formData.twoUnitProportion" maxlength="10" placeholder="请输入一级单位兑换比例" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8" v-if="formData.multiUnitSwitch == '1'">
							<a-form-item label="一级单位价格" v-bind="validateInfos.twoUnitPrice" id="ConfigMaterialInfoForm-twoUnitPrice" name="twoUnitPrice">
								<a-input-number v-model:value="formData.twoUnitPrice" maxlength="10" placeholder="请输入一级单位价格" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物料上限" v-bind="validateInfos.upperLimit" id="ConfigMaterialInfoForm-upperLimit" name="upperLimit">
								<a-input v-model:value="formData.upperLimit" maxlength="10" placeholder="请输入物料上限" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="物料下限" v-bind="validateInfos.lowerLimit" id="ConfigMaterialInfoForm-lowerLimit" name="lowerLimit">
								<a-input v-model:value="formData.lowerLimit" maxlength="10" placeholder="请输入物料下限" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="供应商" v-bind="validateInfos.suppliers" id="ConfigMaterialInfoForm-suppliers" name="suppliers" :labelCol="labelCol3" :wrapperCol="wrapperCol3">
                <j-select-multiple placeholder="请选择供应商" v-model:value="formData.suppliers" dictCode="nu_config_suppliers_info,suppliers_name,id,del_flag = 0" allow-clear />
							</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" v-model:value="formData.materialImg" ></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" v-model:value="formData.materialIdent" ></j-image-upload>
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</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 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: '2',   
    oneUnit: '',   
    oneUnitProportion: undefined,
    oneUnitPrice: undefined,
    twoUnit: '',   
    twoUnitProportion: undefined,
    twoUnitPrice: undefined,
    multiUnitType: '0',   
    izEnabled: '0',   
    suppliers: '',   
    materialImg: '',   
    materialIdent: '',   
    upperLimit: undefined,
    lowerLimit: undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 9 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 13 } });
  const labelCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol2 = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const labelCol3 = ref<any>({ xs: { span: 24 }, sm: { span: 3 } });
  const wrapperCol3 = ref<any>({ xs: { span: 24 }, sm: { span: 20 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    materialName: [{ required: true, message: '请输入货品名称!'},],
    salesUnitPrice: [{ required: true, message: '请输入销售单价!'},{ pattern: /^\d+(\.\d+)?$/, message: '只能输入数字（可包含小数点）!' }],
    referenceUnitPrice: [{ required: true, message: '请输入参考单价!'},{ pattern: /^\d+(\.\d+)?$/, message: '只能输入数字（可包含小数点）!' }],
    materialUnits: [{ required: true, message: '请输入货品单位!'}],
    suppliers: [{ required: true, message: '请选择供应商!'},],
    upperLimit: [{ required: false, message: '请输入物料上限!'},{ pattern: /^\d+(\.\d+)?$/, message: '只能输入数字（可包含小数点）!' }],
    lowerLimit: [{ required: false, message: '请输入物料下限!'},{ pattern: /^\d+(\.\d+)?$/, 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) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      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(',');
        }
      }
    }
    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;
  }
</style>
