<template>
    <div class="ManageItemBatchWrapper">
        <crumbs :title="title" :param="$route.params" linkTo="RecordItemList" minWidth="1210px"></crumbs>
        <div class="contents">
            <div class="content">
                <el-form ref="form" :label-position="labelPosition" label-width="125px" class="add-record-form" >
                    
                    <el-form-item label="选择医院：" prop="brbaxx">
                        <el-select v-model="hospitalId"
                                   placeholder="请选择医院"
                                   size="small"
                                   @change="changeHospital">
                            <el-option
                                    v-for="item in hospitalList"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    
                    <el-form-item label="条目列表：" prop="hospitalList">
                        <!-- <el-table
                            ref="multipleTable"
                            :data="tableData"
                            tooltip-effect="light"
                            style="width: 100%"
                            @selection-change="handleSelectionChange">
                            <el-table-column
                              type="selection"
                              width="120">
                            </el-table-column>
                            <el-table-column
                              label="医院名称"
                              prop="hospitalName"
                              width="240">
                             
                            </el-table-column>
                            <el-table-column
                              prop="name"
                              label="扣分值"
                              width="240">
                                 <template slot-scope="scope">
                                  <el-input  class="tipsMsg" v-model="scope.row.value" placeholder="请输入扣分值"></el-input>
                                 </template>
                            </el-table-column>
                            <el-table-column
                              prop="address"
                              label="提示语"
                              width="240"
                              show-overflow-tooltip>
                               <template slot-scope="scope">
                                  <el-input class="tipsMsg" v-model="scope.row.tipMsg" placeholder="请输入提示语"></el-input>
                                 </template>
                            </el-table-column>
                          </el-table> -->
                          <el-collapse v-model="activeLeftNames" @change="handleChange" v-if="caseLIst.length > 0">
                                <el-collapse-item v-for="(item, index) in caseLIst" :title="item.name" :name="item.id" :key="item.id">
                                    <!-- <el-checkbox-group v-model="checkAllMap[item.remark]" >
                                      <el-checkbox v-for=" casesEntry in item.qcCasesEntry" :label="casesEntry.id" :key="casesEntry.id">{{casesEntry.name}}
                                        <el-input placeholder="请输入扣分值"></el-input>
                                      </el-checkbox>
                                  </el-checkbox-group> -->
                                  <el-table
                                    ref="multipleTable"
                                    :data="item.qcCasesEntry"
                                    tooltip-effect="light"
                                    style="width: 100%"
                                    @selection-change="handleSelectionChange($event,item.remark)">
                                    <el-table-column
                                      type="selection"
                                      width="60">
                                    </el-table-column>
                                     <el-table-column
                                      label="条目编码"
                                      prop="code"
                                      width="120">
                                    </el-table-column>
                                    <el-table-column
                                      label="条目名称"
                                      prop="name"
                                      width="240">
                                    </el-table-column>
                                    <el-table-column
                                      label="医院数据模块"
                                      prop="modeName"
                                      width="120">
                                    </el-table-column>
                                    <el-table-column
                                      prop=""
                                      label="扣分值"
                                      width="120">
                                        <template slot-scope="scope">
                                          <el-input  class="scoreInp" oninput="if(value.length>5)value=value.slice(0,5)" v-model.trim="scope.row.score" type="number" placeholder=""></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                      prop="address"
                                      label="提示信息"
                                      width="240"
                                      show-overflow-tooltip>
                                      <template slot-scope="scope">
                                          <el-input class="tipsMsg" v-model.trim="scope.row.msg" placeholder="请输入提示信息"></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                    prop="address"
                                    label="是否启用"
                                    width="120"
                                    show-overflow-tooltip>
                                    <template slot-scope="scope">
                                        <span class="checkUsed" :class="{'active': scope.row.isUsed == 1,'disabled': getDisabled(scope.row,item.remark)}" @click="checkUsed(scope.row,index,scope.$index,item.remark)"></span>
                                        <!-- <el-checkbox v-model="scope.row.isUsed" :value ="scope.row.isUsed" :disabled="getIsUsed(scope.row)" true-label="1" false-label="0">{{scope.row.isUsed}}</el-checkbox> -->
                                      </template>
                                  </el-table-column>
                                  </el-table>
                                </el-collapse-item>
                              </el-collapse>
                    </el-form-item>
                    <p class="oper">
                        <el-button style="margin-right: 30px" size="small" type="primary" @click="comfirn('form')">确定</el-button>
                        <el-button size="small" @click="cancel">取消</el-button>
                    </p>
                </el-form>
            </div>
        </div>
    </div>
