<template>
  <div class="app-container subject">
    <div class="page-container subject-page" v-if="pageType == 1">
      <div class="left-subject-list">
        <div class="page-form-title-box">
          <el-form :model="queryParams" ref="queryForm" :inline="true">
            <el-form-item label="" prop="searchValue">
              <el-input
                v-model="queryParams.searchValue"
                placeholder="实验室/房间号"
                clearable
                maxlength="10"
                style="width:150px;"
              />
            </el-form-item>
            <el-form-item label="" prop="deptId">
              <el-select v-model="queryParams.deptId" placeholder="二级单位" style="width:140px;">
                <el-option
                  v-for="dict in deptOptions"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="buildId">
              <el-select v-model="queryParams.buildId" placeholder="楼栋" style="width:140px;">
                <el-option
                  v-for="dict in buildOptions"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="typeId">
              <el-select v-model="queryParams.typeId" placeholder="安全分类" style="width:140px;">
                <el-option
                  v-for="dict in typeList"
                  :key="dict.typeId"
                  :label="dict.typeName"
                  :value="dict.typeId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="levelId">
              <el-select v-model="queryParams.levelId" placeholder="安全分级" style="width:140px;">
                <el-option
                  v-for="dict in levelList"
                  :key="dict.levelId"
                  :label="dict.levelName"
                  :value="dict.levelId"
                ></el-option>
              </el-select>
            </el-form-item>
            <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
            <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
            <el-dropdown @command="commandButton" style="float: right;">
              <p class="page-submit-common-style-button" style="width:105px;"
              >操作<span class="el-icon-arrow-down" style="margin-left:10px;"></span></p>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{command:1}" v-hasPermiRouter="['system:subject:add']">新增</el-dropdown-item>
                <!--<el-dropdown-item :command="{command:2}">关联配置</el-dropdown-item>-->
                <!--<el-dropdown-item :command="{command:3}">准入配置</el-dropdown-item>-->
                <el-dropdown-item :command="{command:4}">下载二维码</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-form-item v-hasPermiRouter="['system:subject:import']" style="float: right;">
              <import-component :importConfig="importConfig"></import-component>
            </el-form-item>
          </el-form>
        </div>
        <div class="page-content-box">
          <el-table class="table-box" ref="table-box" border :data="dataList" highlight-current-row
                    @select-all="handleSelectionChange" @select="handleSelectionChange" :row-key="getRowKeys"
                    @current-change="handleCurrentChange">
            <el-table-column type="selection" width="50" :reserve-selection="true" align="center"/>
            <el-table-column label="排序" align="left" prop="orderNum" width="75">
              <template slot-scope="scope">
                <el-input maxlength="4" type="text" oninput="value=value.replace(/[^0-9.]/g,'')"
                          v-model="scope.row.orderNum" @focus="liveSort(scope.row)"
                          @blur="editSort(scope.row)">
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="实验室名称" align="left" prop="subName" show-overflow-tooltip/>
            <el-table-column label="房间号" align="left" prop="roomName" width="100" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{scope.row.roomName?scope.row.roomName:'未绑定'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="学院" align="left" prop="deptName" width="130" show-overflow-tooltip/>
            <el-table-column label="楼栋/楼层" align="left" prop="buildName" width="130" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{scope.row.buildName}}/{{scope.row.floorName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="分类/分级" align="left" prop="levelName" width="150" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{scope.row.typeName}}/</span>
                <span :style="'color:'+scope.row.levelColor+';'">{{scope.row.levelName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="实验室责任人" align="left" prop="adminName" width="120" show-overflow-tooltip/>
            <el-table-column label="安全员" align="left" prop="safeUserNames" width="120" show-overflow-tooltip/>
            <el-table-column label="操作" align="left" width="140">
              <template slot-scope="scope">
                <div class="table-button-box">
                  <p class="table-button-null"></p>
                  <p class="table-button-p" v-hasPermiRouter="['system:subject:detail']"
                     @click.stop="clickPage(7,scope.row)">详情</p>
                  <el-dropdown trigger="click" size="mini" @command="(command) => handleCommand(command, scope.row)">
                    <p class="table-button-p">更多>></p>
                    <el-dropdown-menu slot="dropdown" style="margin:0!important;">
                      <el-dropdown-item style="height:36px;line-height:36px;width:90px;text-align: center" command="1"
                                        v-hasPermiRouter="['system:subject:edit']">关联配置
                      </el-dropdown-item>
                      <el-dropdown-item style="height:36px;line-height:36px;width:90px;text-align: center" command="2"
                                        v-hasPermiRouter="['system:subject:edit']">准入配置
                      </el-dropdown-item>
                      <el-dropdown-item style="height:36px;line-height:36px;width:90px;text-align: center" command="3"
                                        v-hasPermiRouter="['system:subject:edit']">编辑
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <p class="table-button-null"></p>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
      <index-right-page ref="indexRightPage"></index-right-page>
    </div>
    <!--新增/编辑-->
    <add-subject v-if="pageType == 2" :subjectData="subjectData"></add-subject>
    <!--准入配置-->
    <admission-configuration v-if="pageType == 4" :subjectData="subjectData"></admission-configuration>
    <!--关联配置-->
    <association-configuration v-if="pageType == 5" :subjectData="subjectData"></association-configuration>
    <!--详情-->
    <info-page v-if="pageType == 6" :subjectData="subjectData"></info-page>
    <!--批量二维码-->
    <batchQrCodeDialog ref="batchQrCodeDialog" :batchQrCodeDialogData="batchQrCodeDialogData"></batchQrCodeDialog>
  </div>
</template>

<script>
  /********************** V3 **********************/
  import importComponent from "@/components/importComponent/importComponent.vue";
  import batchQrCodeDialog from "@/components/batchQrCodeDialog/batchQrCodeDialog.vue";
  import {
    getDeptDropList,
    systemBuildingGetTreeList,
    laboratoryClassTypeGetList,
    laboratoryClassLevelGetList,
  } from '@/api/commonality/permission'
  import {
    laboratorySubRelInfoList,
    laboratorySubRelInfoGetDetailInfo,
    laboratorySubRelInfoGetDetailDelete,
    laboratorySubRelInfoGetHazardSubRelInfo,
    laboratorySubRelInfoUpdateBySort
  } from '@/api/integratedManagement/index'
  import indexRightPage from './indexRightPage/indexRightPage.vue'
  import addSubject from './addSubject.vue'
  import admissionConfiguration from './admissionConfiguration.vue'
  import associationConfiguration from './associationConfiguration.vue'
  import infoPage from './infoPage.vue'
  export default {
    name: 'subject',
    components: {
      importComponent,
      addSubject,
      admissionConfiguration,
      associationConfiguration,
      infoPage,
      indexRightPage,
      batchQrCodeDialog
    },
    data() {
      return {
        //批量二维码
        batchQrCodeDialogData:{},
        //导入数据
        importConfig:{
          upLoadApi:'/laboratory/subRelInfo/importSubData',                //上传接口地址
          downloadApi:'/laboratory/subRelInfo/exportSubTemplate',          //下载模板接口地址
          loseApi:'/laboratory/subRelInfo/exportProblemData',             //失败报表接口地址
          fileName:'实验室导入模板',                                   //下载模板命名
        },
        //页面状态
        pageType: 1,
        // 查询参数
        queryParams: {
          page: 1,
          pageSize: 20,
          searchValue: '',
          deptId: '',
          typeId: '',
          levelId: ''
        },
        // 实验室表格数据
        dataList: [],
        // 楼栋
        buildOptions:[],
        // 总条数
        total: 0,
        //学院列表
        deptOptions: [],
        //实验室数据
        subjectData: {},
        // 临时保存排序
        orderNum: '',
        //分类数据
        typeList: [],
        //分级数据
        levelList: [],
        //二维码勾选数据
        codeList:'',
      }
    },
    created() {
    },
    mounted() {
      //获取院系列表
      this.getDeptDropList()
      //获取楼栋列表
      this.systemBuildingGetTreeList()
      //获取分类列表
      this.laboratoryClassTypeGetList()
      //获取分级列表
      this.laboratoryClassLevelGetList()
      //获取列表数据
      this.getList()
    },
    methods: {
      //操作按钮
      commandButton(item){
        if(item.command == 1){
          this.clickPage(2);
        }else if(item.command == 2){

        }else if(item.command == 3){

        }else if(item.command == 4){
          if(this.codeList.length>0){
            let list = [];
            this.codeList.forEach((item)=>{
              list.push({
                code:item.infoId+'&subId='+item.subId,
                name:item.subName
              })
            })
            this.$set(this,'batchQrCodeDialogData',{
              title:'实验室二维码批量下载',                                               //弹窗名称(非必传)
              type:'5',                                                     //二维码类型 用于区分二维码功能类型
              codeList:list
            });
            this.$nextTick(function () {
              this.$refs['batchQrCodeDialog'].initialize();
            })
          }else{
            this.msgError('请勾选实验室')
          }
        }
      },
      // 页面切换
      clickPage(type, row) {
        if (this.pageType != type) {
          if (type == 1) {
            //列表页面
            this.pageType = type
            this.getList()
            this.$set(this, 'subjectData', {})
          } else if (type == 2) {
            //新增页面
            this.pageType = type
          }else if (type == 7) {
            //实验室详情
            this.getSubInfo(row,1)
          }
        }
      },
      //更多按钮
      handleCommand(command, row) {
        let self = this
        switch (command) {
          case '1':
            //关联配置
            laboratorySubRelInfoGetHazardSubRelInfo({ infoId: row.infoId }).then(response => {
              this.$set(this, 'subjectData', response.data)
              this.$set(this, 'pageType', 5)
            })
            break
          case '2':
            //准入配置
            this.pageType = 4
            this.$set(this, 'subjectData', row)
            break
          case '3':
            //编辑页面
            this.getSubInfo(row,2)
            break
          case '4':
            //删除
            self.$confirm('是否确认删除?', '', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(function() {
              laboratorySubRelInfoGetDetailDelete({ infoId: row.infoId }).then(response => {
                self.msgSuccess(response.message)
                self.getList()
              })
            }).then(() => {
            }).catch(() => {
            })
            break
          default:
            break
        }
      },
      //获取实验室详情 type:1.详情 2.编辑
      getSubInfo(row,type){
        laboratorySubRelInfoGetDetailInfo({ infoId: row.infoId }).then(response => {
          let classifyList = [];
          for(let i=0;i<response.data.labInfoBrandModels.length;i++){
            if(response.data.labInfoBrandModels[i].privateList.length>0 && (response.data.labInfoBrandModels[i].brandType==1||response.data.labInfoBrandModels[i].brandType==2)){
              classifyList.push(response.data.labInfoBrandModels[i]);
            }
          }
          response.data.classifyList = classifyList;
          if(response.data.safeUserList[0]){
            response.data.safeUserId = [];
            response.data.safeUserList.forEach((item)=>{
              response.data.safeUserId.push(item.safeUserId);
            })
          }
          this.$set(this, 'subjectData', response.data)
          if(type == 1){
            //详情
            this.$set(this, 'pageType', 6)
          }else if(type == 2){
            //编辑
            this.$set(this, 'pageType', 2)
          }
        })
      },
      //保存当前排序
      liveSort(row) {
        let obj = {
          orderNum: row.orderNum
        }
        this.orderNum = JSON.parse(JSON.stringify(obj))
      },
      //编辑排序
      editSort(row) {
        let self = this
        if (row.orderNum != this.orderNum.orderNum) {
          self.$confirm('是否确认修改排序?', '', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(function() {
            let obj = {
              infoId: row.infoId,
              orderNum: row.orderNum
            }
            laboratorySubRelInfoUpdateBySort(obj).then(response => {
              self.msgSuccess('修改成功')
              self.getList()
            })
          }).then(() => {
          }).catch(() => {
            let obj = JSON.parse(JSON.stringify(self.orderNum))
            row.orderNum = obj.orderNum
          })
        }
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.$set(this.queryParams,'page',1);
        this.$set(this,'codeList','');
        this.$refs['table-box'].clearSelection();
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.$set(this, 'queryParams', {
          page: 1,
          pageSize: 20,
          searchValue: '',
          deptId: '',
          buildId: '',
          typeId: '',
          levelId: ''
        })
        this.$set(this,'codeList','');
        this.$refs['table-box'].clearSelection();
        this.getList()
      },
      //选中实验室
      handleCurrentChange(val) {
        this.$refs.indexRightPage.initialize(val);
      },
      /** 查询实验室列表 */
      getList() {
        laboratorySubRelInfoList(this.queryParams).then(response => {
          this.$set(this,'dataList',response.data.records);
          this.$set(this,'total',response.data.total);
          if (response.data.records[0]) {
            this.$refs['table-box'].setCurrentRow(response.data.records[0])
          }
        })
      },
      /** 查询学院列表 */
      getDeptDropList() {
        getDeptDropList({ deptName: '', level: 2, deptType: 1 }).then(response => {
          this.$set(this, 'deptOptions', response.data)
        })
      },
      //查询楼栋楼层
      systemBuildingGetTreeList(){
        systemBuildingGetTreeList({}).then(response => {
          let newList = [];
          if (response.data[0]) {
            let list = this.forBuildFloor(response.data);
            for(let i=0;i<list.length;i++){
              if(list[i].buildFloorVoList){
                for(let o=0;o<list[i].buildFloorVoList.length;o++){
                  if(list[i].buildFloorVoList[o].buildFloorVoList){
                    newList.push(list[i].buildFloorVoList[o])
                  }
                }
              }
            }
          }
          this.$set(this, 'buildOptions', newList)
        })
      },
      //处理楼栋楼层数据
      forBuildFloor(list){
        let self = this;
        for(let i=0;i<list.length;i++){
          if(list[i].buildFloorVoList){
            if(list[i].buildFloorVoList[0]){
              list[i].buildFloorVoList = self.forBuildFloor(list[i].buildFloorVoList);
            }else{
              delete list[i].buildFloorVoList;
            }
          }else{
            delete list[i].buildFloorVoList;
          }
        }
        return list
      },
      //查询安全分级
      laboratoryClassLevelGetList() {
        laboratoryClassLevelGetList({}).then(response => {
          this.$set(this, 'levelList', response.data)
        })
      },
      //查询安全分类
      laboratoryClassTypeGetList() {
        laboratoryClassTypeGetList({}).then(response => {
          this.$set(this, 'typeList', response.data)
        })
      },
      //****************************************导入功能**************************************
      // 多选框选中数据
      handleSelectionChange(selection) {
        let self = this;
        if(selection[40]){
          this.$refs['table-box'].clearSelection();
          this.$nextTick(()=>{
            let ids = [];
            for(let i=0;i<selection.length;i++){
              if(i<40){
                ids.push(selection[i]);
                self.$refs['table-box'].toggleRowSelection(selection[i],true);
              }
            }
            self.$set(self,'codeList',ids);
          })
          this.msgError('最多勾选40条')
        }else{
          this.$set(this,'codeList',selection.map(item => item));
        }
      },
      /*===记录勾选数据===
        需要再el-table 添加  :row-key="getRowKeys"
        需要在selection 添加 :reserve-selection="true"
      */
      getRowKeys(row) {
        return row.subId
      },
    },
  }
</script>

<style scoped lang="scss">
  .subject {
    flex:1;
    display: flex!important;
    flex-direction: column;
    overflow: hidden;
    box-shadow: none;
    margin:0;
    .subject-page {
      flex:1;
      display: flex;
      flex-direction: row;
      overflow: hidden;
      .left-subject-list {
        flex: 1;
        width: 1143px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.2);
        border-radius: 10px 10px 10px 10px;
        margin: 5px 7px 20px 10px;
        .page-content-box {
          .table-box{
            ::v-deep .el-input--medium .el-input__inner {
              height: 26px;
              line-height: 26px;
              width: 55px;
              text-align: center;
              padding: 0 10px;
            }
          }
        }
      }
    }
    ::v-deep .el-table__row {
      td:nth-child(1) {
        padding: 0;
      }
    }
    ::v-deep .el-table__row{
      cursor: pointer;
    }
  }
</style>
