<template>
  <div style="display: flex; margin-left: 10px; margin-top: 10px;">
    <div style="width:220px;">
      <div>
        <span>项目类别</span>
        <el-cascader :options="dict.itemTypeTree" v-model="itemTypeIds" style="margin-left: 3px;width:160px;"
          :props="{ checkStrictly: true, expandTrigger: 'hover', ...customerOrg.treeprops, }" :show-all-levels="false"
          clearable filterable @change="getAsbItemByItemType" size="small">
        </el-cascader>
      </div>
      <div class="mainareaBox">
        <el-table :data="dict.asbItem"
          :height="(window.pageHeight > 720 ? (window.pageHeight - 460) : 260)" @row-dblclick="dbClickChoosedAsb" highlight-current-row
          @selection-change="handleSelectionChange" size="small" :row-class-name="handleRowClassName" 
          @row-click="chooseAsbItem">
          <!--
          <el-table-column type="selection" align="center" width="40" />
          -->
          <el-table-column prop="displayName" label="未选组合项目" />
          <!--
          <el-table-column prop="price" label="标准价格" width="70">
            <template slot-scope="scope">
              <div style="text-align: center;">{{ scope.row.price }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="forSexId" label="适用性别" width="70">
            <template slot-scope="scope">
              <div style="text-align: center;">{{ ldddw(dict.forSex, "id", scope.row.forSexId, "displayName") }}</div>
            </template>
          </el-table-column>
          -->          
        </el-table>
      </div>
    </div>

    <div style="width:100px;margin-top: 70px;">
      <div class="btnList">
        <el-button type="primary" @click="addAbs(asbItemChoosed,'choosed')" style="width:90px;">添加 <i class="el-icon-arrow-right"></i>
        </el-button>
      </div>
      <div class="btnList">
        <el-button type="success" @click="addAbs(asbItemChoosed,'all')" style="width:90px;">全添加 <i class="el-icon-d-arrow-right"></i>
        </el-button>
      </div>
      <div class="btnList">
        <el-button type="warning" @click="delAbs(patientRegisterAbsChoosed,'choosed')" style="width:90px;"><i class="el-icon-arrow-left"> 移除</i>
        </el-button>
      </div>
      <div class="btnList">
        <el-button type="danger" @click="delAbs(patientRegisterAbsChoosed,'all')" style="width:90px;"><i class="el-icon-d-arrow-left"> 全移除</i>
        </el-button>
      </div>
      <!-- 不显示保存，当已选组合有修改时，失去焦点自动保存
      <div class="btnList">
        <el-button type="success" @click="onSubmit('保存')">保存 <i class="el-icon-check"></i>
        </el-button>
      </div> 
      -->
    </div>

    <div :style="'width:' + (window.pageWidth - 120 - 30 - 230 - 100) + 'px;'">
      <div style="display: flex;">
        <div class="disTotal">
          <el-tooltip class="item" effect="dark" content="根据输入的折扣，自动计算折后总价" placement="top">
            <span>折扣 </span>
          </el-tooltip>
          <el-input style="width:55px;" v-model="discount" size="small" type="number" @input="changeAllDiscount"
            @focus="discountFoucs = true" @blur="discountFoucs = false" />
        </div>
        <div class="disTotal">
          <el-tooltip class="item" effect="dark" content="总金额即该人员此次体检实收金额，并根据此金额自动计算折扣" placement="top">
            <span>总金额 </span>
          </el-tooltip>
          <el-input style="width:70px;" v-model="total" size="small" type="number" @input="changeTotal" ref="total"
            @focus="totalFoucs = true" @blur="totalFoucs = false" />
        </div>
        <div class="disTotal">
          <el-select v-model="asbItemId" placeholder="快速选择组合项目" size="small" filterable clearable remote automatic-dropdown
            :remote-method="remoteMethod" @change="quickChoosedAsb" default-first-option ref="asbItemId"
            style="width:150px;text-align: left;padding-right: 15px;">
            <el-option v-for="item in quickAsb" :key="item.id" :value="item.id" :label="item.displayName" />
          </el-select>
        </div>
      </div>
      <div class="mainareaBox">
        <el-table :data="patientRegister.patientRegisterAbs" highlight-current-row
          :height="(window.pageHeight > 720 ? (window.pageHeight - 460) : 260)" width="100%" :summary-method="getSummaries"
          show-summary :row-class-name="tableRowClassName" @row-dblclick="removeAbs" @selection-change="selecteditems" size="small"
          @row-click="removeAsbItem">
          <!-- temporaryselection   personnelUnit.nogroupselected-->
          <!-- 取消勾选，换成选中
          <el-table-column type="selection" align="center"/>
          -->
          <el-table-column label="已选组合项目" width="120" prop="asbitemName" />
          <el-table-column label="标准价格" prop="standardPrice" width="70" align="center" />
          <el-table-column label="折扣" prop="discount" width="60">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.discount" size="small" @input="changeDiscount(scope.$index)"
                @blur="onSubmit('')" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="amount" width="50">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.amount" size="small" @blur="onSubmit('')" />
            </template>
          </el-table-column>
          <el-table-column label="实收价格" prop="chargePrice" width="70">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.chargePrice" size="small"
                @input="changePrice(scope.$index)" @blur="onSubmit('')" />
            </template>
          </el-table-column>
          <el-table-column prop="total" label="金额" width="70" v-if="false" />
          <el-table-column prop="standardPrice" label="标准金额" width="70" v-if="false" />
          <el-table-column label="支付方式" prop="payTypeFlag" width="100">
            <template slot-scope="scope">
              <el-select v-model="scope.row.payTypeFlag" size="small">
                <el-option v-for="item in dict.payType" :key="item.id" :label="item.displayName" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="isCharge" label="收费" width="50" align="center">
            <template slot-scope="scope">
              <el-checkbox :value="scope.row.isCharge == 'Y'" />
            </template>
          </el-table-column>
          <el-table-column prop="checkCompleteFlag" label="状态" align="center">
            <template slot-scope="scope">
              <div>{{ ldddw(dict.checkCompleteFlag, "id", scope.row.checkCompleteFlag, "displayName") }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="isLock" label="锁" width="50" align="center">
            <template slot-scope="scope">
              <el-checkbox :value="scope.row.isLock == 'Y'" />
            </template>
          </el-table-column>
          <el-table-column prop="creatorName" label="登记人" align="center"></el-table-column>
          <el-table-column prop="creationTime" label="登记日期" width="90" align="center">
            <template slot-scope="scope">
              <div>{{ lmoment(scope.row.creationTime, 'yyyy-MM-DD') }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import moment from 'moment';
import { mapState, mapActions } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { arrayFilter, arrayReduce, arrayExistObj, dddw, deepCopy} from "../../utlis/proFunc";
export default {
  props: ["patientRegisterForm","payTypeFlag"],
  data() {
    return {
      itemType: [], //项目类别
      itemTypeIds: '', //被选中的项目类别ID
      asbItemChoosed: [], //勾选的  未选组合项目
      startPoint:-1,

      //patientRegisterAbs:[],         //体检人员所选组合项目 放vuex
      patientRegisterAbsChoosed: [], //勾选的 体检人员所选组合项目
      PstartPoint:-1,
      //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
      // }, //单个添加的组合项目

      asbItemId: '',
      discount: 100,
      total: 0,
      totalStand: 0,
      quickAsb: [],
      totalFoucs: false,    //总价是否获取焦点
      discountFoucs: false, //总折扣是否获取焦点
    };
  },
  computed: {
    ...mapState(["window", "dict", "customerOrg", "patientRegister", "personnelUnit"]),
  },

  mounted() { 
    // if(this.patientRegisterForm.id){
    //   this.getPatientRegisterAbs(this.patientRegisterForm.id)
    // }else{
    //   this.getPatientRegisterAbs()
    // }
  },

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

    ldddw(arrayData, key, value, display) {
      return dddw(arrayData, key, value, display);
    },

    lmoment(date, forMat) {
      return moment(new Date(date)).format(forMat);
    },

    tableRowClassName({row, rowIndex}){
      //console.log(row)
      if (row.choosed) {
        return 'current-row';
      } else {
        if (row.groupPackageId) {
          //console.log('row.groupPackageId',row.groupPackageId)
          return 'purple-row'; //分组或套餐
        }else{
          return '';
        }  
      }          
    },

    handleRowClassName({ row, rowIndex }) {
      // highLightBg 为 'selected'的高亮 
      //console.log(rowIndex, row)
      //return row.highLightBg == 'selected' ? 'high-light-bg' : '';
      if (row.choosed) {
        return 'current-row';
      } else {
        return '';
      }

    },

    //选择 未选的组合项目
    chooseAsbItem(row){
      this.dict.asbItem.forEach((e,index) => {
        e.index = index; 
        return e
      });
      // 按住了shift键
      if (this.window.shift) {         
        //清除所有选择
        this.dict.asbItem.forEach(e => {
          e.choosed = false;  
          return e
        });

        if (this.startPoint == - 1) {
          this.dict.asbItem[row.index].choosed = true;
          this.startPoint = row.index;
          return
        }

        if (this.startPoint > row.index) {
          for (let i = row.index; i <= this.startPoint; i++) {
            this.dict.asbItem[i].choosed = true
          }
        } else if (this.startPoint <= row.index) {
          for (let i = this.startPoint; i <= row.index; i++) {
            this.dict.asbItem[i].choosed = true
          }
        }
        return
      }

      // 按住了ctrl 键
      if (this.window.ctrl) {   
        console.log('this.window.ctrl',this.window.ctrl,this.dict.asbItem)      
        this.dict.asbItem[row.index].choosed = true;
        this.startPoint = row.index;
        return        
      }

      // 未按住了ctrl 、shift 键
      //清除所有选择
      //console.log('清除所有选择')
      this.dict.asbItem.forEach(e => {
        e.choosed = false;  
        return e
      });
      this.dict.asbItem[row.index].choosed = true;
      this.startPoint = row.index;   

    },

    //选择 已选的组合项目
    removeAsbItem(row){
      this.patientRegister.patientRegisterAbs.forEach((e,index) => {
        e.index = index; 
        return e
      });
      // 按住了shift键
      if (this.window.shift) {         
        //清除所有选择
        this.patientRegister.patientRegisterAbs.forEach(e => {
          e.choosed = false;  
          return e
        });

        if (this.PstartPoint == - 1) {
          this.patientRegister.patientRegisterAbs[row.index].choosed = true;
          this.PstartPoint = row.index;
          return
        }

        if (this.PstartPoint > row.index) {
          for (let i = row.index; i <= this.PstartPoint; i++) {
            this.patientRegister.patientRegisterAbs[i].choosed = true
          }
        } else if (this.PstartPoint <= row.index) {
          for (let i = this.PstartPoint; i <= row.index; i++) {
            this.patientRegister.patientRegisterAbs[i].choosed = true
          }
        }
        return
      }

      // 按住了ctrl 键
      if (this.window.ctrl) {   
        console.log('this.window.ctrl',this.window.ctrl,this.patientRegister.patientRegisterAbs)      
        this.patientRegister.patientRegisterAbs[row.index].choosed = true;
        this.PstartPoint = row.index;
        return        
      }

      // 未按住了ctrl 、shift 键
      //清除所有选择
      //console.log('清除所有选择')
      this.patientRegister.patientRegisterAbs.forEach(e => {
        e.choosed = false;  
        return e
      });
      this.patientRegister.patientRegisterAbs[row.index].choosed = true;
      this.PstartPoint = row.index;   

    },

    //保存按钮
    // [
    //   {
    //     "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)
      await postapi(`/api/app/registerasbitem/updatemany`, body)
        .then((res) => {
          console.log("batchEditAsb", 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) {
        //this.$message.warning("请先保存人员体检基本信息！")
        return
      }
      if (this.patientRegister.patientRegisterAbs.length < 1) {
        //this.$message.warning("暂无可操作的数据")
        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);
      //console.log('111111', msg, body.length, body, insBody.length, insBody);
      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);
    },

    //批量添加组合项目    
    async batchAddAsb(registerAsbitems, msg) {
      let body = {
        organizationUnitId:this.patientRegisterForm.organizationUnitId,
        registerAsbitems
      }

      if(this.patientRegisterForm.organizationUnitId.id){
        body.isAutoMerger = 'N'
      }
      //console.log(`/api/app/registerasbitem/createregisterasbitemmany`, body)
      await postapi('/api/app/registerasbitem/createregisterasbitemmany', 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'
    async addAbs(asbItemChoosed,oprType) {
      let body = []
      let checked = true
      let payTypeFlag = '0' //默认个人支付
      let lfind = -1

      //勾选时不需要此操作  start
      if(oprType && oprType == 'all'){
        asbItemChoosed = deepCopy(this.dict.asbItem)
      }else if(oprType && oprType == 'choosed'){
        asbItemChoosed = [] 
        this.dict.asbItem.forEach(e =>{
          if(e.choosed){
            asbItemChoosed.push(e)
            e.choosed = false
          }
        })
      }
      //勾选时不需要此操作  end 

      if (asbItemChoosed.length < 1) {
        this.$message.warning("请选择要添加的组合项目")
        return
      }

      //性别、年龄判断 
      // "displayName": "身高体重",
      //   "shortName": "哈f哈",
      //   "forSexId": "F",
      //   "itemTypeId": "3a0b16de-75b9-c910-c61b-844709a88940",
      //   "price": 0,
      console.log('asbItemChoosed.length', asbItemChoosed.length)
      for (let i = 0; i < asbItemChoosed.length; i++) {
        if (this.patientRegisterForm.sexId == 'U') break //未选性别时，无需判断组合项目性别限制
        if (asbItemChoosed[i].forSexId == 'A') continue
        if (asbItemChoosed[i].forSexId != this.patientRegisterForm.sexId) {
          this.$message.warning(`所选项目：${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 < asbItemChoosed.length; i++) {
        let pojo = {
          asbitemId: asbItemChoosed[i].id,
          patientRegisterId: this.patientRegisterForm.id,
          standardPrice: asbItemChoosed[i].price,
          chargePrice: asbItemChoosed[i].price,
          payTypeFlag,
          isCharge: "N",
          amount: 1,
          total: asbItemChoosed[i].price,
        }
        body.push(pojo)
        this.patientRegister.patientRegisterAbs.push({ ...pojo, asbitemName: asbItemChoosed[i].displayName })
        lfind = arrayExistObj(this.dict.asbItem, 'id', asbItemChoosed[i].id)
        if (lfind > -1) this.dict.asbItem.splice(lfind, 1)

        lfind = arrayExistObj(this.dict.asbItemQuick, 'id', asbItemChoosed[i].id)
        if (lfind > -1) this.dict.asbItemQuick.splice(lfind, 1)

      }

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

    },

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

    //批量删除组合项目
    async batchDelAsb(body, msg) {
      console.log(`/api/app/registerasbitem/deletemany`, body)
      await 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(absForDel,oprType) {
      let body = {}
      let registerAsbitemIds = []
      let chargeComplete = ''
      let lfind = -1

      //勾选时不需要此操作  start
      if(oprType && oprType == 'all'){
        absForDel = deepCopy(this.patientRegister.patientRegisterAbs)
      }else if(oprType && oprType == 'choosed'){
        absForDel = [] 
        this.patientRegister.patientRegisterAbs.forEach(e =>{
          if(e.choosed){
            absForDel.push(e)
            e.choosed = false
          }
        })
      }
      //勾选时不需要此操作  end 

      if (absForDel.length < 1) {
        this.$message.warning("请选择要移除的组合项目")
        return
      }

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

          absForDel.splice(i, 1)
          i--
          continue
        }

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

      //刷新
      this.getAsbItemByItemType()

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

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

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

    },

    //双击删除已选项目
    removeAbs(row) {
      this.delAbs([row]);
    },

    //项目类别过滤 组合项目，未过滤已选择的组合项目
    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)
      this.dict.asbItemQuick = [...this.dict.asbItemAll];

    },

    //按项目类别显示组合项目，并过滤已选择的组合项目
    getAsbItemByItemType() {
      this.getAsbItemByItemTypeAll()
      //刷新显示 未选组合项目
      arrayReduce(this.dict.asbItem, [...this.patientRegister.patientRegisterAbs], "id=asbitemId");
      arrayReduce(this.dict.asbItemQuick, [...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) {
    //       //未选项目中移除，已选项中添加
    //     }
    //   });
    // },

    //选中分组所包含的组合项目
    // async 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);
    //       }
    //     });
    // },

    //选中 套餐/分组 所包含的组合项目
    getGroupPackageAsb(typeFlag, groupPackageId) {
      let delBody = {};
      let url = typeFlag == 'group' ?
        '/api/app/customer-org-group-detail/customer-org-group-detail-in-asbitem/'
        : '/api/app/medical-package-detail/medical-package-in-asbitem?MedicalPackageId=';
      let msg = typeFlag == 'group' ? '更换分组' : '更换套餐';

      console.log(`${url}${groupPackageId}`);
      getapi(`${url}${groupPackageId}`)
        .then((res) => {
          console.log("getGroupPackageAsb", res);
          if (res.code != -1) {
            //this.patientRegister.medicalPackageAsb = res.data;
            //return this.promiseRemoveGroupPackageAsb();

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

            //添加或更新已选组合项目
            this.addGroupPackageAsb(res.data, groupPackageId);
            //console.log('delBody', delBody,delBody['registerAsbitemIds'].length);
            if (delBody['registerAsbitemIds'].length > 0) {
              return postapi(`/api/app/registerasbitem/deletemany`, delBody)
            } else {
              this.onSubmit(msg);
            }
          }
        })
        .then(res => {
          //console.log('res', res);
          if (res && res.code != -1) {
            //添加新套餐的组合项目
            this.onSubmit(msg);
          }
        });
    },

    //添加新套餐/分组的组合项目
    addGroupPackageAsb(groupPackageAsb, groupPackageId) {

      let payTypeFlag = '0';  //默认个人支付
      let lfind = -1


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

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

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

      //删除已选 分组或套餐的组合项目 ，如已收费或 已检时，将 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 };

      return body;

    },

    //双击选择组合项目
    dbClickChoosedAsb(row) {
      this.addAbs([row]);
    },
    //快速选择组合项目
    quickChoosedAsb(v) {
      //远程查询时，设置了 value-key 也不管用，只能取到value console.log('quickChoosedAsb',v)
      let lfind = -1
      if (v) {
        lfind = arrayExistObj(this.dict.asbItemQuick, 'id', v)
        if (lfind > -1) {
          this.addAbs([this.dict.asbItemQuick[lfind]])
        }
      }    

    },

    // quickChoosedAsb(v){
    //   let lfind = -1
    //   let asbItemChoosed = []

    //   console.log('quickChoosedAsb',v,this.dict.asbItemQuick)
    //   if(v){
    //     lfind = arrayExistObj(this.dict.asbItemQuick,'id',v)
    //     if(lfind > -1){
    //       asbItemChoosed.push(this.dict.asbItemQuick[lfind])       
    //       this.addAbs(asbItemChoosed)   
    //     }             
    //   }      
    // },   

    //快速选择组合项目时，调整可按拼间简码及简称查找
    remoteMethod(keyWords) {
      //console.log('remoteMethod',this.dict.asbItemQuick)  
      if (keyWords) {
        this.quickAsb = [];
        this.dict.asbItemQuick.forEach(item => {
          if (item.displayName.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
            || item.simpleCode.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
            || item.shortName.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1) {
            this.quickAsb.push(item);
          }
        });
      } else {
        this.quickAsb = [...this.dict.asbItemQuick];
      }
    },

    //修改总折扣
    changeAllDiscount() {

      if (!this.discount || this.discount == 0) return
      if (!this.patientRegister.patientRegisterAbs || this.patientRegister.patientRegisterAbs.length == 0) return

      this.patientRegister.patientRegisterAbs.forEach(e => {
        e.discount = this.discount
        e.chargePrice = (e.standardPrice * this.discount / 100).toFixed(2)
        e.total = (e.standardPrice * this.discount * e.amount / 100).toFixed(2)
        return e
      });
      this.onSubmit('')

    },

    //修改总金额
    changeTotal() {

      if (!this.total) return
      if (!this.patientRegister.patientRegisterAbs || this.patientRegister.patientRegisterAbs.length == 0) return

      let sumChargeDetails = 0 //单个标准价折后价 合计总计 
      let qtyIsOneLast = 0   //数量为1的最后行项目，用于返写金额


      this.discount = (100 * this.total / this.totalStand).toFixed(2)

      this.patientRegister.patientRegisterAbs.forEach((e, index) => {
        if (e.amount == 1) qtyIsOneLast = index
        e.discount = this.discount
        e.chargePrice = (e.standardPrice * this.discount / 100).toFixed(2)
        e.total = (e.standardPrice * this.discount * e.amount / 100).toFixed(2)
        sumChargeDetails += Number((e.standardPrice * this.discount * e.amount / 100).toFixed(2))
        return e
      });
      console.log('this.total - sumChargeDetails', sumChargeDetails, this.total - sumChargeDetails)
      if (this.total != sumChargeDetails) {
        this.patientRegister.patientRegisterAbs[qtyIsOneLast].chargePrice
          = (Number(this.patientRegister.patientRegisterAbs[qtyIsOneLast].chargePrice)
            + Number((this.total - sumChargeDetails) / this.patientRegister.patientRegisterAbs[qtyIsOneLast].amount)).toFixed(2)
      }
      this.onSubmit('')
    },

    //修改数量
    changeDiscount(index) {
      //console.log('index',index)
      if (!this.patientRegister.patientRegisterAbs || this.patientRegister.patientRegisterAbs.length == 0) return
      if (!this.patientRegister.patientRegisterAbs[index].discount) return
      //console.log(this.patientRegister.patientRegisterAbs[index].chargePrice,this.patientRegister.patientRegisterAbs[index].standardPrice)
      this.patientRegister.patientRegisterAbs[index].chargePrice = Number(this.patientRegister.patientRegisterAbs[index].standardPrice * this.patientRegister.patientRegisterAbs[index].discount / 100).toFixed(2)
      this.onSubmit('')
    },

    //修改单价
    changePrice(index) {
      //console.log('index',index)
      if (!this.patientRegister.patientRegisterAbs || this.patientRegister.patientRegisterAbs.length == 0) return
      if (!this.patientRegister.patientRegisterAbs[index].chargePrice) return
      //console.log(this.patientRegister.patientRegisterAbs[index].chargePrice,this.patientRegister.patientRegisterAbs[index].standardPrice)
      this.patientRegister.patientRegisterAbs[index].discount = Number(this.patientRegister.patientRegisterAbs[index].chargePrice * 100 / this.patientRegister.patientRegisterAbs[index].standardPrice).toFixed(2)
      this.onSubmit('')
    },

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

        //不合计的列
        if (sumCol.indexOf(index) == -1) {
          sums[index] = '';
          return;
        }

        sums[index] = 0
        data.forEach(e => {
          if (!isNaN(e[column.property])) sums[index] += e[column.property] * e['amount']
        })
        sums[index] = sums[index].toFixed(2) //+ ' 元';

        // 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;  //原始
        //       return prev + curr;  //改造
        //     } else {
        //       return prev;
        //     }
        //   }, 0);
        //   sums[index] = sums[index].toFixed(2) + ' 元';
        // } else {
        //   sums[index] = 'N/A';
        // }

      });
      this.totalStand = sums[2];
      //console.log('this.totalFoucs/this.discountFoucs',this.totalFoucs,this.discountFoucs)
      if (!this.totalFoucs) this.total = sums[5];
      if (!this.discountFoucs) this.discount = Number(this.total * 100 / this.totalStand).toFixed(2);
      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);
        this.getGroupPackageAsb('group', 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);
        this.getGroupPackageAsb('medical', this.patientRegisterForm.medicalPackageId);
      }
    },

    //体检信息保存，触发已选组合项目保存
    "patientRegister.saveTimes"(newVal, oldVal) {
      console.log("patientRegister.saveTimes newVal：", newVal, " oldVal：", oldVal);
      if (newVal != oldVal) {
        this.onSubmit('');
      }
    },

    //快速选择完后，重新将光标定位到 asbItemId
    "asbItemId"(newVal, oldVal) {
      if (newVal != oldVal && newVal != '') {
        //重新定位光标
        this.$nextTick(() => {
          console.log("1this.$refs['asbItemId'].focus()");
          this.$refs['asbItemId'].focus(); //total  asbItemId
          console.log("2this.$refs['asbItemId'].focus()");
        });
      }
    },

    // 在人员列表处已 getPatientRegisterAbs ，此处无需再监听
    // "patientRegisterForm.id"(newVal, oldVal) {
    //   if (newVal && newVal != oldVal) {
    //     this.getPatientRegisterAbs(newVal)
    //   }
    // },

    //按钮更新支付方式
    "payTypeFlag"(newVal, oldVal) {
      if (newVal != oldVal && newVal != '') {
        this.patientRegister.patientRegisterAbs.forEach(e =>{
          e.payTypeFlag = newVal;
          return e;
        });
        this.onSubmit('调整支付方式');
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../assets/css/global.css";

.mainareaBox {
  border: 1px solid #000;
  height: v-bind("(window.pageHeight > 720 ? (window.pageHeight - 460) : 260) + 'px'");
  margin-top: 5px;
}

.btnList {
  margin-top: 5px;
  margin-left: 5px;
  margin-right: 5px;
}

.disTotal {
  margin-left: 10px;
}

::v-deep .el-input__inner {
  /*text-align: center;*/
  padding-left: 1px;
  padding-right: 1px;
  /*background-color: rgb(255, 0, 255);*/
}

::v-deep .el-table th.el-table__cell {
  /*text-align: center;*/
  padding-left: 2px;
  padding-right: 2px;
}

::v-deep .el-table td.el-table__cell {
  padding-left: 2px;
  padding-right: 2px;
}

::v-deep .el-table .cell {
  padding-left: 2px;
  padding-right: 2px;
}

::v-deep input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none !important;
  margin: 0 !important;
}

</style>

