<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" popper-class="example" style="margin-left: 3px;width:160px;"
          :props="{ checkStrictly: true, expandTrigger: 'hover', ...customerOrg.treeprops, }"
          clearable filterable @change="changeItemType" size="small" :disabled="isComplete">
        </el-cascader>
      </div>
      <div class="mainareaBox">
        <el-table :data="asbItem" style="border-radius: 5px;"
          :height="(window.pageHeight > 700 ? (window.pageHeight - 440) : 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 v-show="checkPagePriv(pagePriv.privs,'添加')" class="btnList">
        <el-button class="commonbutton" @click="addAbs(asbItemChoosed,'choosed')" style="width:90px;" :disabled="isComplete">添加 <i class="el-icon-arrow-right"></i>
        </el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs,'全添加')" class="btnList">
        <el-button type="success" class="difference" @click="addAbs(asbItemChoosed,'all')" style="width:90px;" :disabled="isComplete">全添加 <i class="el-icon-d-arrow-right"></i>
        </el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs,'移除')" class="btnList">
        <el-button type="warning" class="commonbutton" @click="delAbs(patientRegisterAbsChoosed,'choosed')" style="width:90px;" :disabled="isComplete"><i class="el-icon-arrow-left"> 移除</i>
        </el-button>
      </div>
      <div v-show="checkPagePriv(pagePriv.privs,'全移除')" class="btnList">
        <el-button type="danger" class="difference" @click="delAbs(patientRegisterAbsChoosed,'all')" style="width:90px;" :disabled="isComplete"><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 - 110 - 20 - 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 :filter-method="filterMethod" :disabled="isComplete"
            clearable @clear="quickAsb = deepCopy(asbItemQuick)" 
            @change="quickChoosedAsb" default-first-option ref="quickAsbOCX"
            style="width:240px;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="prAsb" highlight-current-row border ref="patientRegister_patientRegisterAbs" style="border-radius: 5px;"
          :height="(window.pageHeight > 700 ? (window.pageHeight - 440) : 260)" width="100%" :summary-method="getSummaries"
          show-summary :row-class-name="handleRowClassName" @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="已选组合项目" min-width="120" prop="asbitemName" >
            <template slot-scope="scope">
              <div>
                <el-tooltip class="item" effect="dark" content="标五角星表示属于分组或套餐的项目" placement="top">
                  <i v-if="scope.row.groupPackageId" class="el-icon-star-on" style="font-size: 14px;color: purple;"></i>
                </el-tooltip>
                {{ scope.row.asbitemName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="标准价格" prop="standardPrice" min-width="70" align="center" />
          <el-table-column label="折扣" prop="discount" min-width="60">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.discount" size="small" @input="changeDiscount(scope.$index)" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="amount" min-width="50">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.amount" size="small" @input="changeDiscount(scope.$index)" />
            </template>
          </el-table-column>
          <el-table-column label="实收价格" prop="chargePrice" min-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="金额" min-width="70" align="center"/>
          <el-table-column prop="standardPrice" label="标准金额" min-width="70" v-if="false" />
          <el-table-column label="支付方式" prop="payTypeFlag" min-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="收费" min-width="40" align="center">
            <template slot-scope="scope">
              <el-checkbox :value="scope.row.isCharge == 'Y'" />
            </template>
          </el-table-column>
          <el-table-column prop="checkCompleteFlag" label="状态" min-width="40" align="center">
            <template slot-scope="scope">
              <div>{{ dddw(dict.checkCompleteFlag, "id", scope.row.checkCompleteFlag, "displayName") }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="isLock" label="锁" min-width="40" align="center">
            <template slot-scope="scope">
              <el-checkbox :value="scope.row.isLock == 'Y'" />
            </template>
          </el-table-column>
          <el-table-column prop="creatorName" label="登记人" min-width="70" align="center"></el-table-column>
          <el-table-column prop="creationTime" label="登记日期" win-width="90" align="center">
            <template slot-scope="scope">
              <div>{{ scope.row.creationTime ? moment(scope.row.creationTime).format('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 { getPagePriv,checkPagePriv, arrayFilter, arrayReduce, arrayExistObj, dddw, deepCopy, tcdate} from "../../utlis/proFunc";
import proApi from "../../utlis/proApi";

export default {
  props: ["prForm","prAsbOpraOpts","triggerHeadSave","refreshFormId"],
  data() {
    return {
      pagePriv:{
        routeUrlorPageName:'PatientRegisterEdit', //当前页面归属路由或归属页面权限名称
        privs:[] // 页面权限
      },
      oldFormId:'',     //配合登记人员复制新增使用
      itemType: [],     //项目类别
      itemTypeIds: '', //被选中的项目类别ID
      asbItem:[],      //左侧显示的未选组合项目
      asbItemAll:[],   //所有未选组合项目

      asbItemChoosed: [], //勾选的  未选组合项目
      startPoint:-1,

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


      prAsb:[],  //当前显示的已选组合项目（新增与编辑的在一起）
      prAsbDels:[], //待提交 删除的组合项目

      groupAsbs:[],   //分组包含的项目
      packageAsbs:[], //套餐包含的项目
   

      asbItemId: '',
      discount: 100,
      total: 0,
      totalStand: 0,
      quickAsb: [],
      asbItemQuick:[],
      totalFoucs: false,    //总价是否获取焦点
      discountFoucs: false, //总折扣是否获取焦点
    };
  },
  computed: {
    ...mapState(["window", "dataTransOpts", "dict", "customerOrg", "patientRegister", "personnelUnit"]),
    //是否总检
    isComplete(){
      return this.prForm.completeFlag == '3' ? true:false;
    },

  },

  created(){
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if(userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))

    this.dictInit()    
  },

  updated(){
    this.$nextTick(() => {
      this.$refs['patientRegister_patientRegisterAbs'].doLayout()
    })
  },
  mounted() { 
    
  },

  methods: {
    ...mapActions(['getCustomerOrgGroup', 'getPatientRegisterAbs']),
    dddw,moment,deepCopy,checkPagePriv,

    // 初始化字典信息
    dictInit(){
      
      // 项目类别 树结构
      getapi("/api/app/item-type/by-code-all").then((res) => {
        if (res.code != -1) {
          this.dict.itemTypeTree = res.data;
          tcdate(this.dict.itemTypeTree);
        }
      });

      // 获取组合项目
      postapi('/api/app/asbitem/GetBasicList',{isFilterActive:'Y'}).then(res =>{
        if(res.code != -1){
          this.asbItem = res.data
          this.asbItemAll = res.data
          this.asbItemQuick = res.data
          this.quickAsb = res.data
        }
      });
    },

    // 获取人员组合项目信息
    async getPrAsb(id){
      // debugger
      // 清空待删除、分组、套餐
      console.log('getPrAsb(id)',`getPrAsb(${id})`)
      this.prAsbDels = []
      this.groupAsbs = []
      this.packageAsbs = []

      let result = await proApi.getPrAsb(id)
      this.prAsb = result.data
      this.refreshAsbitem()  
    },

    // 复制新增 拷贝明细项目
    async copyNew(){
      if(this.oldFormId){
        let result = await proApi.getPrAsb(this.oldFormId)
        this.prAsb = result.data
        this.prAsb.forEach(e => {
          e.id = '';
          e.patientRegisterId = '';
          e.isCharge = 'N';
          e.checkCompleteFlag = '0'
          e.isLock = 'N'
        })
        this.refreshAsbitem()
      }
    },

    // 刷新未选组合项目
    refreshAsbitem(){
      let asbItemAll = deepCopy(this.asbItemAll)
      let choosedAsb = this.prAsb.filter(e => {
        return e.checkCompleteFlag == '0' || !(e.checkCompleteFlag)
      }) // 如果已经检查，则可以重新选进来（复查）

      arrayReduce(asbItemAll, choosedAsb, "id=asbitemId");
      this.changeItemType();       
      this.asbItemQuick = deepCopy(asbItemAll);      
      this.quickAsb = deepCopy(asbItemAll);
    },
    
    handleRowClassName({ row, rowIndex }) {
      if (row.choosed) {
        return 'current-row';
      } else {
        return '';
      }
    },

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

        if (this.startPoint == - 1) {
          this.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.asbItem[i].choosed = true
          }
        } else if (this.startPoint <= row.index) {
          for (let i = this.startPoint; i <= row.index; i++) {
            this.asbItem[i].choosed = true
          }
        }
        return
      }

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

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

    },

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

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

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

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

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

    },

    //更新所选组合项目
    async onSubmit(msg) {
      let ret = false

      ret = await this.batchAddAsb()
      if(!ret){
        if(msg) this.$message.warning(`组合项目 ${msg} 失败！`)
        return
      }

      ret = await this.batchDelAsb()
      if(!ret){
        if(msg) this.$message.warning(`组合项目 ${msg} 失败！`)
        return
      }

      ret = await this.batchEditAsb()
      if(!ret){
        if(msg) this.$message.warning(`组合项目 ${msg} 失败！`)
        return
      }
      
      console.log('this.prAsbOpraOpts.formId',this.prAsbOpraOpts.formId)
      if(this.prAsbOpraOpts.formId){
        this.refreshFormId()        
      }else{ 
        //触发保存人员基本信息        
        this.triggerHeadSave()
        this.getPrAsb(this.prForm.id)
      }
    },

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

    

    // 添加组合项目
    ///api/app/register-asbitem/many/3fa85f64-5717-4562-b3fc-2c963f66afa6'
    addAbs(asbItemChoosed,oprType) {      
      let checked = true
      let payTypeFlag = '0' //默认个人支付
      

      //勾选时不需要此操作  start
      if(oprType && oprType == 'all'){
        asbItemChoosed = deepCopy(this.asbItem)
      }else if(oprType && oprType == 'choosed'){
        asbItemChoosed = [] 
        this.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.prForm.sexId == 'U') break //未选性别时，无需判断组合项目性别限制
        if (asbItemChoosed[i].forSexId == 'A') continue
        if (asbItemChoosed[i].forSexId != this.prForm.sexId) {
          this.$message.warning(`所选项目：${asbItemChoosed[i].displayName}，不适合当前人员性别`)
          checked = false
          break
        }
      }
      //console.log(222,checked)
      if (!checked) return

      if (this.prForm.customerOrgId != this.dict.personOrgId) payTypeFlag = '1'
      for (let i = 0; i < asbItemChoosed.length; i++) {
        let pojo = {
          asbitemId: asbItemChoosed[i].id,
          asbitemName: asbItemChoosed[i].displayName,
          patientRegisterId: this.prForm.id,
          standardPrice: asbItemChoosed[i].price,
          chargePrice: asbItemChoosed[i].price,
          payTypeFlag,
          isCharge: "N",
          checkCompleteFlag:'0',
          discount:100,
          amount: 1,
          total: asbItemChoosed[i].price,
        }        
        this.prAsb.push(pojo)
      }

      this.refreshAsbitem()

    },

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

    //批量提交添加组合项目
    async batchAddAsb() {
      let ret = false
      let patientRegisterId = this.prForm.id || this.prAsbOpraOpts.formId
      if(!patientRegisterId){
        this.$message.warning("人员基本信息未保存");
        return ret
      }

      let registerAsbitems = []

      this.prAsb.forEach(e => {
        if(!e.id){
          registerAsbitems.push({
            asbitemId: e.asbitemId,
            patientRegisterId,
            standardPrice: e.standardPrice,
            chargePrice: e.chargePrice,
            payTypeFlag: e.payTypeFlag,
            isCharge: e.isCharge,
            amount: e.amount,
            groupPackageId: e.groupPackageId
          })
        }
      })

      if(registerAsbitems.length == 0) return true

      let body = {
        organizationUnitId:this.prForm.organizationUnitId,
        registerAsbitems,
        isAutoMerger:'Y'
      }

      try {
        let res = await postapi('/api/app/registerasbitem/createregisterasbitemmany', body)
        if(res.code != -1) ret = true
      } catch (error) {
        console.log('批量添加组合项目失败',error)
      }

      return ret
      
    },

    //批量提交更新组合项目
    async batchEditAsb() {
      let ret = false
      let body = []


      this.prAsb.forEach(e => {
        if(e.id){
          body.push({
            registerAsbitemId:e.id,
            input: {
              chargePrice: e.chargePrice,
              payTypeFlag: e.payTypeFlag,
              isCharge: e.isCharge,
              amount: e.amount,
              groupPackageId: e.groupPackageId
            }
          })          
        }
      })
      if(body.length == 0) return true

      try {
        let res = await postapi(`/api/app/registerasbitem/updatemany`, body)
        if(res.code != -1) ret = true
      } catch (error) {
        console.log('批量提交更新组合项目失败',error)
      }
      return ret
    },

    //批量提交删除组合项目
    async batchDelAsb() {
      let ret = false
      if(this.prAsbDels.length == 0) return true

      let registerAsbitemIds=[]

      this.prAsbDels.forEach(e => {
        registerAsbitemIds.push(e.id)
      })

      console.log(`/api/app/registerasbitem/deletemany`, {registerAsbitemIds})

      try {
        let res = await postapi(`/api/app/registerasbitem/deletemany`, {registerAsbitemIds})
        if(res.code != -1) ret = true
      } catch (error) {
        console.log('批量删除组合项目失败',error)
      }

      return ret
    },

    //删除 人员已选中的组合项目
    ///api/app/register-asbitem/many?RegisterAsbitemIds=3fa85f64-5717-4562-b3fc-2c963f66afa6
    delAbs(absForDel,oprType) {      
      let chargeComplete = ''
      let lfind = -1
      let tempRd = {}

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

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

      absForDel.forEach(e => {
        // 如果已经收费 或 体检，则不允许删除
        if (e.isCharge == 'Y' || (e.checkCompleteFlag && e.checkCompleteFlag != '0')) {
          chargeComplete += e.asbitemName + '，'   
        }else{
          lfind = arrayExistObj(this.prAsb, 'asbitemId', e.asbitemId)
          if(lfind > -1){
            tempRd = Object.assign({},this.prAsb.splice(lfind,1)[0])
            if(e.id) this.prAsbDels.push(tempRd)
          }    
        }            
      })

      //刷新
      this.refreshAsbitem()

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

    },

    //双击删除已选项目
    removeAbs(row) {
      if(this.isComplete){
        this.$message.info('人员已总检，不可 添加/删除 组合项目')
        return
      } 
      this.delAbs([row]);
    },

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

      if (lv) {
        this.asbItem = arrayFilter(asbItemAll, "itemTypeId", lv);
      } else {
        this.asbItem = deepCopy(asbItemAll);
      }
      arrayReduce(this.asbItem, this.prAsb, "id=asbitemId");
    },

     

    //选中 分组 所包含的组合项目
    getGroupAsbs(id){
      if(!id){
        this.groupAsbs = []
        this.changeGroup(id)
        return
      }
      
      getapi(`/api/app/customerorggroupdetail/getcustomerorggroupdetailinasbitem?CustomerOrgGroupId=${id}`)
      .then((res) => {
        if(res.code != -1){          
          this.groupAsbs = res.data
          this.changeGroup(id)
        }
      });
      
    },

    //选中 套餐 所包含的组合项目
    getPackageAsbs(id){
      if(!id){
        this.packageAsbs = []
        this.changePackage(id)
        return
      }

      postapi('/api/app/medicalpackagedetail/getmedicalpackageinasbitem',{medicalPackageId:id})
      .then((res) => {
        if(res.code != -1){
          this.packageAsbs = res.data
          this.changePackage(id)
        }
      });
    },

    // 更换分组 
    changeGroup(newId){
      //已收费项目，不更改收费方式、价格及数量，只更改分组id
      let payTypeFlag = '0'
      let lfind = -1
      let tempRd = {}

      if(!newId){
        this.setGroupPackageNull()
        return
      }

      if (this.prForm.customerOrgId != this.dict.personOrgId) payTypeFlag = '1'  //单位支付

      for(let i = this.prAsb.length - 1;i>-1;i--){
        lfind = arrayExistObj(this.groupAsbs,'asbitemId',this.prAsb[i].asbitemId)
        if(lfind > -1){
          //找到了则更新此项目
          tempRd = Object.assign({},this.groupAsbs.splice(lfind,1)[0])
          this.prAsb[i].groupPackageId = newId
          if(this.prAsb[i].isCharge != 'Y'){
            this.prAsb[i].payTypeFlag = payTypeFlag
            this.prAsb[i].amount = tempRd.customerOrgGroupDetailAmount
            this.prAsb[i].standardPrice = tempRd.price            
            this.prAsb[i].chargePrice = tempRd.customerOrgGroupDetailPrice
            this.prAsb[i].discount = tempRd.discount
          }
        }else{
          //没找到则移除此项目
          if(this.prAsb[i].isCharge == 'Y' || (this.prAsb[i].checkCompleteFlag && this.prAsb[i].checkCompleteFlag != '0')){
            this.prAsb[i].groupPackageId = null
          }else{
            tempRd = Object.assign({},this.prAsb.splice(i,1)[0])
            if(tempRd.id) this.prAsbDels.push(tempRd)
          }
        }
      }

      // debugger
      //未找到则添加(如果在待删除中找到记录，则待删除中记录移至当前显示记录中来)
      this.groupAsbs.forEach(e =>{
        lfind = arrayExistObj(this.prAsbDels,'asbitemId',e.asbitemId)
        if(lfind > -1){
          tempRd = Object.assign(this.prAsbDels.splice(lfind,1)[0],
            {
              groupPackageId:newId,
              standardPrice:e.price,
              chargePrice:e.customerOrgGroupDetailPrice,
              payTypeFlag,
              isCharge: "N",
              discount:e.discount,
              amount:e.customerOrgGroupDetailAmount,
              total: Math.round(e.customerOrgGroupDetailAmount * e.customerOrgGroupDetailPrice * 100)/100
            }
          )
        }else{
          tempRd = {  
            groupPackageId:newId,       
            asbitemId:e.asbitemId,
            asbitemName:e.displayName,
            patientRegisterId:this.prForm.id,
            standardPrice:e.price,
            chargePrice:e.customerOrgGroupDetailPrice,
            payTypeFlag,
            isCharge: "N",
            discount:e.discount,
            amount:e.customerOrgGroupDetailAmount,
            total: Math.round(e.customerOrgGroupDetailAmount * e.customerOrgGroupDetailPrice * 100)/100
          }
        }
        this.prAsb.push(tempRd)
      })

      this.refreshAsbitem()
    },

    // 更换套餐 
    changePackage(newId){
      //已收费项目，不更改收费方式、价格及数量，只更改分组id
      let payTypeFlag = '0'
      let lfind = -1
      let tempRd = {}

      if(!newId){
        this.setGroupPackageNull()
        return
      }

      if (this.prForm.customerOrgId != this.dict.personOrgId) payTypeFlag = '1'  //单位支付

      for(let i = this.prAsb.length - 1;i>-1;i--){
        lfind = arrayExistObj(this.packageAsbs,'id',this.prAsb[i].asbitemId)
        if(lfind > -1){
          //找到了则更新此项目
          tempRd = Object.assign({},this.packageAsbs.splice(lfind,1)[0])
          this.prAsb[i].groupPackageId = newId
          if(this.prAsb[i].isCharge != 'Y'){
            this.prAsb[i].payTypeFlag = payTypeFlag
            this.prAsb[i].amount = tempRd.medicalPackageDetailAmount
            this.prAsb[i].standardPrice = tempRd.price            
            this.prAsb[i].chargePrice = tempRd.medicalPackageDetailPrice
            this.prAsb[i].discount = tempRd.discount
          }
        }else{
          //没找到则移除此项目
          if(this.prAsb[i].isCharge == 'Y' || (this.prAsb[i].checkCompleteFlag && this.prAsb[i].checkCompleteFlag != '0')){
            this.prAsb[i].groupPackageId = null
          }else{
            tempRd = Object.assign({},this.prAsb.splice(i,1)[0])
            if(tempRd.id) this.prAsbDels.push(tempRd)
          }
        }
      }

      //未找到则添加(如果在待删除中找到记录，则待删除中记录移至当前显示记录中来)
      this.packageAsbs.forEach(e =>{
        lfind = arrayExistObj(this.prAsbDels,'asbitemId',e.id)
        if(lfind > -1){
          tempRd = Object.assign(this.prAsbDels.splice(lfind,1)[0],
            {
              groupPackageId:newId,
              standardPrice:e.price,
              chargePrice:e.medicalPackageDetailPrice,
              payTypeFlag,
              isCharge: "N",
              discount:e.discount,
              amount:e.medicalPackageDetailAmount,
              total: Math.round(e.medicalPackageDetailAmount * e.medicalPackageDetailPrice * 100)/100
            }
          )
        }else{
          tempRd = {
            groupPackageId:newId,
            asbitemId:e.id,
            asbitemName:e.displayName,
            patientRegisterId:this.prForm.id,
            standardPrice:e.price,
            chargePrice:e.medicalPackageDetailPrice,
            payTypeFlag,
            isCharge: "N",
            discount:e.discount,
            amount:e.medicalPackageDetailAmount,
            total: Math.round(e.medicalPackageDetailAmount * e.medicalPackageDetailPrice * 100)/100
          }
        }
        this.prAsb.push(tempRd)
      })

      this.refreshAsbitem()
    },

    // 从 有分组/套餐 切换成 无分组/套餐 时
    setGroupPackageNull(){
      this.prAsb.forEach(e =>{
        e.groupPackageId = null
      })
    },
   
    //双击选择组合项目
    dbClickChoosedAsb(row) {
      if(this.isComplete){
        this.$message.info('人员已总检，不可 添加/删除 组合项目')
        return
      } 
      this.addAbs([row]);
    },

    //快速选择组合项目
    quickChoosedAsb(v) {
      //远程查询时，设置了 value-key 也不管用，只能取到value console.log('quickChoosedAsb',v)
      let lfind = -1
      if (v) {
        lfind = arrayExistObj(this.asbItemQuick, 'id', v)
        if (lfind > -1) {
          this.addAbs([this.asbItemQuick[lfind]])
        }
      }    
      //this.$refs['quickAsbOCX'].focus(); //asbItemId
      this.$nextTick(() => {        
        this.$refs['quickAsbOCX'].blur(); //total  asbItemId
        this.asbItemId = ''
        this.quickAsb = deepCopy(this.asbItemQuick)        
        this.$refs['quickAsbOCX'].focus(); //total  asbItemId       
      });
      
    },
 

    //快速选择组合项目时，调整可按拼间简码及简称查找
    filterMethod(keyWords) {
      //console.log('filterMethod',this.asbItemQuick)  
      if (keyWords) {
        this.quickAsb = [];
        this.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 = deepCopy(this.asbItemQuick);
      }
    },    

    //修改总折扣
    changeAllDiscount() {

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

      this.prAsb.forEach(e => {
        e.discount = this.discount
        e.chargePrice = Math.round(e.standardPrice * this.discount) / 100
        e.total = Math.round(e.standardPrice * this.discount * e.amount) / 100
      });
      // this.onSubmit('')

    },

    //修改总金额
    changeTotal() {

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

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

      // console.log('this.total / this.totalStand',this.total , this.totalStand)
      this.discount = Math.round((100 * this.total / this.totalStand) * 100)/100

      this.prAsb.forEach((e, index) => {        
        if (e.amount == 1 && e.standardPrice != 0) qtyIsOneLast = index
        e.discount = this.discount
        e.chargePrice = Math.round((e.standardPrice * this.discount / 100) * 100)/100
        e.total = Math.round((e.standardPrice * this.discount * e.amount / 100) * 100)/100
        sumChargeDetails += Math.round((e.standardPrice * this.discount * e.amount / 100) * 100)/100
      });
      console.log('this.prAsb',this.prAsb)

      // console.log('this.total - sumChargeDetails', sumChargeDetails, this.total - sumChargeDetails)
      //平衡金额（按总价折扣后，再根据折扣合计 会出现金额差）
      if (this.total != sumChargeDetails) {
        console.log('qtyIsOneLast',qtyIsOneLast)
        this.prAsb[qtyIsOneLast].total = 
          Math.round((Number(this.prAsb[qtyIsOneLast].total) + Number(this.total) - Number(sumChargeDetails))*100)/100
        this.prAsb[qtyIsOneLast].chargePrice = 
          Math.round(this.prAsb[qtyIsOneLast].total * 100 / this.prAsb[qtyIsOneLast].amount)/100
        if(this.prAsb[qtyIsOneLast].standardPrice != 0){
          this.prAsb[qtyIsOneLast].discount = 
            Math.round(this.prAsb[qtyIsOneLast].chargePrice * 10000/this.prAsb[qtyIsOneLast].standardPrice)/100
        }
      }
      //this.onSubmit('')
    }, 

    //修改数量
    changeDiscount(index) {
      //console.log('index',index)
      if (!this.prAsb || this.prAsb.length == 0) return
      if (!this.prAsb[index].discount) return
      //console.log(this.prAsb[index].chargePrice,this.prAsb[index].standardPrice)
      this.prAsb[index].chargePrice = Math.round(this.prAsb[index].standardPrice * this.prAsb[index].discount)/100
      this.prAsb[index].total = this.prAsb[index].chargePrice * this.prAsb[index].amount
      // this.onSubmit('')
    },

    //修改单价
    changePrice(index) {
      //console.log('index',index)
      if (!this.prAsb || this.prAsb.length == 0) return
      if (!this.prAsb[index].chargePrice) return
      //console.log(this.prAsb[index].chargePrice,this.prAsb[index].standardPrice)
      this.prAsb[index].discount = Math.round(this.prAsb[index].chargePrice * 10000 / this.prAsb[index].standardPrice)/100
      // this.onSubmit('')
    },

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

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

        sums[index] = 0
        data.forEach(e => {
          if (!isNaN(e[column.property])){
            if(index == 1){
              sums[index] += e[column.property] * e['amount']
            }else{
              sums[index] += e[column.property]
            }            
          }
        })
        sums[index] = Math.round(sums[index] * 100)/100 //+ ' 元';

        // 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[1];
      //console.log('this.totalFoucs/this.discountFoucs',this.totalFoucs,this.discountFoucs)
      if (!this.totalFoucs) this.total = sums[5];
      if (!this.discountFoucs) this.discount = Math.round(this.total * 10000 / this.totalStand)/100;
      return sums;
    },
  },

  //监听事件
  watch: {    
    // //配合复制新增使用 查询人员下的组合项目
    // "prForm.id":{
    //   immediate: true, // 立即执行
    //   // deep: true, // 深度监听复杂类型内变化
    //   handler(newVal,oldVal){
    //     console.log('人员登记 组合项目明细，人员id:',newVal,oldVal)
    //     this.oldFormId = oldVal   
    //     this.getPrAsb(newVal)
    //     // if(newVal != oldVal){
    //     //   this.getPrAsb(newVal)
    //     // }     
    //   }
    // },

    // //人员 id 未变的情况下，亦可触发刷新组合项目
    // "prAsbOpraOpts.prAsbQuery":{
    //   // immediate: true, // 立即执行
    //   // deep: true, // 深度监听复杂类型内变化
    //   handler(newVal,oldVal){        
    //     console.log('watch:prAsbOpraOpts.prAsbQuery:',newVal,oldVal)
    //     if(newVal != oldVal){
    //       this.getPrAsb(this.prForm.id)
    //     }
    //   }
    // },

    "dataTransOpts.refresh.register_asbitem.M":{
      immediate: true, // 立即执行
      // deep: true, // 深度监听复杂类型内变化
      handler(newVal,oldVal){        
        console.log('watch: 刷新 人员登记/编辑 时的组合项目: ',this.dataTransOpts.tableS.patient_register.id)
        this.getPrAsb(this.dataTransOpts.tableS.patient_register.id)        
      }
    },

    //按钮更新支付方式
    "prAsbOpraOpts.payTypeFlag":{
      // immediate: true, // 立即执行
      // deep: true, // 深度监听复杂类型内变化
      handler(newVal, oldVal) {
        if (newVal != oldVal && newVal != '') {
          this.prAsb.forEach(e =>{
            e.payTypeFlag = newVal;
            return e;
          });
          // this.onSubmit('调整支付方式');
        }
      }
    },

    //更换分组
    "prAsbOpraOpts.prAsbGroup":{
      // immediate: true, // 立即执行
      // deep: true, // 深度监听复杂类型内变化
      handler(newVal, oldVal) {        
        if (newVal != oldVal) {
          this.getGroupAsbs(this.prForm.customerOrgGroupId)
        }
      }
    },

    //更换套餐
    "prAsbOpraOpts.prAsbPackage":{
      // immediate: true, // 立即执行
      // deep: true, // 深度监听复杂类型内变化
      handler(newVal, oldVal) {
        if (newVal != oldVal) {
          this.getPackageAsbs(this.prForm.medicalPackageId)
        }
      }
    },

    //复制新增 拷贝明细项目
    "prAsbOpraOpts.copyNew":{
      // immediate: true, // 立即执行
      // deep: true, // 深度监听复杂类型内变化
      handler(newVal, oldVal) {
        if (newVal != oldVal) {
          this.copyNew()
        }
      }
    },

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

  },
};
</script>
<style lang="scss" scoped>
@import "../../assets/css/global_table.css";
@import "../../assets/css/global_input.css";
@import "../../assets/css/global.css";

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

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

.disTotal {
  margin-left: 10px;
}

</style>

