<template>
    <div class="newAssociatedPage">
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="form-box">
        <el-form-item label="关键字" prop="name">
          <el-input
            style="width:160px;"
            maxlength="10"
            v-model="queryParams.searchValue"
            placeholder="实验室"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="安全分类" prop="typeId">
          <el-select v-model="queryParams.typeId" placeholder="请选择安全分类" style="width:160px;">
            <el-option
              v-for="dict in typeList"
              :key="dict.id"
              :label="dict.typeName"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安全分级" prop="level">
          <el-select v-model="queryParams.level" placeholder="请选择安全分级" style="width:160px;">
            <el-option
              v-for="item in levelList"
              :key="item.id"
              :label="item.classifiedName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联时间" prop="senseState">
          <el-date-picker
            :clearable="false"
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item style="float: right;">
          <el-col :span="1.5">
            <p class="reset-button-one"
               @click="backButton"
               style="float: right;"
            >返回</p>
            <p class="add-button-one-90"
               @click="handleAdd(1)"
               style="float: right;margin-right:20px;"
            >新增</p>
          </el-col>
        </el-form-item>
        <el-form-item>
          <p class="inquire-button-one" style="margin-right:10px;" @click="handleQuery">查询</p>
          <p class="reset-button-one" @click="resetQuery">重置</p>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" border :data="tableData">
        <el-table-column label="实验室" align="left" prop="name" width="300" show-overflow-tooltip/>
        <el-table-column label="安全分类" align="left" prop="typeName" width="140">
          <template slot-scope="scope">
            <span v-for="(item,index) in typeList" :key="index" v-if="item.id == scope.row.typeId">{{item.typeName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="安全分级" align="left" prop="leveName" width="140">
          <template slot-scope="scope">
            <span v-for="(item,index) in levelList" :key="index" v-if="item.id == scope.row.level">{{item.classifiedName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="危险源" align="left" prop="labSensorHazardRelationsList" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="margin-right:10px;" v-for="(item,index) in scope.row.labSensorHazardRelationsList" :key="index">
              {{item.hazardName}} - {{item.sensorName}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="关联时间" align="left" prop="relationTime" width="200"/>
        <el-table-column label="状态" align="left" prop="senseState" width="140"/>
        <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="100">
          <template slot-scope="scope">
            <div class="table-button-box">
              <p class="table-button-null"></p>
              <p class="table-button-p" @click="handleDelete(scope.row)">移除</p>
              <p class="table-button-null"></p>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination :page-sizes="[20, 30, 40, 50]"
                  v-show="total>0"
                  :total="total"
                  layout="total, prev, pager, next, sizes, jumper"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList"
      />
      <el-dialog title='关联实验室' v-if="dialogAssociatedOpen" :visible.sync="dialogAssociatedOpen" width="1200px">
        <div style="height: 600px;overflow: hidden;display: flex;flex-direction: column;flex:1;">
          <el-form :model="param" ref="queryForm" :inline="true" label-width="80px">
            <el-form-item label="关键字" prop="searchValue">
              <el-input
                maxlength="10"
                v-model="param.searchValue"
                placeholder="实验室"
                clearable
                size="small"
              />
            </el-form-item>
            <el-form-item label="安全分类" prop="typeId" label-width="80px">
              <el-select v-model="param.typeId" placeholder="请选择安全分类" clearable size="small">
                <el-option
                  v-for="dict in typeList"
                  :key="dict.id"
                  :label="dict.typeName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="安全分级" prop="level" label-width="80px">
              <el-select v-model="param.level" placeholder="请选择安全分级" clearable size="small">
                <el-option
                  v-for="dict in levelList"
                  :key="dict.id"
                  :label="dict.classifiedName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <p class="inquire-button-one" style="margin-right:10px;" @click="onSearch">查询</p>
              <p class="reset-button-one" @click="resetForm">重置</p>
            </el-form-item>
          </el-form>
          <!--<div style="display: flex;background: rgb(202,229,253);height:40px;line-height:40px;font-size:16px;padding:0 82px;margin-bottom:20px;">-->
            <!--<p style="margin-right:24px;">已选择 <span style="color:#0183FA;">{{allNum}}</span> 项</p>-->
            <!--<p style="color:#0183FA;cursor: pointer;" @click="allButton(1)">全选本页</p>-->
            <!--<p style="color:#0183FA;margin:0 32px 0 30px;cursor: pointer;"  @click="allButton(2)">选择全部</p>-->
          <!--</div>-->
          <el-table ref="table" v-loading="loading" border :data="dialogTableData" @selection-change="handleSelectionChange" :row-key="getRowKeys">
            <el-table-column type="selection" width="55" :reserve-selection="true" align="center" />
            <el-table-column label="实验室" width="220" align="center" prop="name" show-overflow-tooltip/>
            <el-table-column label="安全分类" width="100" align="center" prop="typeId" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-for="(item,index) in typeList" :key="index" v-if="item.id == scope.row.typeId">{{item.typeName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="安全分级" width="100" align="center" prop="level" show-overflow-tooltip>
              <template slot-scope="scope">
                <span v-for="(item,index) in levelList" :key="index" v-if="item.id == scope.row.level">{{item.classifiedName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="危险源" align="left">
              <template slot-scope="scope">
                <div style="margin-bottom:10px;">
                  <div v-for="(item,index) in scope.row.buttonList" :key="index"
                    style="display: inline-block;padding:0 10px;border:1px solid #E0E0E0;margin:10px 10px 0 0;">
                    <span style="line-height:40px;font-size:14px;">{{item.hazardSubjectName}}-{{item.sensorName}}</span>
                    <span class="el-icon-circle-close" @click="delMinObj(scope.row.buttonList,index)"
                          style="cursor: pointer;width:14px;height:14px;margin-left:10px;margin-top:14px;color:#666;"></span>
                  </div>
                  <p v-if="scope.row.buttonType == 0"
                     @click="addObjButton(1,scope.row)"
                    style="color:#0183FA;font-size:16px;border:1px solid #0183FA;
                border-radius:4px;width:88px;height:30px;line-height:30px;
                display: inline-block;margin:5px 0 0 10px;text-align: center;cursor: pointer;">新增危险源</p>
                  <div v-if="scope.row.buttonType == 1"
                    style="display: flex;margin-top:10px;">
                    <el-select v-model="scope.row.hazardSubjectId" placeholder="请选择危险源"
                               @change="(val)=>hardwareChange(val,scope.row)"
                               style="width:168px;">
                      <el-option
                        v-for="dict in scope.row.labHazardSubVOList"
                        :key="dict.xyId"
                        :label="dict.label"
                        :value="dict.xyId"
                      ></el-option>
                    </el-select>
                    <p style="width:30px;text-align: center;line-height:40px;">-</p>
                    <el-select v-model="scope.row.sensorId" placeholder="请选择传感器"
                               @change="(val)=>sensorChange(val,scope.row)"
                               style="width:168px;">
                      <el-option
                        v-for="dict in scope.row.labSensorList"
                        :key="dict.id"
                        :label="dict.name"
                        :value="dict.id"
                      ></el-option>
                    </el-select>
                    <p style="color:#CCCCCC;font-size:16px;border:1px solid #E0E0E0;
                  border-radius:4px;width:80px;height:30px;line-height:30px;
                  display: inline-block;margin:5px 0 0 10px;text-align: center;cursor: pointer;" @click="addObjButton(2,scope.row)">取消</p>
                    <p style="color:#0183FA;font-size:16px;border:1px solid #0183FA;
                  border-radius:4px;width:80px;height:30px;line-height:30px;
                  display: inline-block;margin:5px 0 0 10px;text-align: center;cursor: pointer;" @click="addObjButton(3,scope.row)">确定</p>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="dialogTotal>0"
            :total="dialogTotal"
            :page.sync="param.pageNum"
            :limit.sync="param.pageSize"
            @pagination="getList"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <div style="display: flex">
            <p style="flex:1;"></p>
            <p style="cursor: pointer;border-radius:6px;width:70px;line-height:30px;font-size:12px;text-align:center;margin-right:17px;color:#999999;background:#E0E0E0;" @click="handleAdd(2)">取消</p>
            <p style="cursor: pointer;border-radius:6px;width:70px;line-height:30px;font-size:12px;text-align:center;color:#fff;background:#0045AF;" @click="handleAdd(3)">确定</p>
            <p style="flex:1;"></p>
          </div>
        </div>
      </el-dialog>
    </div>
</template>

<script>
  import { optionHardware } from "@/api/laboratory/hardware";
  import { optionSensor } from "@/api/laboratory/sensor";
  import { listClassifiedAll } from "@/api/laboratory/classified";
  import { listClasstypeAll } from "@/api/laboratory/classtype";
  import { getLabRiskPlanJoinSub,getLabRiskPlanNoJoinSub,deleteRiskPlanJoinSub,riskPlanJoinSub,riskPlanBatchJoinSub } from "@/api/evacuation3_2/index";
  export default {
    name: 'newAssociatedPage',
    props:{
      associationData:{},
    },
    data() {
      return {
        loading:false,
        levelList:[],
        typeList:[],
        // 查询参数
        dateRange:[],
        queryParams:{
          pageNum: 1,
          pageSize:20,
          searchValue:"",

        },
        total:0,
        tableData:[],
        /***************关联危险源开始****************/
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 查询数据
        param:{
          pageNum:1,
          pageSize:10,
        },
        dialogTotal:5,
        //关联实验室
        dialogAssociatedOpen:false,
        dialogTableData:[],
        //传感器
        sensorList:[],
        sensorListData:[],
        //设备
        hardwareList:[],
        /***************关联危险源结束****************/
        allNum:0,
      }
    },
    created(){
      this.getListAll();
    },
    mounted(){
      this.getList();
    },
    methods:{
      getListAll(){
        optionSensor({}).then(response => {
          this.sensorList = response.data;
          this.sensorListData = JSON.parse(JSON.stringify(response.data))
        });
        optionHardware({}).then(response => {
          this.hardwareList = response.data;
        });
        listClassifiedAll().then(response=>{
          if(response.code==200){
            this.levelList=response.data
          }
        })
        listClasstypeAll().then(response=>{
          if(response.code==200){
            this.typeList=response.data;
          }
        });
      },
      //新增关联实验室弹窗
      handleAdd(type){
        let self = this;
        if (type == 1){
          this.resetForm();
          this.$set(this,'allNum',0);
          this.$set(this,'dialogAssociatedOpen',true);
        }else if(type == 2){
          this.$set(this,'dialogAssociatedOpen',false);
        }else if(type == 3){
          let list = JSON.parse(JSON.stringify(this.$refs.table.selection));
          if(!list[0]){
            this.msgError('请勾选需要关联的实验室');
            return
          }
          let newList = [];
          for(let i=0;i<list.length;i++){
            let obj = {
              riskPlanId:self.associationData.id,
              subjectId:list[i].id,
              labSensorHazardRelations:list[i].buttonList,
            }
            newList.push(obj);
          }
          let newObj = {
            riskPlanId:self.associationData.id,
            yesOrNo:0,
            labRiskPlanSubVos:newList,
          }
          riskPlanJoinSub(newObj).then(response => {
            if(response.data.ifConflict == 1){
              self.$confirm(response.data.message, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(function() {
                let newData =  {
                  riskPlanId:self.associationData.id,
                  yesOrNo:1,
                  labRiskPlanSubVos:newList,
                }
                riskPlanJoinSub(newData).then(response => {
                  self.msgSuccess(response.msg);
                  self.resetQuery();
                  self.$set(self,'dialogAssociatedOpen',false);
                });
              }).then(() => {
              }).catch(() => {});
            }else{
              self.msgSuccess(response.msg);
              self.resetQuery();
              self.$set(self,'dialogAssociatedOpen',false);
            }
          });
        }
      },
      //查询
      onSearch(){
        this.$set(this.param,'pageNum',1);
        this.getLabRiskPlanNoJoinSub();
      },
      //重置
      resetForm(){
        this.$set(this,'param',{
          pageNum:1,
          pageSize:20,
          searchValue:"",
          typeId:"",
          level:"",
        });
        this.$set(this,'dialogTotal',0);
        this.$set(this,'dialogTableData',[]);
        this.onSearch();
      },
      //获取未关联实验室列表
      getLabRiskPlanNoJoinSub(){
        this.$set(this.param,'riskPlanId',this.associationData.id);
        getLabRiskPlanNoJoinSub(this.param).then(response => {
          for(let i=0;i<response.rows.length;i++){
            response.rows[i].buttonType = 0;
            response.rows[i].buttonList = [];
            response.rows[i].sensorId = null;
            response.rows[i].sensorName = null;
            response.rows[i].hazardSubjectId = null;
            response.rows[i].hazardSubjectName = null;
          }
          this.dialogTableData = response.rows;
          this.dialogTotal = response.total;
          this.loading = false;
        });
      },
      //新增对象至选中实验室
      addObjButton(type,item){
        if(type == 1){
          if(item.buttonList.length>8){
            this.msgError('最多添加9项')
            return
          }
          item.buttonType = 1;
        }else if(type == 2){
          item.buttonType = 0;
        }else if(type == 3){
          console.log('sensorId',item.sensorId)
          console.log('hazardSubjectId',item.hazardSubjectId)
          if(item.hazardSubjectId == null){
            this.msgError('请选择要添加的危险源')
            return
          }
          if(item.sensorId == null){
            this.msgError('请选择要添加的传感器')
            return
          }
          let obj = {
            sensorId:item.sensorId,
            sensorName:item.sensorName,
            hazardSubjectId:item.hazardSubjectId,
            hazardSubjectName:item.hazardSubjectName,
          };
          for(let i=0;i<item.buttonList.length;i++){
            if(item.buttonList[i].sensorId == item.sensorId && item.buttonList[i].hazardSubjectId == item.hazardSubjectId){
              this.msgError('该条件已存在');
              return
            }
          }
          item.buttonList.push(obj);
          item.sensorId = null;
          item.sensorName = null;
          item.hazardSubjectId = null;
          item.hazardSubjectName = null;
          item.buttonType = 0;
          this.$forceUpdate();
        }
      },
      //删除列表内的对象
      delMinObj(list,index){
        list.splice(index,1)
        this.$forceUpdate();
      },
      sensorChange(val,row){
        console.log('传感器')
        for(let i=0;i<row.labSensorList.length;i++){
          if(row.labSensorList[i].id == val){
            row.sensorId = row.labSensorList[i].id;
            row.sensorName = row.labSensorList[i].name;
          }
        }
        this.$forceUpdate();
      },
      hardwareChange(val,row){
        console.log('危险源')
        for(let i=0;i<row.labHazardSubVOList.length;i++){
          if(row.labHazardSubVOList[i].xyId == val){
            row.hazardSubjectId = row.labHazardSubVOList[i].xyId;
            row.hazardSubjectName = row.labHazardSubVOList[i].label;
          }
        }
        this.$forceUpdate();
      },
      //删除关联实验室
      handleDelete(item){
        let self = this;
        this.$confirm('您确定要移除该实验室吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          let obj = {
            riskPlanId:self.associationData.id,
            subjectId:item.id
          }
          deleteRiskPlanJoinSub(obj).then((response) => {
            self.msgSuccess(response.msg)
            self.resetQuery();
          });
        }).then(() => {
        }).catch(() => {});
      },
      //查询
      handleQuery(){
        this.$set(this.queryParams,'pageNum',1);
        if(this.dateRange[0]){
          this.queryParams.startDate = this.dateRange[0]
          this.queryParams.endDate = this.dateRange[1]
        }else {
          this.queryParams.startDate = null
          this.queryParams.endDate = null
        }
        this.getList();
      },
      //重置
      resetQuery(){
        this.$set(this,'queryParams',{
          pageNum:1,
          pageSize:20,
          searchValue:"",
          typeId:"",
          level:"",
        });
        this.$set(this,'dateRange',[]);
        this.$set(this,'total',0);
        this.$set(this,'tableData',[]);
        this.handleQuery();
      },
      /** 查询列表 */
      getList() {
        let self = this;
        this.loading = true;
        this.$set(this.queryParams,'riskPlanId',this.associationData.id);
        getLabRiskPlanJoinSub(this.queryParams).then(response => {
          for(let i=0;i<response.rows.length;i++){
            for(let o=0;o<self.typeList.length;o++){
              if(response.rows[i].typeId == self.typeList[o].id){
                response.rows[i].typeName = self.typeList[o].typeName;
              }
            }
            for(let o=0;o<self.levelList.length;o++){
              if(response.rows[i].level == self.levelList[o].id){
                response.rows[i].leveName = self.levelList[o].classifiedName;
              }
            }
            response.rows[i].labSensorHazardRelationsList = [];
            for(let o=0;o<response.rows[i].labSensorHazardRelations.length;o++){
              let obj = {
                hazardName:response.rows[i].labSensorHazardRelations[o].hazardName,
                sensorName:response.rows[i].labSensorHazardRelations[o].sensorName,
              }
              response.rows[i].labSensorHazardRelationsList.push(obj);
            }
          }
          this.tableData = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      //返回
      backButton(){
        if(this.associationData.type == 1){
          this.$parent.tableClickButton(6)
        }else{
          this.$parent.tableClickButton(5)
        }
      },
      /*===记录勾选数据===
        需要再el-table 添加  :row-key="getRowKeys"
        需要在selection 添加 :reserve-selection="true"
      */
      getRowKeys(row) {
        return row.id
      },
      //勾选
      handleSelectionChange(selection){
        this.$set(this,'allNum',selection.length);
        // console.log('selection',selection)
      },
      allButton(type){
        let self = this;
        if(type == 1){
          let list = [];
          for(let i=0;i<self.dialogTableData.length;i++){
            list.push(self.dialogTableData[i].id);
          }
          let obj = {
            riskPlanId:self.associationData.id,
            subjectIds:list+''
          }
          riskPlanBatchJoinSub(obj).then(response => {
            this.msgSuccess(response.msg);
            this.resetQuery();
            this.$set(this,'dialogAssociatedOpen',false);
          });
        }else if(type == 2){
          let obj = {
            riskPlanId:self.associationData.id,
            searchValue:self.param.searchValue,
            typeId:self.param.typeId,
            level:self.param.level,
            subjectIds:'-1'
          };
          riskPlanBatchJoinSub(obj).then(response => {
            this.msgSuccess(response.msg);
            this.resetQuery();
            this.$set(this,'dialogAssociatedOpen',false);
          });
        }
      },
    },
  }
</script>

<style scoped lang="scss">
  .newAssociatedPage{
    flex: 1;
    display: flex !important;
    flex-direction: column;
    overflow: hidden;
    padding:20px;
    p {
      margin: 0;
      font-weight: 500;
    }
  }
</style>
