<template>
  <!-- 修改和增加 -->
  <el-dialog :title="dialogtitle" v-model="show" width="800px" @close="reset">
    <el-form :inline="false" ref="refform" :model="form" :rules="rules" class="demo-form-inline">
      <el-form-item label="耗材名称" prop="conName">
        <el-input v-model="form.conName" placeholder="请输入耗材名称"></el-input>
      </el-form-item>
      <el-form-item label="耗材分类" prop="consGroupId">
        <div class="center" style="gap: 14px;">
          <el-select v-model="form.consGroupId" placeholder="请选择耗材分类" style="width: 200px">
            <el-option v-for="option in consGroups" :key="option.conTypeId" :label="option.label"
              :value="option.id"></el-option>
          </el-select>
          <el-button type="primary" icon="Plus" @click="addClassificationModalRef.open()">添加耗材类型</el-button>
        </div>
      </el-form-item>
      <el-form-item label="耗材价格" prop="price">
        <div class="center">
          <el-input-number v-model="form.price" placeholder="请输入" @change="onPriceChange"></el-input-number>
          <span>{{ form.conUnit }}</span>
          <div class="ipt">
            第二单位价格：
            <el-input-number v-model="twoPrice" placeholder="请输入" @change="onTwoPriceChange"></el-input-number>
            <span>{{ form.conUnitTwo }}</span>
          </div>
        </div>
      </el-form-item>
      <!-- <el-form-item label="库存">
        <el-input-number v-model="form.stockNumber" placeholder="请输入库存值"></el-input-number>
      </el-form-item> -->
      <el-form-item label="状态">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="单位" prop="conUnit">
        <el-input v-model="form.conUnit" placeholder="请输入单位"></el-input>
      </el-form-item>
      <el-alert class="u-m-t-10 u-m-b-10" title="提示" description="换算值为第一单位*第二单位转换数量=第二单位" type="warning" show-icon
        :closable="false"></el-alert>
      <el-form-item label="预警值">
        <el-input-number v-model="form.conWarning" placeholder="请输入耗材预警值"></el-input-number>
      </el-form-item>
      <el-form-item label="是否检测耗材">
        <el-switch v-model="form.isStock" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="第二单位" prop="conUnitTwo">
        <el-input v-model="form.conUnitTwo" placeholder="请输入第二单位"></el-input>
      </el-form-item>
      <el-form-item label="第二单位转换数量" prop="conUnitTwoConvert">
        <el-input-number v-model="form.conUnitTwoConvert" placeholder="第二单位转换数量"></el-input-number>
      </el-form-item>
      <el-form-item label="默认入库单位" prop="defaultUnit">
        <el-input v-model="form.defaultUnit" placeholder="请输入默认入库单位"></el-input>
      </el-form-item>
      <el-form-item style="display: flex; justify-content: flex-end">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm('refform')">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <addClassificationModal ref="addClassificationModalRef" @success="getConsGroups" />
</template>


<script setup>
import { ref, reactive, computed } from "vue";
import consApi from "@/api/product/cons";
import consGroupApi from "@/api/product/cons-group";
import { ElMessage } from "element-plus";
import addClassificationModal from "../../classification/components/addClassificationModal.vue";

const addClassificationModalRef = ref(null)

const consGroups = ref([]);
const rules = {
  conName: [{ required: true, message: "请输入耗材名称", trigger: "blur" }],
  consGroupId: [{ required: true, message: "请选择耗材类型", trigger: "change" }],
  price: [{ required: true, message: "请输入耗材价格", trigger: "blur" }],
  conWarning: [{ required: true, message: "请输入耗材预警值", trigger: "blur" }],
  conUnit: [{ required: true, message: "请输入耗材单位", trigger: "blur" }],
  conWarning: [
    {
      required: true,
      message: "请输入单位",
      trigger: "blur",
    },
  ],
};
function getConsGroups() {
  consGroupApi.getAllList().then((res) => {
    consGroups.value = res.map((v) => {
      return {
        ...v,
        label: v.name,
        value: v.id,
      };
    });
  });
}
getConsGroups();
const basicForm = {
  conName: "",
  consGroupId: "",
  conUnit: "",
  price: undefined,
  conWarning: undefined,
  id: "",
  isStock: 1,
};
const forms = ref([{ ...basicForm }]);
const form = reactive({
  ...basicForm,
});

// 第二单位价格为计算字段：第一单位价格 * 第二单位转换数量
const twoPrice = computed({
  get() {
    const p = Number(form.price || 0);
    const c = Number(form.conUnitTwoConvert || 0);
    const val = c ? p * c : 0;
    return parseFloat(val.toFixed(4));
  },
  set(val) {
    const c = Number(form.conUnitTwoConvert || 0);
    if (!c || !isFinite(Number(val))) return;
    // 修改第二单位价格时，反算第一单位价格并保留四位小数
    form.price = parseFloat((Number(val) / c).toFixed(4));
  },
});

function onPriceChange(val) {
  if (!isFinite(Number(val))) return;
  form.price = parseFloat(Number(val).toFixed(4));
}

function onTwoPriceChange(val) {
  if (!isFinite(Number(val))) return;
  const c = Number(form.conUnitTwoConvert || 0);
  if (!c) return;
  form.price = parseFloat((Number(val) / c).toFixed(4));
}

const show = ref(false);
let dialogtitle = ref("");
function open(item) {
  dialogtitle.value = item ? "编辑" : "新增";
  Object.assign(form, item);
  show.value = true;
}
function formsAdd(index) {
  forms.value.push({ ...basicForm });
}
function close() {
  show.value = false;
}

const refform = ref();
const refForms = ref([]);
function setFormRef(el, index) {
  if (el) {
    refForms.value[index] = el;
  }
}
function returnPromise(index, prosise) {
  return new Promise((resolve, reject) => {
    prosise
      .then((res) => {
        console.log(res);
        resolve({ sucees: true });
      })
      .catch((err) => {
        console.log(err);
        resolve({ sucees: false });
      });
  });
}

const emits = defineEmits(["refresh"]);
async function submitForm() {
  refform.value.validate(async (valid) => {
    if (valid) {
      const res = dialogtitle.value == "新增" ? await consApi.add(form) : await consApi.edit(form);
      ElMessage({ type: "success", message: dialogtitle.value + "成功" });
      emits("refresh");
      close();
    }
  });
}
async function submitForms() {
  let isAllPassForm = 0;
  for (let i in this.forms) {
    console.log(refForms.value[i]);
    const res = await returnPromise(i, refForms.value[i].validate());
    console.log(res);
    isAllPassForm += res.sucees ? 1 : 0;
  }
  //判断验证是否通过
  if (isAllPassForm === this.forms.length) {
    await consApi.add(this.forms);
    ElMessage({ type: "success", message: "添加成功" });
    // for(let i of this.forms){
    //   const res=await posttbConsInfo(i)
    //   this.$message({ type: "success", message: "添加成功" });
    // }
    this.dialogshow = false;
    this.resetRuleForms();
    this.ruleFormLoading = false;
    this.getTableData();
  }
}
function reset() {
  refform.value.resetFields();
  Object.assign(form, basicForm);
  console.log(form);
}
defineExpose({
  open,
  close,
});
</script>

<style scoped lang="scss">
.center {
  display: flex;
  align-items: center;

  .ipt {
    display: flex;
    align-items: center;
    gap: 5px;
    margin-left: 28px;
  }
}
</style>