<template>
  <div>
    <el-form :model="form" label-width="180px" :rules="rules" ref="form">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="commonTableTypeId" label="分类">
            <el-select v-model="form.commonTableTypeId" placeholder="请选择" size="small" disabled>
              <el-option v-for="item in commonTableTypes" :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="24">
          <el-form-item prop="displayName" label="体检系统编码">
            <el-input v-model="form.displayName" size="small" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item prop="simpleCode" label="体检系统名称">
            <el-input v-model="form.simpleCode" size="small" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-for="col in Object.keys(commonTableCols)">
        <el-col :span="24">
          <el-form-item :prop="col" :label="commonTableCols[col]">
            <el-input v-model="form[col]" size="small" />
          </el-form-item>
        </el-col>
      </el-row> 
    </el-form>
    <div style="display: flex;margin-top: 15px;justify-content:space-between;">
      <div></div>
      <div style="display: flex;">
        <el-button class="commonbutton" @click="dialogWin.CommonTableEdit = 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";


export default {
  components: {

  },
  props: ["params","commonTableCols"],
  data() {
    return {
      form: {
        id: "",
        commonTableTypeId: null, //所属体检次数
        displayName: "",
        simpleCode:"",
        dataCode: "",
        dataCode2: "",
        dataCode3: "",
        dataCode4: "",
        dataCode5: "",
        dataCode6: "",
        dataCode7: "",
        dataCode8: "",
        dataCode9: ""
      },
      editType: 'insert',
      commonTableTypes: [], //    
      formInit: {}, //表单初始值
      rules: {
        commonTableTypeId: [{ required: true, message: "请填写分类名称", trigger: "blur" }],
        dataCode: [{ required: true, message: "请填写dataCode", trigger: "blur" }],
        displayName: [{ required: true, message: "请填写分组名称", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapState(["dict", "dialogWin", "dataTransOpts"]),
  },
  created() {
    this.form.id = this.params.id
    this.form.commonTableTypeId = this.params.commonTableTypeId
  },
  mounted() {
    // 获取初始数据（单位、适用性别） 
    this.dictInit();
    this.getFormData(this.params.id);
  },
  methods: {
    moment, dddw, deepCopy,

    // 获取初始数据
    dictInit() {
      //获取适用性别
      postapi("/api/app/CommonTableType/GetList").then((res) => {
        if (res.code != -1) {
          this.commonTableTypes = res.data;
        }
      });
    },

    // 生成表单数据
    getFormData(id) {
      this.$refs['form'].resetFields();

      if (id) {
        postapi('/api/app/CommonTable/Get', { commonTableId: id })
          .then(res => {
            if (res.code != -1) {
              this.form = deepCopy(res.data)
            }
          })
        this.editType = 'update'
      } else {
        // console.log('this.formInit', this.formInit)
        // this.form = this.$options.data().form        
        this.form = Object.assign({}, this.formInit, { commonTableTypeId: this.params.commonTableTypeId })
        this.editType = 'insert'
      }
    },


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

        let url = '/api/app/CommonTable/Create'
        let body = deepCopy(this.form);
        body.commonTableId = body.id

        if (this.editType == 'update') {
          url = '/api/app/CommonTable/Update'
        }

        //新增 编辑
        postapi(url, body)
          .then(res => {
            if (res.code != -1) {
              console.log("操作成功！");
              if(this.editType == 'insert') this.dataTransOpts.tableS.common_table.id = res.data.id
              this.dialogWin.CommonTableEdit = 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: {
    // 体检分组ID未切换换时 也可以强制刷新数据
    "dataTransOpts.refresh.common_table.S": {
      // immediate: true,
      handler(newVal, oldVal) {
        console.log(`watch 体检分组 newVal:${newVal} oldVal:${oldVal} common_table.id: ${this.params.id}`);
        if (newVal != oldVal) this.getFormData(this.params.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>
