<template>
  <div style="margin-left: 10px">
    <div>
      <span>项目类别</span>
      <el-cascader :options="dict.itemTypeTree" v-model="itemTypeIds"
        :props="{ checkStrictly: true, expandTrigger: 'hover', ...customerOrg.treeprops, }" :show-all-levels="false"
        clearable filterable @change="getAsbItemByItemType">
      </el-cascader>
    </div>

    <div class="mainareaBox">
      <el-table :header-cell-style="{ background: '#eef1f6' }" :data="dict.asbItem" height="200"
        @selection-change="handleSelectionChange" size="small">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="未选组合项目" prop="displayName"></el-table-column>
      </el-table>
    </div>

    <div class="mainbutton">
      <div style="margin-left: 10px">
        <el-button type="primary" @click="addAbs">添加 <i class="el-icon-bottom"></i>
        </el-button>
      </div>
      <div style="margin-left: 10px">
        <el-button type="primary" @click="delAbs">移除 <i class="el-icon-top"></i>
        </el-button>
      </div>
      <div style="margin-left: 10px">
        <el-button type="success" @click="onSubmit('保存')">保存 <i class="el-icon-check"></i>
        </el-button>
      </div>
    </div>

    <div class="mainareaBox">
      <el-table :data="patientRegister.patientRegisterAbs" height="200" :summary-method="getSummaries" show-summary
        @selection-change="selecteditems" size="small">
        <!-- temporaryselection   personnelUnit.nogroupselected-->
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="已选组合项目" width="110" prop="asbitemName" />
        <el-table-column label="标准价格" prop="standardPrice" />
        <el-table-column label="折扣" prop="discount">
          <template slot-scope="scope">
            <el-input v-model="scope.row.discount" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="实收价格" prop="chargePrice">
          <template slot-scope="scope">
            <el-input v-model="patientRegister.patientRegisterAbs[scope.$index].chargePrice" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="amount">
          <template slot-scope="scope">
            <el-input v-model="patientRegister.patientRegisterAbs[scope.$index].amount" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="支付方式" prop="payTypeFlag" width="100">
          <template slot-scope="scope">
            <el-select v-model="patientRegister.patientRegisterAbs[scope.$index].payTypeFlag" size="small">
              <el-option v-for="item in dict.payType" :key="item.id" :label="item.displayName" :value="item.id"
                width="100" />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import { mapState, mapActions } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { arrayFilter, arrayReduce, arrayExistObj } from "../../utlis/proFunc";
