<template>
  <div style="display: flex; margin-top:5px;">
    <div :style="'display: flex;width:' + (window.pageWidth - window.pageMarginWidth - 110 - 5) + 'px;font-size:14px;'">
      <!--未选组合项目-->
      <div style="display: block; width:300px;">
        <div>
          <span>项目类别</span>
          <el-cascader :options="dict.itemTypeTree" v-model="itemTypeIds" popper-class="example"
            style="margin-left: 3px;width:240px;"
            :props="{ checkStrictly: true, expandTrigger: 'hover', ...customerOrg.treeprops, }" clearable filterable
            @change="getAsbItemByItemType" size="small">
          </el-cascader>
        </div>
        <div class="box">
          <el-table :data="dict.asbItem" border size="small" highlight-current-row :height="tableHeight"
            @row-dblclick="dbClickChoosedAsb" row-key="id" @selection-change="selectLeft"
            :row-class-name="handleRowClassName" @row-click="chooseAsbItem">
            <!--
            <el-table-column type="selection" align="center" ></el-table-column>
            -->
            <el-table-column type="index" align="center" width="40" />
            <el-table-column label="未选组合项目" min-width="170" prop="displayName" align="center"></el-table-column>
          </el-table>
        </div>
      </div>

      <!--中间操作按钮-->
      <div style="display: block;margin: 40px 10px 0 15px;width:110px;">
        <div style="padding: 5px 0;">
          <el-button class="commonbutton" @click="addAbs(asbItemChoosed, 'choosed')">添加 <i
              class="el-icon-arrow-right"></i></el-button>
        </div>
        <div style="padding: 5px 0;">
          <el-button class="difference" @click="addAbs(asbItemChoosed, 'all')">全部添加</el-button>
        </div>
        <div style="padding: 5px 0;">
          <el-button class="commonbutton" @click="delAbs(roomAsbitemsChoosed, 'choosed')">移除 <i
              class="el-icon-arrow-left"></i></el-button>
        </div>
        <div style="padding: 5px 0;">
          <el-button class="difference" @click="delAbs(roomAsbitemsChoosed, 'all')">全部移除</el-button>
        </div>
      </div>

      <!--已选组合项目-->
      <div
        :style="'display: block; width:' + (window.pageWidth - 300 - 120 - window.pageMarginWidth - 110 - 5) + 'px;'">
        <div style="height:32px;">
          <div>
            <span>快速选择</span>
            <el-select v-model="asbItemId" placeholder="快速选择组合项目" size="small" filterable default-first-option
              :filter-method="filterMethod" clearable @clear="quickAsb = deepCopy(dict.asbItemQuick)"
              @change="quickChoosedAsb" ref="quickAsbOCX" style="margin-left: 3px;width:240px;">
              <el-option v-for="item in quickAsb" :key="item.id" :value="item.id" :label="item.displayName" />
            </el-select>
          </div>
        </div>
        <div class="box">
          <el-table :data="roomAsbitems" border size="small" @selection-change="selectRight" highlight-current-row
            :height="tableHeight" :summary-method="getSummaries" show-summary :row-class-name="handleRowClassName"
            @row-dblclick="removeAbs" @row-click="removeAsbItem" ref="tableCustomerOrgGroupAsbitems">
            <!--
            <el-table-column type="selection"></el-table-column>
            -->
            <el-table-column type="index" width="40" align="center" />
            <el-table-column label="已选组合项目" min-width="140" prop="asbitemName"></el-table-column>
            <!--
            <el-table-column label="标准价格" prop="price" min-width="60" align="center" />
            <el-table-column label="折扣" min-width="40" align="center">
              <template slot-scope="scope">
                <el-input @input="changeDiscount(scope.$index)" type="number" size="small"
                  v-model="scope.row.discount" />
              </template>
</el-table-column>
<el-table-column label="应收价格" prop="roomDetailPrice" min-width="60" align="center">
  <template slot-scope="scope">
                <el-input @input="changePrices(scope.$index)" type="number" size="small"
                  v-model="scope.row.roomDetailPrice" />
              </template>