</template>
<script type="text/javascript">
 import api from '@api/records.js';
 import $ from 'jquery';

  export default {
    name:'ManageItemBatch',
    data(){
      return{
        // data:{},
        labelPosition:'left',
        /*zybljlList:[
          {name:'aaa',content:'333333'},
          {name:'vvv',content:'333sa'}
        ],*/
        hospitalList:[],
        caseLIst:[],
        sexType:[],
        bloodType:[],
        rhType:[],
        title:'病历条目-批量管理',
        hospitalId:'',
        tableData:[],
        checkAllMap:{

        },
        multipleSelection: [],
        id:null,
        activeLeftNames: [],
        modifier:''
      }
    },
    created(){
      const userLoginDTO = JSON.parse(localStorage.getItem('userLoginDTO'))
      this.modifier = userLoginDTO && userLoginDTO.linkman
     
      this.getRecordHopitalList()
      // this.getRecordInpModule()
    },
    methods:{
      toggleSelection(values) {
        setTimeout(()=>{
          //  this.$refs.multipleTable[6].toggleRowSelection(this.caseLIst[6].qcCasesEntry[0]);
          //  this.$refs.multipleTable[6].toggleRowSelection(this.caseLIst[6].qcCasesEntry[1]);
          for(let i = 0; i < values.length; i++){
            if(values[i].length > 0){
              values[i].forEach(value=>{
                const index = this.caseLIst[i].qcCasesEntry.findIndex(item =>item.id === value.id)
                this.$refs.multipleTable[i].toggleRowSelection(this.caseLIst[i].qcCasesEntry[index]);
              })
            }
          }
          // if (rows) {
          // rows.forEach(row => {
          //   this.$refs.multipleTable.toggleRowSelection(row);
          //   // console.log('this.$refs.multipleTabl',this.$refs.multipleTable)
          //   // const domLen = this.$refs.multipleTable.length
          //   // const values = Object.values(this.checkAllMap)
          //   // console.log('values，',values)
          //   // for(let i = 0; i < values.length; i++){
          //   //   if(values[i].length > 0){
          //   //     console.length('aaaaaaaaaaa')
          //   //     this.$refs.multipleTable[i].toggleRowSelection(value[i]);
          //   //   }
          //   // }
          // });
        // } else {
        //   console.log('bbbb')
        //    const domLen = this.$refs.multipleTabl.length
        //     for(let i = 0; i < domLen; i++){
        //       // this.$refs.multipleTable[i].clearSelection();
        //     }
        // }
        })
        
      },
      checkUsed(row,index,ii,remark){
        if(this.getDisabled(row,remark)){
          return
        }
        let isUsed = this.caseLIst[index].qcCasesEntry[ii].isUsed
        const caseLIstCopy = JSON.parse(JSON.stringify(this.caseLIst))
        if(isUsed == 1){
          caseLIstCopy[index].qcCasesEntry[ii].isUsed = 0
        }else{
          caseLIstCopy[index].qcCasesEntry[ii].isUsed = 1
        }
        this.caseLIst = caseLIstCopy
        const values = Object.values(this.checkAllMap)
        this.toggleSelection(values)
      },
      handleSelectionChange(val,remark) {
        this.checkAllMap[remark] = val;
      },
      getIsUsed(row){
        // if(this.multipleSelection.findIndex(it => it.hospitalId ==row.hospitalId) > -1){
        //   return false
        // } else{
        //    return true
        // }
        
      },
      getDisabled(row,remark){
        const hasChecked = this.checkAllMap[remark].findIndex(item => item.id === row.id) === -1
        return hasChecked
      },
       handleChange(val) {
      },
      changeHospital(val){
        this.getRecordInpModule().then(()=>{
          this.getRecordByHospital(val)
         }
        )
        
      },
      getRecordInpModule(){
        return api.getRecordInpModule({}).then((res)=>{
          const result = res.data;
          if(result.code==0){
            let  caseLIstCopy = result.data
            for(let i = 0; i < caseLIstCopy.length; i++){
              for(let j = 0; j < caseLIstCopy[i].qcCasesEntry.length; j++){
                caseLIstCopy[i].qcCasesEntry[j].isUsed = 0
              }
            }

            this.caseLIst = caseLIstCopy  //提醒每项加分值和备注

             const checkAllMap = {}
            for(let i = 0; i < this.caseLIst.length; i++){
              checkAllMap[this.caseLIst[i].remark] = []
            }
            this.checkAllMap = checkAllMap
          }else{
            this.$message({
              message:result.msg,
              type:'warning',
              showClose: true
            });
          }
        })
      },
      getRecordHopitalList(){
        return api.getRecordHopitalList({}).then((res)=>{
          const result = res.data;
          if(result.code==0){
            this.hospitalList = result.data
            const tableData = []
            for(let i = 0; i < this.hospitalList.length; i++){
              tableData.push({
                hospitalId: this.hospitalList[i].id,
                hospitalName:  this.hospitalList[i].name,
                value: '',
                tipMsg:''
              })
            }
            this.tableData = tableData
          }else{
            this.$message({
              message:result.msg,
              type:'warning',
              showClose: true
            });
          }
        })
      },
      getRecordByHospital(hospitalId){
        const param = {
          hospitalId: hospitalId
        }
        return api.getRecordByHospital(param).then((res)=>{
          const result = res.data;
          if(result.code==0){
            this.hospitalItemList =  result.data
            for (let i = 0; i< this.hospitalItemList.length; i++){
              const hospitalItem = this.hospitalItemList[i]
              let caseItem = this.caseLIst.find(item =>item.id === hospitalItem.casesId)
              for(let j = 0; j < hospitalItem.getAllByHospitalDetialDTOS.length; j++){
               
                const checkedItem = hospitalItem.getAllByHospitalDetialDTOS[j]
                let recordItem = caseItem.qcCasesEntry.find(item => item.id === checkedItem.casesEntryId)
                recordItem.score = checkedItem.score
                recordItem.msg = checkedItem.msg
                recordItem.isUsed = checkedItem.isUsed
                recordItem.modeName = checkedItem.modeName
                this.checkAllMap[caseItem.remark].push(recordItem)
              }
            }
            this.caseLIst = JSON.parse(JSON.stringify(this.caseLIst))
             const values = Object.values(this.checkAllMap)
            this.toggleSelection(values)
          }else{
            this.$message({
              message:result.msg,
              type:'warning',
              showClose: true
            });
          }
        })
      },
      cancel(){
        this.$router.push({
          name: 'RecordItemList',
          params: Object.assign({}, this.$route.params)
        });
      },
      comfirn(form){
        if(!this.hospitalId){
          this.$message({
                    message:"请选择医院",
                    type:'warning',
                    showClose: true
                  });
        }
        const values = Object.values(this.checkAllMap);
        let casesEntryHospitals = [],requiredValNull=[],valueTypeWr=[],tempItemIdx={};
        $(".el-collapse .wrong").removeClass("wrong");
        for(let i = 0; i < values.length; i++){
          for(let j = 0; j < values[i].length;j++){
            const value = values[i][j];
            if(!valueTypeWr.length&&(!value.msg||value.score==="")){
              tempItemIdx=this.caseLIst[i].qcCasesEntry.findIndex(item =>item.id === value.id);
              requiredValNull.push(value.casesId);
              $(".el-collapse .el-collapse-item:eq("+i+") table tr:eq("+(+tempItemIdx+1)+")").addClass("wrong");
            }
            var reg = new RegExp(/^\d+(\.\d)?$/);
            if(!requiredValNull.length&&(!reg.test(value.score) || value.score >100)){
              tempItemIdx=this.caseLIst[i].qcCasesEntry.findIndex(item =>item.id === value.id);
              $(".el-collapse .el-collapse-item:eq("+i+") table tr:eq("+(+tempItemIdx+1)+")").addClass("wrong");
              valueTypeWr.push(value.casesId);
            }
            let item = {
              "casesEntryId": value.id,
              "creator": "0",
              "hospitalId": this.hospitalId,
              "modifier": this.modifier,
              "msg": value.msg||"",
              "remark": value.remark,
              "score": Number(value.score),
              "isUsed":value.isUsed||0
            }
            casesEntryHospitals.push(item)
          }
        }
        if(requiredValNull.length>0){
          this.$message({
            message:'勾选项扣分值和提示信息不能为空',
            type:'warning',
            showClose: true
          });
          this.activeLeftNames = requiredValNull;
          return
        }else if(valueTypeWr.length>0){
          this.$message({
            message:'扣分值请输入≥0且≤100的数字，最多保留小数点后1位',
            type:'warning',
            showClose: true
          });
          this.activeLeftNames = valueTypeWr;
          return
        }
        let param = {
          "casesEntryHospitals": casesEntryHospitals,
          "hospitalIds": [
           this.hospitalId
          ]
        }
        api.updateRecordByHospital(param).then((res)=>{
                if(res.data.code==0){
                  this.$message({
                    message:"修改成功",
                    type:'success',
                    showClose: true
                  });
                  //返回带搜索条件的首页
                  this.$router.push({
                    name: 'RecordItemList',
                    params: Object.assign({}, this.$route.params)
                  });
                }else{
                  this.$message({
                    message:res.data.msg,
                    type:'warning',
                    showClose: true
                  });
                }
              })
        return
        /*if(!this.form.name.trim() || !this.form.refreshTime.trim()){
          this.$message({
            message:'请填写相关内容',
            type:'warning'
          });
          return
        }*/
        /*this.$refs[form].validate((valid) => {
          if (valid) {*/
            // if(this.basyid){//修改
            //   const param = Object.assign({},this.form,{basyid:this.basyid,brzyid:this.brzyid});
            //   api.saveRecord(param).then((res)=>{
            //     if(res.data.code==0){
            //       this.$message({
            //         message:"修改成功",
            //         type:'success'
            //       });
            //       //返回带搜索条件的首页
            //       this.$router.push({
            //         name: 'RecordManager',
            //         params: Object.assign({}, this.$route.params)
            //       });
            //     }else{
            //       this.$message({
            //         message:res.data.msg,
            //         type:'warning'
            //       });
            //     }
            //   })
            // }else{//添加
            //   // 复制时把list多余字段过滤掉，如id等
            //   const detail = this.list;
            //   let copyDetail=[];
            //   let item={};
            //   if(detail && detail.length>0){
            //     for(let i=0; i<detail.length; i++){
            //       item.title = detail[i].title;
            //       item.description = detail[i].description;
            //       copyDetail.push(item);
            //       item={};
            //     }
            //   }
            //   const params = Object.assign({},this.form);
            //   // api.addVersInfo(this.form).then((res)=>{
            //   api.saveRecord(params).then((res)=>{
            //     if(res.data.code==0){
            //       this.$message({
            //         message:"添加成功",
            //         type:'success'
            //       })
            //       // this.$router.push({path: 'LT-GBBXXWH-BBXXWH'});
            //       this.$router.push({name: 'RecordManager'});
            //     }else{
            //       this.$message({
            //         message:res.data.msg,
            //         type:'warning'
            //       });
            //     }
            //   })
            // }
          /*} else {
            return false;
          }
        });*/
      },
    }
  }
