<template>
  <div>
    <el-form :model="form" label-width="80px" :rules="rules" ref="form">
      <el-row>
        <el-col :span="8">
          <el-form-item prop="displayName" label="分组名称">
            <el-input v-model="form.displayName" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="金额">
            <el-input v-model="form.price" type="number" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="适用性别">
            <el-select v-model="form.forSexId" placeholder="请选择" size="small">
              <el-option v-for="item in dict.forSex" :key="item.id" :label="item.displayName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="婚姻状况">
            <el-select v-model="form.maritalStatusId" placeholder="请选择" style="width: 100%" size="small">
              <el-option v-for="item in dict.forMaritalStatus" :key="item.id" :label="item.displayName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年龄下限">
            <el-input v-model="form.ageLowerLimit" type="number" min="1" max="200" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="年龄上限">
            <el-input v-model="form.ageUpperLimit" type="number" min="1" max="200" size="small" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="适用职务">
            <el-input v-model="form.jobPost" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="适用职称">
            <el-input v-model="form.jobTitle" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="可自选金额">
            <el-input type="number" v-model="form.canAddMoney" size="small" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark" size="small" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="display: flex;margin-top: 5px;justify-content:space-between;">
      <div></div>
      <div style="display: flex;">
        <el-button class="commonbutton" @click="dialogWin.CustomerOrgGroupEdit = false">关闭</el-button>
        <!--
        <el-button type="success" @click="computePrice">同比折算组合项目价格</el-button>
        -->
        <el-button class="commonbutton" type="primary" @click="onSubmit('form')">确定</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import moment from "moment";

import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { mapState } from "vuex";
import {
  dddw,
  deepCopy,
  objCopy,
  arrayExistObj,
} from "../../utlis/proFunc";

import CustomerOrgGroupAsbitem from "../../components/customerOrg/customerOrgGroupAsbitem.vue";