</el-table-column>
<el-table-column label="数量" prop="roomDetailAmount" width="50" align="center">
  <template slot-scope="scope">
                <el-input @input="changePrices(scope.$index)" type="number" size="small"
                  v-model="scope.row.roomDetailAmount" />
              </template>
</el-table-column>
<el-table-column label="标准金额" prop="asbitemMoney" min-width="60" align="center">
</el-table-column>
<el-table-column label="应收金额" prop="roomDetailMoney" min-width="60" align="center">
</el-table-column>
-->
          </el-table>
        </div>
      </div>
    </div>
    <!--批量操作按钮（复制套餐与分组）-->
    <div style="display: block;margin-left: 5px;">
      <div style="margin-top: 50px;">
        <el-button class="commonbutton" @click="btnSave">保存</el-button>
      </div>
    </div>

  </div>
</template>
<script>
import moment from 'moment';
import { mapState } from "vuex";
import { getapi, postapi, putapi } from "@/api/api";
import { getPagePriv, checkPagePriv, arrayExistObj, tcdate, arrayFilter, arrayReduce, deepCopy, dddw } from "../../utlis/proFunc";


export default {
  props: ['room'],
  data() {
    return {
      pagePriv: {
        routeUrlorPageName: 'room', //当前页面归属路由或归属页面权限名称
        privs: [] // 页面权限
      },

      roomAsbitems: [], //分组包含组合项目(显示)
      roomAsbitemsChoosed: [], //分组包含组合项目(显示) 被选中
      itemTypeIds: [], //项目类别
      asbItemId: '',   //当前快速选到的给合项目ID
      quickAsb: [],    //过滤显示的组合项目

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



      dialogVisible: false,
      copyGroupdialogVisible: false,
      packagelist: [],
      tabledata: [],
      temporaryselection: [], //已选组合项目table
      copegroupdata: [], //复制分组
      addrulst: [], //添加保存的Id
      price: "", //价格
      title: 1,
    };
  },
  computed: {
    ...mapState(["window", "dict", "dataTransOpts", "customerOrg"]),

    tableHeight() {
      let height = 600
      if (this.window.pageHeight > 600) {
        height = this.window.pageHeight
      }
      // console.log(height - this.window.pageHeaderHeight - this.window.pageMarginHeight - 240 - 96 - 10)  
      return height - this.window.pageHeaderHeight - this.window.pageMarginHeight - 240 - 96 - 16
    }
  },



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

    this.dictInit()
  },
  mounted() {
    this.getRoomAsbitems(this.room.id);
  },

  updated() {
    // this.refreshTable('tableCustomerOrgGroupAsbitems')
  },
  methods: {
    moment, dddw, deepCopy, checkPagePriv,
    //表格强制刷新
    refreshTable(tableRef) {
      this.$nextTick(() => {
        this.$refs[tableRef].doLayout()
      })
    },

    //初始数据
    dictInit() {
      //体检类别 树结构
      getapi("/api/app/item-type/by-code-all").then((res) => {
        if (res.code != -1) {
          this.dict.itemTypeTree = res.data;
          tcdate(this.dict.itemTypeTree);
        }
      });

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

    },

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

    },

    //项目类别过滤 组合项目，未过滤已选择的组合项目
    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 = deepCopy(this.dict.asbItemAll);
      }
      //console.log('lv,this.dict.asbItem', lv, this.dict.asbItem)
      this.dict.asbItemQuick = deepCopy(this.dict.asbItemAll);

    },

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

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

    // 添加组合项目
    ///api/app/register-asbitem/many/3fa85f64-5717-4562-b3fc-2c963f66afa6'
    async addAbs(asbItemChoosed, oprType) {
      // console.log('this.room',this.room)
      // console.log('asbItemChoosed', asbItemChoosed)      
      if (!this.room.id) {
        this.$message.warning({ showClose: true, message: "请先选中分诊叫号房间" })
        return
      }
      if (this.room.isComplete && this.room.isComplete.toUpperCase() == 'Y') {
        this.$message.warning({ showClose: true, message: "体检次数已完成，不允许操作" })
        return
      }
      let message = []
      let checked = true
      let lfind = -1

      //oprType 不传值时，兼容勾选方式
      //勾选时不需要此操作  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({ showClose: true, message: "请选择要添加的组合项目" })
        return
      }

      //性别、年龄判断 
      // "displayName": "身高体重",
      //   "shortName": "哈f哈",
      //   "forSexId": "F",
      //   "itemTypeId": "3a0b16de-75b9-c910-c61b-844709a88940",
      //   "price": 0,

      // for (let i = 0; i < asbItemChoosed.length; i++) {
      //   if (this.room.forSexId == 'A') break //未选性别时，无需判断组合项目性别限制
      //   if (asbItemChoosed[i].forSexId == 'A' || asbItemChoosed[i].forSexId == 'U') continue
      //   if (asbItemChoosed[i].forSexId != this.room.sexId) {
      //     this.$message.warning(`所选项目：${asbItemChoosed[i].displayName}，不适合当前人员性别`)
      //     checked = false
      //     break
      //   }
      // }
      // //console.log(222,checked)
      // if (!checked) return

      // 去掉重复的项目
      arrayReduce(asbItemChoosed, this.roomAsbitems, "id=asbitemId")

      for (let i = asbItemChoosed.length - 1; i > - 1; i--) {
        if (this.room.forSexId == 'A') break //未选性别时，无需判断组合项目性别限制 
        if (asbItemChoosed[i].forSexId == 'A' || asbItemChoosed[i].forSexId == 'U') continue
        if (asbItemChoosed[i].forSexId != this.room.forSexId) {
          message.push(asbItemChoosed[i].displayName)   //.warning(`所选项目：${asbItemChoosed[i].displayName}，不适合当前人员性别`)
          checked = false
          asbItemChoosed.splice(i, 1)
        }
      }
      //console.log(222,checked)
      if (!checked) this.$message.warning(`所选项目【${JSON.stringify(message)}】不适合当前人员性别`)

      for (let i = 0; i < asbItemChoosed.length; i++) {
        let pojo = {
          asbitemId: asbItemChoosed[i].id,
          // displayName: asbItemChoosed[i].displayName,
          asbitemName: asbItemChoosed[i].displayName,
          discount: 100,
          roomDetailAmount: 1,
          price: asbItemChoosed[i].price,
          roomDetailPrice: asbItemChoosed[i].price,
          roomDetailMoney: asbItemChoosed[i].price,
          asbitemMoney: asbItemChoosed[i].price,
        }


        this.roomAsbitems.push(pojo)
        //this.roomAsbitems.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)

      }


    },

    //双击选择组合项目
    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]])
        }
      }

      this.$nextTick(() => {
        this.$refs['quickAsbOCX'].blur(); //total  asbItemId
        this.asbItemId = ''
        this.quickAsb = deepCopy(this.dict.asbItemQuick)
        this.$refs['quickAsbOCX'].focus(); //total  asbItemId       
      });

    },

    //选择 未选的组合项目
    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;

    },

    //删除 人员已选中的组合项目
    ///api/app/register-asbitem/many?RegisterAsbitemIds=3fa85f64-5717-4562-b3fc-2c963f66afa6
    delAbs(absForDel, oprType) {
      if (!this.room.id) {
        this.$message.warning({ showClose: true, message: "请先选中单位分组" })
        return
      }
      if (this.room.isComplete && this.room.isComplete.toUpperCase() == 'Y') {
        this.$message.warning({ showClose: true, message: "体检次数已完成，不允许操作" })
        return
      }


      let lfind = -1

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

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

      for (let i = 0; i < absForDel.length; i++) {

        lfind = arrayExistObj(this.roomAsbitems, 'asbitemId', absForDel[i].asbitemId)
        if (lfind > -1) this.roomAsbitems.splice(lfind, 1)

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

      }

      //刷新
      this.getAsbItemByItemType()

    },

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

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

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

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

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

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

    },

    changeDiscount(index) {

      this.roomAsbitems[index].roomDetailPrice =
        (this.roomAsbitems[index].discount * this.roomAsbitems[index].price / 100).toFixed(2)


      this.roomAsbitems[index].roomDetailMoney =
        (this.roomAsbitems[index].roomDetailPrice * this.roomAsbitems[index].roomDetailAmount).toFixed(2)

      //this.getSummaries()

    },

    //修改价格或数量
    changePrices(index) {
      this.roomAsbitems[index].roomDetailMoney =
        (this.roomAsbitems[index].roomDetailPrice * this.roomAsbitems[index].roomDetailAmount).toFixed(2)

      this.roomAsbitems[index].asbitemMoney =
        (this.roomAsbitems[index].price * this.roomAsbitems[index].roomDetailAmount).toFixed(2)

      this.roomAsbitems[index].discount = (this.roomAsbitems[index].roomDetailPrice * 100 / this.roomAsbitems[index].price).toFixed(2)
      //this.getSummaries()
    },


    //合计
    getSummaries(param) {
      console.log('getSummaries param', param)
      // if(!param){
      //   param = {
      //     columns:[{}, {}, {}, {}, {}, {}, {property: 'asbitemMoney'},{property: 'roomDetailMoney'}],
      //     data:this.roomAsbitems
      //   }
      // }

      const { columns, data } = param;
      const sumCol = [6, 7]  //需合计的列
      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] += Number(e[column.property])// * e['amount']
        })
        sums[index] = sums[index].toFixed(2) //+ ' 元';

      });
      this.groupPrice = sums[7];
      // console.log('getSummaries',sums)
      // if (!this.totalFoucs) this.total = sums[5];
      // if (!this.discountFoucs) this.discount = Number(this.total * 100 / this.totalStand).toFixed(2);
      return sums;
    },

    //保存按钮
    btnSave() {
      if (!this.room.id) {
        this.$message.warning({ showClose: true, message: "请先选中分诊叫号房间" })
        return
      }


      let body = {
        roomId: this.room.id,
        asbitemIds: []
      }
      // {
      //   "roomId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      //   "asbitemIds": [
      //     "3fa85f64-5717-4562-b3fc-2c963f66afa6"
      //   ]
      // }

      this.roomAsbitems.forEach(e => {
        body.asbitemIds.push(e.asbitemId)
      })
      
      postapi('/api/app/Room/CreateRoomDetails', body)        
        .then(res => {
          if (res && res.code != -1) {
            console.log("操作成功");            
            this.dataTransOpts.refresh.room_detail.M++
          }
        })

    },


    //右侧勾选按钮
    selectRight(val) {
      this.roomAsbitemsChoosed = val;
    },


    // 左侧未选
    selectLeft(val) {
      this.asbItemChoosed = val;
    },


    //获取当前列列表数据
    getRoomAsbitems(roomId) {
      if (roomId) {
        postapi('/api/app/Room/GetAsbitemListByRoomId', { roomId })
          .then((res) => {
            if (res.code != -1) {
              this.roomAsbitems = res.data;
              this.getAsbItemByItemType()
            }
          });
      } else {
        this.roomAsbitems = []
        this.getAsbItemByItemType()
      }
    },

  },

  //监听事件
  watch: {
    // 体检分组ID未切换换时 也可以强制刷新数据
    "dataTransOpts.refresh.room_detail.M": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log(`watch 体检分组 newVal:${newVal} oldVal:${oldVal} registerCheckId: ${this.room.id}`);
        if (newVal != oldVal) this.getRoomAsbitems(this.room.id);
      }
    },
  },
};
</script>
<style scoped>
.box {
  margin-top: 5px;
  /* border: 1px solid #000; */
}

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