</script>
<style lang="less">
    @import "../../less/admin.less";
    .ManageItemBatchWrapper{
      .content{
        background: #fff;
        padding: 20px 20px 50px;
        color: #545455;
        min-width: 1200px;
        position: relative;
        .short-inp{
            width: 200px;
        }
        .sub-title{
            font-weight: bold;
            font-size: 16px;
            margin-bottom: 20px;
        }
        .oper{
            text-align: right;
        }
        .checkUsed{
          cursor: pointer;
          position: relative;
          // color: #fff;
          display: inline-block;
          width: 14px;
          height: 14px;
          background:  #fff;
          border: 1px solid #333;
          box-sizing: border-box;
          border-radius: 2px;
          -webkit-transition: border-color .25s cubic-bezier(.71,-.46,.29,1.46),background-color .25s cubic-bezier(.71,-.46,.29,1.46);
          transition: border-color .25s cubic-bezier(.71,-.46,.29,1.46),background-color .25s cubic-bezier(.71,-.46,.29,1.46);
        }
        .active{
          position: relative;
          // color: #fff;
          display: inline-block;
          width: 14px;
          height: 14px;
          background:  #48C5D7;
          border: 1px solid #333;
          box-sizing: border-box;
          border-radius: 2px;
          -webkit-transition: border-color .25s cubic-bezier(.71,-.46,.29,1.46),background-color .25s cubic-bezier(.71,-.46,.29,1.46);
          transition: border-color .25s cubic-bezier(.71,-.46,.29,1.46),background-color .25s cubic-bezier(.71,-.46,.29,1.46);
        }
        .wrong td{
            border:1px #ff0000 solid;
            border-right:none;
            border-left:none;
            &:last-child{
                 border-right:1px #ff0000 solid;
             }
            &:first-child{
                 border-left:1px #ff0000 solid;
             }
        }
        .active::after{
            -webkit-box-sizing: content-box;
            box-sizing: content-box;
            content: "";
            border: 1px solid #FFF;
            border-left: 0;
            border-top: 0;
            height: 7px;
            left: 4px;
            position: absolute;
            top: 1px;
            -webkit-transform: rotate(45deg) scaleY(0);
            transform: rotate(45deg) scaleY(0);
            width: 3px;
            -webkit-transition: -webkit-transform .15s ease-in .05s;
            transition: -webkit-transform .15s ease-in .05s;
            transition: transform .15s ease-in .05s;
            transition: transform .15s ease-in .05s, -webkit-transform .15s ease-in .05s;
            transition: transform .15s ease-in .05s,-webkit-transform .15s ease-in .05s;
            -webkit-transform-origin: center;
            transform-origin: center;
            -webkit-transform: rotate(45deg) scaleY(1);
            transform: rotate(45deg) scaleY(1);
        }
        .active.disabled::after{
           -webkit-box-sizing: content-box;
            box-sizing: content-box;
            content: "";
            border: 1px solid #c9cdd5;
            border-left: 0;
            border-top: 0;
            height: 7px;
            left: 4px;
            position: absolute;
            top: 1px;
            -webkit-transform: rotate(45deg) scaleY(0);
            transform: rotate(45deg) scaleY(0);
            width: 3px;
            -webkit-transition: -webkit-transform .15s ease-in .05s;
            transition: -webkit-transform .15s ease-in .05s;
            transition: transform .15s ease-in .05s;
            transition: transform .15s ease-in .05s, -webkit-transform .15s ease-in .05s;
            transition: transform .15s ease-in .05s,-webkit-transform .15s ease-in .05s;
            -webkit-transform-origin: center;
            transform-origin: center;
            -webkit-transform: rotate(45deg) scaleY(1);
            transform: rotate(45deg) scaleY(1);
         
        }
        .disabled{
          cursor: not-allowed;
          background-color: #edf2fc;
        }
        /deep/.el-table__row td:nth-child(3){
          text-align: left;
        }
        /deep/.el-input{
              .el-input__inner{
                    border: 1px solid #333;
                    color: #000;
              }
            }
        /deep/.el-checkbox__inner{
                  border: 1px solid #333;
            }
        /deep/.tipsMsg{
            .el-input__inner{
                width:200px;
                height: 30px;
                display: inline-block;
                border: 1px solid #333;
                color: #000;
            }
        }
        /deep/.el-table .cell, .el-table th div, .el-table--border td:first-child .cell, .el-table--border th:first-child .cell {
          padding: 0;
        }
         /deep/.el-input input::-webkit-outer-spin-button,
            /deep/.el-input input::-webkit-inner-spin-button {
              -webkit-appearance: none;
            }
        /deep/.el-input input[type="number"]{
          -moz-appearance: textfield;
          line-height: 20px;
        }
        /deep/.scoreInp.el-input{
              width:50px;
              .el-input__inner{
                    width:50px;
                    height: 30px;
                    display: inline-block;
                }
            }
      }
    }
    

</style>