export default {
  components: {
    CustomerOrgGroupAsbitem,
  },
  props: ["params"],
  data() {
    return {
      form: {
        //体检单位分组
        customerOrgId: "", //复制分组时用到(预留查历次分组)
        isComplete: "N", //体检次数是否完成，如完成不允许调整分组项目
        id: "",
        customerOrgRegisterId: null, //所属体检次数
        displayName: "",
        price: 0,
        forSexId: "A",
        maritalStatusId: "A",
        ageLowerLimit: 0,
        ageUpperLimit: 200,
        canAddMoney:0,
        jobPost: "",
        jobTitle: "",
        remark: "",
        isMaxMedicalTimes: "N",
      },
      formOri: {}, //用于对比分析哪些信息更改了（主要是价格）
      formInit: {}, //表单初始值
      rules: {
        displayName: [{ required: true, message: "请填写分组名称", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapState(["dict", "dialogWin", "dataTransOpts"]),
  },
  created() {
    this.formInit = deepCopy(this.form);
    this.form.customerOrgId = this.params.customerOrgId
    this.form.customerOrgRegisterId = this.params.customerOrgRegisterId
  },
  mounted() {
    // 获取初始数据（单位、适用性别） 
    this.dictInit();
    this.getFormData(this.dataTransOpts.tableS.customer_org_group.id);
  },
  methods: {
    moment, dddw, deepCopy,

    // 获取初始数据
    dictInit() {
      //获取单位列表
      getapi("/api/app/customer-org/parent-all").then((res) => {
        if (res.code != -1) {
          this.customerOrgAll = res.data;
          let lfind = arrayExistObj(this.customerOrgAll, "id", this.dict.personOrgId);
          if (lfind > -1) this.customerOrgAll.splice(lfind, 1);
          this.customerOrg = deepCopy(this.customerOrgAll);
        }
      });

      //获取适用性别
      getapi("/api/app/for-sex").then((res) => {
        if (res.code != -1) {
          this.dict.forSex = res.data;
        }
      });
    },

    // 生成表单数据
    getFormData(id) {
      if (id) {
        getapi(`/api/app/customer-org-group/${id}`)
          .then(res => {
            if (res.code != -1) {
              this.formOri = deepCopy(res.data)
              this.form = deepCopy(res.data)
            }
          })
      } else {
        console.log('this.formInit',this.formInit)
        this.form = deepCopy(this.formInit)
        this.form.customerOrgId = this.params.customerOrgId
        this.form.customerOrgRegisterId = this.params.customerOrgRegisterId
      }
    },


    onSubmit(formName) {
      this.$refs[formName].validate((valid, fields) => {
        if (!valid) {
          this.$message.warning(fields[Object.keys(fields)[0]][0].message);
          return false;
        }

        if (!this.form.id && !this.form.customerOrgRegisterId) {
          this.$message.warning("请选择单位体检次数！");
          return false;
        }

        let body = deepCopy(this.form);
        delete body.id;
        delete body.customerOrgId;
        delete body.isComplete;

        if (this.form.id) {
          let customerOrgGroupId = this.form.id;
          let customerOrgGroupAsbitems = []; //分组包含的套餐

          //编辑
          /*
          putapi(`/api/app/customer-org-group/${this.form.id}`, body)
            .then((res) => {
              // console.log(res)
              if (res.code != -1) {
                console.log("保存分组成功！");                
                // 价格是否有调整
                if (this.formOri.price != this.form.price) {
                  return getapi(`/api/app/customerorggroupdetail/getcustomerorggroupdetailinasbitem?CustomerOrgGroupId=${customerOrgGroupId}`);
                } else {
                  this.dialogWin.CustomerOrgGroupEdit = false;
                }
              }
            })
            .then((res) => {
              if (res && res.code != -1) {
                customerOrgGroupAsbitems = res.data;
                if (customerOrgGroupAsbitems.length < 1) {
                  console.log("该分组暂没有组合项目！");
                  this.dialogWin.CustomerOrgGroupEdit = false;
                } else {
                  let detailsBody = {
                    customerOrgGroupId,
                    details: this.madeNewGroupAsbitems(customerOrgGroupAsbitems, this.form.price),
                  };
                  return postapi("/api/app/customerorggroupdetail/createcustomerorggroupdetailmany", detailsBody);
                }
              }
            })
            .then((res) => {
              if (res && res.code != -1) {
                console.log("操作成功！并自动按总价同比折算组合项目价格！");
                this.dialogWin.CustomerOrgGroupEdit = false;
                // 刷新明细
                let id = this.form.id;
                this.form.id = "";
                setTimeout(() => {
                  this.form.id = id;
                }, 100);
              }
            });
          */
          // 合并事务更新明细金额
          putapi(`/api/app/customer-org-group/${this.form.id}`, body)
            .then((res) => {
              // console.log(res)
              if (res.code != -1) {
                console.log("保存分组成功！");   
                this.dataTransOpts.refresh.customer_org_group_detail.M
              }
            })
            
        } else {
          //新增
          postapi("/api/customerorggroup/createcustomerorggroupincustomerorgregister", body)
            .then(res => {
              if (res.code != -1) {
                console.log("操作成功！");
                this.dataTransOpts.tableS.customer_org_group.id = res.data.id                
                this.dialogWin.CustomerOrgGroupEdit = false;
              }
            });
        }
      });
    },

    //
    computePrice() {
      if (!this.form.id) {
        this.$message.warning("尚未保存信息，不可执行此操作！");
        return;
      }
      let customerOrgGroupId = this.form.id;
      let customerOrgGroupAsbitems = []; //分组包含的套餐

      getapi(`/api/app/customerorggroupdetail/getcustomerorggroupdetailinasbitem?CustomerOrgGroupId=${customerOrgGroupId}`)
        .then((res) => {
          if (res.code != -1) {
            customerOrgGroupAsbitems = res.data;

            if (customerOrgGroupAsbitems.length < 1) {
              this.$message.warning("当前分组尚未设置组合项目，不可执行此操作！");
            } else {
              let body = {
                customerOrgGroupId,
                details: this.madeNewGroupAsbitems(
                  customerOrgGroupAsbitems,
                  this.form.price
                ),
              };
              console.log("body", body);
              return postapi("/api/app/customerorggroupdetail/createcustomerorggroupdetailmany", body);
            }
          }
        })
        .then((res) => {
          if (res.code != -1) {
            //console.log("操作成功");
            //触发分组明细刷新
            this.form.id = "";
            //要做延时处理，否则不会触发监听
            setTimeout(() => {
              this.form.id = customerOrgGroupId;
              this.onSubmit("form");
            }, 100);
          }
        });
    },

    madeNewGroupAsbitems(oldGroupAsbitems, newTotal) {
      newTotal = Math.round(Number(newTotal) * 100) / 100;
      let newGroupAsbitems = [];
      let oldTotal = Number(0);
      oldGroupAsbitems.forEach((e) => {
        oldTotal += Number(e.asbitemMoney); //customerOrgGroupDetailMoney
      });
      oldTotal = Math.round(Number(oldTotal) * 100) / 100;

      let discount = 0;
      if (oldTotal != 0) discount = Math.round((newTotal * 10000) / oldTotal) / 100;

      oldTotal = Number(0);
      oldGroupAsbitems.forEach((e) => {
        e.customerOrgGroupDetailPrice = Math.round(e.price * discount) / 100;
        e.customerOrgGroupDetailMoney =
          Math.round(
            e.customerOrgGroupDetailPrice * e.customerOrgGroupDetailAmount * 100
          ) / 100;
        oldTotal += Number(e.customerOrgGroupDetailMoney);
      });
      oldTotal = Math.round(Number(oldTotal) * 100) / 100;

      //console.log('discount,oldTotal',discount,oldTotal)

      let didTotal = Math.round(Number(newTotal - oldTotal) * 100) / 100;
      if (didTotal != 0) {
        for (let i = 0; i < oldGroupAsbitems.length; i++) {
          if (oldGroupAsbitems[i].customerOrgGroupDetailAmount == 1) {
            oldGroupAsbitems[i].customerOrgGroupDetailPrice =
              Math.round(
                (Number(oldGroupAsbitems[i].customerOrgGroupDetailPrice) +
                  Number(didTotal)) *
                100
              ) / 100;
            break;
          }
        }
      }

      oldGroupAsbitems.forEach((e) => {
        newGroupAsbitems.push({
          customerOrgGroupId: e.customerOrgGroupId,
          asbitemId: e.asbitemId,
          price: e.customerOrgGroupDetailPrice,
          amount: e.customerOrgGroupDetailAmount,
        });
      });

      return newGroupAsbitems;
    },


  },
  //监听事件
  watch: {
    //
    // "customerOrgGroup.id"(newVal, oldVal) {
    //   console.log("customerOrgGroup.id ",newVal,oldVal);
    //   if (newVal != oldVal) {
    //     this.getCustomerOrgGroupAsbitems(newVal);
    //   }
    // },

    // 体检分组ID未切换换时 也可以强制刷新数据
    "dataTransOpts.refresh.customer_org_group.S": {
      // immediate: true,
      handler(newVal, oldVal) {
        console.log(`watch 体检分组 newVal:${newVal} oldVal:${oldVal} customerOrgGroupId: ${this.dataTransOpts.tableS.customer_org_group.id}`);
        this.getFormData(this.dataTransOpts.tableS.customer_org_group.id);
      }
    },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_button.css";
@import "../../assets/css/global_dialog.css";
@import "../../assets/css/global_table.css";
@import "../../assets/css/global_form.css";
@import "../../assets/css/global_input.css";
@import "../../assets/css/global.css";

.btnClass {
  width: 100px;
  margin-bottom: 5px;
}
</style>