export default {
  props: ["patientRegisterForm"],
  data() {
    return {
      itemType: [], //项目类别
      itemTypeIds: '', //被选中的项目类别ID
      asbItemChoosed: [], //勾选的  未选组合项目

      //patientRegisterAbs:[],         //体检人员所选组合项目 放vuex
      patientRegisterAbsChoosed: [], //勾选的 体检人员所选组合项目
      //patientRegisterAbsDel: [], //体检人员 待删除的组合项目

      patientRegisterAbsRd: {
        id: null,         //更新不需传
        asbitemId: null, // string($uuid) 组合项目
        asbitemName: '',  //组合项目名称，更新不需传
        patientRegisterId: null, //string($uuid) 登记流水号
        standardPrice: 0, //number($double) 标准价格
        chargePrice: 0, //	number($double) 实收价格
        payTypeFlag: "0", // string 支付方式,比如是自费、免费、单位支付  0自费、2免费、1单位支付
        isCharge: "N", //	string 是否已收费
        //lisRequestId: null, //	string($uuid)LIS申请ID
        amount: 1, //	integer($int32) 数量
        groupPackageId: null, //	string($uuid) 分组或者套餐ID
      }, //单个添加的组合项目
    };
  },
  computed: {
    ...mapState(["dict", "customerOrg", "patientRegister", "personnelUnit"]),
  },

  mounted() { },

  methods: {
    ...mapActions(['getCustomerOrgGroup', 'getMedicalPackageAsb', 'getPatientRegisterAbs']),

    //保存按钮
    // [
    //   {
    //     "registerAsbitemId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    //     "input": {
    //       "chargePrice": 0,
    //       "payTypeFlag": "string",
    //       "isCharge": "string",
    //       "amount": 0,
    //       "groupPackageId": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
    //     }
    //   }
    // ]

    //批量更新组合项目
    async batchEditAsb(body, msg) {
      console.log(`/api/app/registerasbitem/updatemany`, body)
      postapi(`/api/app/registerasbitem/updatemany`, body)
        .then((res) => {
          console.log("onSubmit", res);
          if (res.code == 1) {
            if (msg) {
              //未选项目中移除，已选项中添加
              this.getPatientRegisterAbs(this.patientRegisterForm.id)
              this.$message.success(`${msg}操作成功`);
            }
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `${msg}操作失败，原因：${err}` });
        });
    },

    //更新所选组合项目
    async onSubmit(msg) {
      let body = [], insBody = []
      if (!this.patientRegisterForm.id) {
        alert("请先保存人员体检基本信息！")
        return
      }
      if (this.patientRegister.patientRegisterAbs.length < 1) {
        alert("暂无可操作的数据")
        return
      }
      for (let i = 0; i < this.patientRegister.patientRegisterAbs.length; i++) {
        if (this.patientRegister.patientRegisterAbs[i].id) {
          body.push({
            registerAsbitemId: this.patientRegister.patientRegisterAbs[i].id,
            input: {
              chargePrice: this.patientRegister.patientRegisterAbs[i].chargePrice,
              payTypeFlag: this.patientRegister.patientRegisterAbs[i].payTypeFlag,
              isCharge: this.patientRegister.patientRegisterAbs[i].isCharge,
              amount: this.patientRegister.patientRegisterAbs[i].amount,
              groupPackageId: this.patientRegister.patientRegisterAbs[i].groupPackageId
            }
          })
        } else {
          insBody.push({
            asbitemId: this.patientRegister.patientRegisterAbs[i].asbitemId,
            patientRegisterId: this.patientRegisterForm.id,
            standardPrice: this.patientRegister.patientRegisterAbs[i].standardPrice,
            chargePrice: this.patientRegister.patientRegisterAbs[i].chargePrice,
            payTypeFlag:this.patientRegister.patientRegisterAbs[i].payTypeFlag,
            isCharge: this.patientRegister.patientRegisterAbs[i].isCharge,
            amount: this.patientRegister.patientRegisterAbs[i].amount,
            groupPackageId: this.patientRegister.patientRegisterAbs[i].groupPackageId
          })
        }
      }

      //if (body.length > 0 ) await this.batchEditAsb(body, msg);
      if (body.length > 0 && insBody.length > 0){
        await this.batchEditAsb(body, '');
        await this.batchAddAsb(insBody,msg);
      }else if (body.length > 0 && insBody.length < 1){
        await this.batchEditAsb(body, msg);
      }else if (body.length < 1 && insBody.length > 0){
        await this.batchAddAsb(insBody,msg);
      }

    },

    //未选组合项目 勾选情况
    handleSelectionChange(val) {
      // this.selecteddata = val;
      this.asbItemChoosed = val;
      //console.log(this.asbItemChoosed);
    },

    //批量添加组合项目
    batchAddAsb(body, msg) {
      console.log(`/api/app/registerasbitem/createmany?CustomerOrgId=${this.patientRegisterForm.customerOrgId}`, body)
      postapi(`/api/app/registerasbitem/createmany?CustomerOrgId=${this.patientRegisterForm.customerOrgId}`, body)
        .then((res) => {
          console.log("batchAddAsb", res);
          if (res.code == 1) {
            //未选项目中移除，已选项中添加
            this.getPatientRegisterAbs(this.patientRegisterForm.id)
            if (msg) this.$message.success(`${msg}操作成功`);
          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `${msg}操作失败，原因：${err}` });
        });
    },

    // 添加组合项目
    ///api/app/register-asbitem/many/3fa85f64-5717-4562-b3fc-2c963f66afa6'
    addAbs() {
      let body = []
      let checked = true
      let payTypeFlag = '0' //默认个人支付
      let lfind = -1
      if (this.asbItemChoosed.length < 1) {
        alert("请选择要添加的组合项目")
        return
      }

      //性别、年龄判断 
      // "displayName": "身高体重",
      //   "shortName": "哈f哈",
      //   "forSexId": "F",
      //   "itemTypeId": "3a0b16de-75b9-c910-c61b-844709a88940",
      //   "price": 0,
      //console.log('this.asbItemChoosed.length',this.asbItemChoosed.length)
      for (let i = 0; i < this.asbItemChoosed.length; i++) {
        if (this.patientRegisterForm.sexId == 'U') break //未选性别时，无需判断组合项目性别限制
        if (this.asbItemChoosed[i].forSexId == 'A') continue
        if (this.asbItemChoosed[i].forSexId != this.patientRegisterForm.sexId) {
          alert(`所选项目：${this.asbItemChoosed[i].displayName}，不适合当前人员性别`)
          checked = false
          break
        }
      }
      //console.log(222,checked)
      if (!checked) return

      if (this.patientRegisterForm.customerOrgId != this.dict.personOrgId) payTypeFlag = '1'
      for (let i = 0; i < this.asbItemChoosed.length; i++) {
        let pojo = {
          asbitemId: this.asbItemChoosed[i].id,
          patientRegisterId: this.patientRegisterForm.id,
          standardPrice: this.asbItemChoosed[i].price,
          chargePrice: this.asbItemChoosed[i].price,
          payTypeFlag,
          isCharge: "N",
          amount: 1
        }
        body.push(pojo)
        this.patientRegister.patientRegisterAbs.push({ ...pojo, asbitemName: this.asbItemChoosed[i].displayName })
        lfind = arrayExistObj(this.dict.asbItem, 'id', this.asbItemChoosed[i].id)
        if (lfind > -1) this.dict.asbItem.splice(lfind, 1)
      }

      if (this.patientRegisterForm.id) this.batchAddAsb(body, '添加组合项目');

    },



    //人员已选组合项目 勾选情况
    selecteditems(val) {
      this.patientRegisterAbsChoosed = val
    },

    //批量删除组合项目
    batchDelAsb(body, msg) {
      console.log(`/api/app/registerasbitem/deletemany`, body)
      postapi(`/api/app/registerasbitem/deletemany`, body)
        .then((res) => {
          console.log("delAbs", res);
          if (res.code != -1) {
            //项目类别过滤 组合项目，未过滤已选择的组合项目
            this.getAsbItemByItemTypeAll()

            if (msg) {
              //未选项目中移除，已选项中添加
              this.getPatientRegisterAbs(this.patientRegisterForm.id)
              this.$message.success(`${msg}操作成功`);
            }

          }
        })
        .catch((err) => {
          this.$message({ type: "error", message: `${msg}操作失败，原因：${err}` });
        });
    },
    //删除 人员已选中的组合项目
    ///api/app/register-asbitem/many?RegisterAsbitemIds=3fa85f64-5717-4562-b3fc-2c963f66afa6
    delAbs() {
      let body = {}
      let registerAsbitemIds = []
      let chargeComplete = ''
      let lfind = -1

      if (this.patientRegisterAbsChoosed.length < 1) {
        alert("请选择要移除的组合项目")
        return
      }

      for (let i = 0; i < this.patientRegisterAbsChoosed.length; i++) {
        //未在数据库中，直接删除
        if (!this.patientRegisterAbsChoosed[i].id) {
          lfind = arrayExistObj(this.patientRegister.patientRegisterAbs, 'asbitemId', this.patientRegisterAbsChoosed[i].asbitemId)
          if (lfind > -1) this.patientRegister.patientRegisterAbs.splice(lfind, 1)

          this.patientRegisterAbsChoosed.splice(i, 1)
          i--
          continue
        }

        if (this.patientRegisterAbsChoosed[i].isCharge == 'Y' || this.patientRegisterAbsChoosed[i].checkCompleteFlag != '0') {
          chargeComplete += this.patientRegisterAbsChoosed[i].asbitemName + '，'
          this.patientRegisterAbsChoosed.splice(i, 1)
          i--
        }
      }

      //刷新
      this.getAsbItemByItemType()

      if (chargeComplete) {
        this.$message({ type: "info", message: `所选项目：${chargeComplete}已收费或已检，不可删除！` });
        if (this.patientRegisterAbsChoosed.length < 1) return
      }

      for (let i = 0; i < this.patientRegisterAbsChoosed.length; i++) {
        registerAsbitemIds.push(this.patientRegisterAbsChoosed[i].id)
      }

      body = { registerAsbitemIds }
      if (registerAsbitemIds.length > 0 && this.patientRegisterForm.id) this.batchDelAsb(body, '删除组合项目');

    },

    //项目类别过滤 组合项目，未过滤已选择的组合项目
    getAsbItemByItemTypeAll() {
      console.log('getAsbItemByItemType', typeof this.itemTypeIds, this.itemTypeIds)
      let lv = "";
      if (typeof this.itemTypeIds === "object") {
        lv = this.itemTypeIds[this.itemTypeIds.length - 1];
      }

      if (lv) {
        this.dict.asbItem = arrayFilter(this.dict.asbItemAll, "itemTypeId", lv);
      } else {
        this.dict.asbItem = [...this.dict.asbItemAll];
      }
      console.log('lv,this.dict.asbItem', lv, this.dict.asbItem)

    },

    //按项目类别显示组合项目，并过滤已选择的组合项目
    getAsbItemByItemType() {
      this.getAsbItemByItemTypeAll()
      //刷新显示 未选组合项目
      arrayReduce(this.dict.asbItem, [...this.patientRegister.patientRegisterAbs], "id=asbitemId");
    },


    //体检登记的组合项目创建
    // registerAsbitem(body) {
    //   console.log("registerAsbitem");
    //   postapi(
    //     `/api/app/register-asbitem?CustomerOrgId=${this.patientRegisterForm.customerOrgId}`,
    //     body
    //   ).then((res) => {
    //     console.log("medicalPackageAsb", res);
    //     if (res.code == 1) {
    //       //未选项目中移除，已选项中添加
    //     }
    //   });
    // },

    //选中分组所包含的组合项目
    getCustomerOrgGroupAsb(customerOrgGroupId) {
      console.log(`getCustomerOrgGroupAsb /api/app/customer-org-group-detail/customer-org-group-detail-in-asbitem/${customerOrgGroupId}`);
      getapi(`/api/app/customer-org-group-detail/customer-org-group-detail-in-asbitem/${customerOrgGroupId}`)
        .then((res) => {
          console.log("getCustomerOrgGroupAsb", res);
          if (res.code == 1) {
            this.patientRegister.customerOrgGroupAsb = res.data;
            //移除旧分组或套餐的组合项目
            this.removeGroupPackageAsb();

            //添加新分组的组合项目;
            this.addCustomerOrgGroupAsb(customerOrgGroupId);
          }
        });
    },

    //选中套餐所包含的组合项目
    getMedicalPackageAsb(medicalPackageId) {
      console.log(`/api/app/medical-package-detail/medical-package-in-asbitem?MedicalPackageId=${medicalPackageId}`);
      getapi(`/api/app/medical-package-detail/medical-package-in-asbitem?MedicalPackageId=${medicalPackageId}`)
        .then((res) => {
          console.log("getMedicalPackageAsb", res);
          if (res.code == 1) {
            this.patientRegister.medicalPackageAsb = res.data;

            //移除旧分组或套餐的组合项目
            this.removeGroupPackageAsb();

            //添加新套餐的组合项目
            this.addMedicalPackageAsb(medicalPackageId);
          }
        });
    },

    //添加新分组的组合项目
    async addCustomerOrgGroupAsb(groupPackageId) {
      let body = []
      let payTypeFlag = '0'
      let lfind = -1
      let editCount = 0

      if (this.patientRegisterForm.customerOrgId != this.dict.personOrgId) payTypeFlag = '1'
      console.log('this.patientRegister.customerOrgGroupAsb', this.patientRegister.customerOrgGroupAsb)
      for (let i = 0; i < this.patientRegister.customerOrgGroupAsb.length; i++) {
        lfind = arrayExistObj(this.patientRegister.patientRegisterAbs, 'asbitemId', this.patientRegister.customerOrgGroupAsb[i].asbitemId)
        if (lfind > - 1) {
          this.patientRegister.patientRegisterAbs[lfind].groupPackageId = groupPackageId
          continue
        }
        let pojo = {
          asbitemId: this.patientRegister.customerOrgGroupAsb[i].asbitemId,
          patientRegisterId: this.patientRegisterForm.id,
          standardPrice: this.patientRegister.customerOrgGroupAsb[i].price,
          chargePrice: this.patientRegister.customerOrgGroupAsb[i].customerOrgGroupDetailPrice,
          payTypeFlag,
          isCharge: "N",
          amount: 1,
          groupPackageId: groupPackageId
        }
        body.push(pojo)
        this.patientRegister.patientRegisterAbs.push({ ...pojo, asbitemName: this.patientRegister.customerOrgGroupAsb[i].displayName })

      }
      console.log('this.patientRegister.patientRegisterAbs', this.patientRegister.patientRegisterAbs)
      // if (editCount > 0 && this.patientRegisterForm.id) await this.onSubmit('');
      // if (body.length > 0 && this.patientRegisterForm.id) {
      //   await this.batchAddAsb(body, '更换分组');
      // } else {
      //   //刷新
      //   this.getAsbItemByItemType()
      // }
      if(this.patientRegister.patientRegisterAbs.length > 0 && this.patientRegisterForm.id){
        await this.onSubmit('更换分组');
      }

    },

    //添加新套餐的组合项目
    async addMedicalPackageAsb(groupPackageId) {
      let body = []
      let payTypeFlag = '0'
      let lfind = -1
      let editCount = 0

      if (this.patientRegisterForm.customerOrgId != this.dict.personOrgId) payTypeFlag = '1'
      for (let i = 0; i < this.patientRegister.medicalPackageAsb.length; i++) {
        lfind = arrayExistObj(this.patientRegister.patientRegisterAbs, 'asbitemId', this.patientRegister.medicalPackageAsb[i].id)
        if (lfind > - 1) {
          this.patientRegister.patientRegisterAbs[lfind].groupPackageId = groupPackageId
          editCount++
          continue
        }
        let pojo = {
          asbitemId: this.patientRegister.medicalPackageAsb[i].id,
          patientRegisterId: this.patientRegisterForm.id,
          standardPrice: this.patientRegister.medicalPackageAsb[i].price,
          chargePrice: this.patientRegister.medicalPackageAsb[i].price,
          payTypeFlag,
          isCharge: "N",
          amount: 1,
          groupPackageId: groupPackageId
        }
        body.push(pojo)
        this.patientRegister.patientRegisterAbs.push({ ...pojo, asbitemName: this.patientRegister.customerOrgGroupAsb[i].displayName })
      }

      if (editCount > 0 && this.patientRegisterForm.id) await this.onSubmit('');
      if (body.length > 0 && this.patientRegisterForm.id) {
        await this.batchAddAsb(body, '更换分组');
      } else {
        //刷新
        this.getAsbItemByItemType()
      }
    },

    //移除旧分组或套餐的组合项目
    async removeGroupPackageAsb() {
      let body = {}
      let registerAsbitemIds = []
      let chargeComplete = ''

      //体检基本信息未保存时，删除所有所选项目
      if (!this.patientRegisterForm.id) {
        this.patientRegister.patientRegisterAbs = []
        return
      }

      //删除已选 分组或套餐的组合项目 ，如已收费或 已检时，将 groupPackageId 置为null
      for (let i = 0; i < this.patientRegister.patientRegisterAbs.length; i++) {
        if (!this.patientRegister.patientRegisterAbs[i].id) {
          this.patientRegister.patientRegisterAbs.splice(i, 1)
          i--
          continue
        }
        if (this.patientRegister.patientRegisterAbs[i].isCharge == 'Y' || this.patientRegister.patientRegisterAbs[i].checkCompleteFlag != '0') {
          chargeComplete += this.patientRegister.patientRegisterAbs[i].asbitemName + '，'
          this.patientRegister.patientRegisterAbs[i].groupPackageId = null
        } else {
          //数据库有，才添加到待删除的数组中
          if (this.patientRegister.patientRegisterAbs[i].id) {
            registerAsbitemIds.push(this.patientRegister.patientRegisterAbs[i].id)
          }
          this.patientRegister.patientRegisterAbs.splice(i, 1)
          i--
        }
      }

      if (chargeComplete) {
        this.$message({ type: "info", message: `所选项目：${chargeComplete}已收费或已检，不可删除！` });
      }

      body = { registerAsbitemIds }
      if (registerAsbitemIds.length > 0) {
        await this.batchDelAsb(body, '');
      }

      let updateBody = []
      if (this.patientRegister.patientRegisterAbs.length > 0) {
        for (let i = 0; i < this.patientRegister.patientRegisterAbs.length; i++) {
          //数据库有，才添加到待更新的数组中
          if (this.patientRegister.patientRegisterAbs[i].id) {
            updateBody.push({
              registerAsbitemId: this.patientRegister.patientRegisterAbs[i].id,
              input: {
                chargePrice: this.patientRegister.patientRegisterAbs[i].chargePrice,
                payTypeFlag: this.patientRegister.patientRegisterAbs[i].payTypeFlag,
                isCharge: this.patientRegister.patientRegisterAbs[i].isCharge,
                amount: this.patientRegister.patientRegisterAbs[i].amount,
                groupPackageId: this.patientRegister.patientRegisterAbs[i].groupPackageId
              }
            })
          }
        }
        await this.batchEditAsb(updateBody, '');
      }

    },

    //自定义计算列
    getSummaries(param) {
      const { columns, data } = param;
      const sumCol = [2,4]  //需合计的列
      const sums = [];
      columns.forEach((column, index) => {
        //显示合计列
        if (index === 1) {
          sums[index] = '合计';
          return;
        }

        //不合计的列
        if (sumCol.indexOf(index) == -1) {
          sums[index] = '';
          return;
        }
        
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },

  },

  //监听事件
  watch: {
    //分组改变，查出当前分组下对应的组合项目
    "patientRegister.customerOrgGroupChange"(newVal, oldVal) {
      console.log("watch patientRegister.customerOrgGroupChange newVal：", newVal, " oldVal：", oldVal);
      if (newVal != oldVal && newVal > 0) {
        this.getCustomerOrgGroupAsb(this.patientRegisterForm.customerOrgGroupId);
      }
    },

    //套餐改变，查出当前套餐下对应的组合项目
    "patientRegister.medicalPackageChange"(newVal, oldVal) {
      console.log("watch patientRegister.medicalPackageChange newVal：", newVal, " oldVal：", oldVal);
      if (newVal != oldVal && newVal > 0) {
        this.getMedicalPackageAsb(this.patientRegisterForm.medicalPackageId);
      }
    },

    //体检信息触发分组的保存
    "patientRegister.saveTimes"(newVal, oldVal) {
      this.onSubmit('')
    },
  },
};
</script>
<style scoped>
.mainareaBox {
  border: 1px solid #000;
  height: 200px;
  margin-top: 10px;
}

.mainbutton {
  display: flex;
  margin-left: 20px;
  padding: 5px 10px;
  margin-top: 10px;
}
</style>
