<template>
  <div class="newAssociatedPage">
    <div class="page-form-title-box">
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="form-box">
        <el-form-item label="" prop="searchValue">
          <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.typeId"
              :label="dict.typeName"
              :value="dict.typeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="level">
          <el-select v-model="queryParams.levelId" placeholder="请选择安全分级" style="width:160px;">
            <el-option
              v-for="item in levelList"
              :key="item.levelId"
              :label="item.levelName"
              :value="item.levelId">
            </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="page-submit-common-style-button"
               @click="handleAdd(1)"
               style="float: right;"
            >新增</p>
            <p class="page-reset-common-style-button"
               @click="backButton"
               style="float: right;margin-right:20px;"
            >返回</p>
          </el-col>
        </el-form-item>
        <el-form-item>
          <p class="page-inquire-common-style-button" style="margin-right:10px;" @click="handleQuery">查询</p>
          <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-content-box">
      <el-table class="table-box" v-loading="loading" border :data="tableData">
        <el-table-column label="实验室" align="left" prop="subName" width="300" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.subName}}{{scope.row.roomNum?'('+scope.row.roomNum+')':''}}</span>
          </template>
        </el-table-column>
        <el-table-column label="安全分类" align="left" prop="typeName" width="140"/>
        <el-table-column label="安全分级" align="left" prop="levelName" width="140"/>
        <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.labHazardSensorRelationVos"
                  :key="index">
              {{item.anotherName}} - {{item.sersorDeviceName}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="关联时间" align="left" prop="createTime" width="200">
          <template slot-scope="scope">
            {{parseTime(scope.row.createTime,"{y}-{m}-{d} {h}:{i}") }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="left" prop="status" width="140">
          <template slot-scope="scope">
            <span>{{scope.row.status == 1?'正常':'失效'}}</span>
          </template>
        </el-table-column>
        <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" v-if="scope.row.adminId == meUserId" @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.page"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList"
      />
    </div>
    <!--关联弹窗-->
    <el-dialog title='关联实验室' v-if="dialogAssociatedOpen" :visible.sync="dialogAssociatedOpen"
               append-to-body width="1200px" :close-on-click-modal="false">
      <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.typeId"
                :label="dict.typeName"
                :value="dict.typeId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="levelId" label-width="80px">
            <el-select v-model="param.levelId" placeholder="请选择安全分级" clearable size="small">
              <el-option
                v-for="dict in levelList"
                :key="dict.levelId"
                :label="dict.levelName"
                :value="dict.levelId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <p class="page-inquire-common-style-button" style="margin-right:10px;" @click="onSearch">查询</p>
            <p class="page-reset-common-style-button" @click="resetForm">重置</p>
          </el-form-item>
        </el-form>
        <div class="page-content-box" style="padding:0;">
          <el-table class="table-box-no-height" 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="subName" show-overflow-tooltip/>
            <el-table-column label="安全分类" width="100" align="center" prop="typeName" show-overflow-tooltip/>
            <el-table-column label="安全分级" width="100" align="center" prop="levelName" show-overflow-tooltip/>
            <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 #666;color:#666;margin:10px 10px 0 0;border-radius:4px;">
                    <span style="line-height:40px;font-size:14px;">{{item.anotherName}} - {{item.sersorDeviceName}}</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:14px;border:1px solid #0183FA;
                  border-radius:4px;width:88px;height:40px;line-height:40px;
                  display: inline-block;margin:10px 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.hazardRelId" placeholder="请选择危险源"
                               class="table-date-select"
                               @change="(val)=>hardwareChange(val,scope.row)"
                               style="width:168px;">
                      <el-option
                        v-for="dict in scope.row.hazardList"
                        :key="dict.hazardRelId"
                        :label="dict.anotherName"
                        :value="dict.hazardRelId"
                      ></el-option>
                    </el-select>
                    <p style="width:30px;text-align: center;line-height:27px;">-</p>
                    <el-select v-model="scope.row.sersorDeviceId" placeholder="请选择传感器"
                               class="table-date-select"
                               @change="(val)=>sensorChange(val,scope.row)"
                               style="width:168px;">
                      <el-option
                        v-for="dict in scope.row.deviceList"
                        :key="dict.id"
                        :label="dict.deviceName"
                        :value="dict.id"
                      ></el-option>
                    </el-select>
                    <p style="color:#999;font-size:14px;border:1px solid #999;
                    border-radius:4px;width:80px;height:40px;line-height:40px;
                    display: inline-block;margin:0 0 0 10px;text-align: center;cursor: pointer;"
                       @click="addObjButton(2,scope.row)">取消</p>
                    <p style="color:#0183FA;font-size:14px;border:1px solid #0183FA;
                    border-radius:4px;width:80px;height:40px;line-height:40px;
                    display: inline-block;margin:0 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.page"
            :limit.sync="param.pageSize"
            @pagination="getNoList"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="handleAdd(2)">取消</p>
        <p class="dialog-footer-button-primary" @click="handleAdd(3)">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    laboratoryRiskPlanSubjectRelationRelationSubList,
    laboratoryRiskPlanSubjectRelationNoRelationSubList,
    laboratoryRiskPlanSubjectRelationRelationSub,
    laboratoryRiskPlanSubjectRelationBatchRelationSub,
    laboratoryRiskPlanSubjectRelationDelete
  } from '@/api/emergencyManagement/index'
  import { laboratoryClassTypeGetList, laboratoryClassLevelGetList } from '@/api/commonality/permission'

  export default {
    name: 'newAssociatedPage',
    props: {
      associationData: {}
    },
    data() {
      return {
        loading: false,
        levelList: [],
        typeList: [],
        // 查询参数
        dateRange: [],
        queryParams: {
          page: 1,
          pageSize: 20,
          searchValue: '',
          typeId:'',
          levelId:'',
        },
        total: 0,
        tableData: [],
        /***************关联危险源开始****************/
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 查询数据
        param: {
          page: 1,
          pageSize: 10,
          searchValue: '',
          typeId:'',
          levelId:'',
        },
        dialogTotal: 5,
        //关联实验室
        dialogAssociatedOpen: false,
        dialogTableData: [],
        //传感器
        sensorList: [],
        sensorListData: [],
        //设备
        hardwareList: [],
        /***************关联危险源结束****************/
        allNum: 0,
        /***** 当前用户userId *****/
        meUserId:localStorage.getItem('userId'),
      }
    },
    created() {
      // this.getListAll();
    },
    mounted() {
      this.getList()
      this.getListAll()
    },
    methods: {
      getListAll() {
        //获取实验室分级列表
        laboratoryClassLevelGetList({}).then(response => {
          if (response.code == 200) {
            this.$set(this, 'levelList', response.data)
          }
        })
        //获取实验室分类列表
        laboratoryClassTypeGetList({}).then(response => {
          if (response.code == 200) {
            this.$set(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 = [];
          let nullNum = 0;
          list.forEach((item) => {
            if(item.buttonList[0]){
              let obj = {
                riskPlanId:this.associationData.id,
                subId:item.subId,
                hazardSensorRelationBos:[],
              }
              item.buttonList.forEach((minItem) => {
                obj.hazardSensorRelationBos.push({
                  riskPlanId:this.associationData.id,
                  subId:item.subId,
                  hazardRelId:minItem.hazardRelId,
                  anotherName:minItem.anotherName,
                  sersorDeviceId:minItem.sersorDeviceId,
                  sersorDeviceName:minItem.sersorDeviceName,
                })
              })
              newList.push(obj);
            }else{
              nullNum++
              this.msgError(item.subName+'未配置危险源')
            }
          })
          if(nullNum != 0){
            return
          }
          laboratoryRiskPlanSubjectRelationBatchRelationSub(newList).then(response => {
            self.msgSuccess(response.message)
            self.resetQuery()
            self.$set(self, 'dialogAssociatedOpen', false)
          })
        }
      },
      //查询
      onSearch() {
        this.$set(this.param, 'page', 1)
        this.getNoList()
      },
      //重置
      resetForm() {
        this.$set(this, 'param', {
          page: 1,
          pageSize: 20,
          searchValue: '',
          typeId: '',
          levelId: ''
        })
        this.$set(this, 'dialogTotal', 0)
        this.$set(this, 'dialogTableData', [])
        this.onSearch()
      },
      //新增对象至选中实验室
      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) {
          if (item.hazardRelId == null) {
            this.msgError('请选择要添加的危险源')
            return
          }
          if (item.sersorDeviceId == null) {
            this.msgError('请选择要添加的传感器')
            return
          }
          let obj = {
            sersorDeviceId: item.sersorDeviceId,
            sersorDeviceName: item.sersorDeviceName,
            hazardRelId: item.hazardRelId,
            anotherName: item.anotherName
          }
          for (let i = 0; i < item.buttonList.length; i++) {
            if (item.buttonList[i].sersorDeviceId == item.sersorDeviceId && item.buttonList[i].hazardRelId == item.hazardRelId) {
              this.msgError('该条件已存在')
              return
            }
          }
          item.buttonList.push(obj)
          item.sersorDeviceId = null
          item.sersorDeviceName = null
          item.hazardRelId = null
          item.anotherName = null
          item.buttonType = 0
          this.$forceUpdate()
        }
      },
      //删除列表内的对象
      delMinObj(list, index) {
        list.splice(index, 1)
        this.$forceUpdate()
      },
      sensorChange(val, row) {
        //传感器
        for (let i = 0; i < row.deviceList.length; i++) {
          if (row.deviceList[i].id == val) {
            row.sersorDeviceId = row.deviceList[i].id
            row.sersorDeviceName = row.deviceList[i].deviceName
          }
        }
        this.$forceUpdate()
      },
      hardwareChange(val, row) {
        //危险源
        for (let i = 0; i < row.hazardList.length; i++) {
          if (row.hazardList[i].hazardRelId == val) {
            row.hazardRelId = row.hazardList[i].hazardRelId
            row.anotherName = row.hazardList[i].anotherName
          }
        }
        this.$forceUpdate()
      },
      //删除关联实验室
      handleDelete(item) {
        let self = this
        this.$confirm('您确定要移除该实验室吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          let obj = {
            id: item.id
          }
          laboratoryRiskPlanSubjectRelationDelete(obj).then((response) => {
            self.msgSuccess(response.message)
            self.resetQuery()
          })
        }).then(() => {
        }).catch(() => {
        })
      },
      //查询
      handleQuery() {
        this.$set(this.queryParams, 'page', 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', {
          page: 1,
          pageSize: 20,
          searchValue: '',
          typeId: '',
          levelId: ''
        })
        this.$set(this, 'dateRange', [])
        this.$set(this, 'total', 0)
        this.$set(this, 'tableData', [])
        this.handleQuery()
      },
      /** 查询列表 */
      getList() {
        let self = this
        this.$set(this, 'loading', true)
        let obj = JSON.parse(JSON.stringify(this.queryParams));
        obj.riskPlanId = this.associationData.id;
        if(this.dateRange[0]){
          obj.startTime = this.dateRange[0]+'T00:00:00'
          obj.endTime = this.dateRange[1]+'T23:59:59'
        }else{
          obj.startTime = "";
          obj.endTime = "";
        }
        this.$set(this.queryParams, 'riskPlanId', this.associationData.id)
        laboratoryRiskPlanSubjectRelationRelationSubList(obj).then(response => {
          this.$set(this, 'tableData', response.data.records)
          this.$set(this, 'total', response.data.total)
          this.$set(this, 'loading', false)
        })
      },
      getNoList() {
        this.$set(this, 'loading', true)
        let obj = JSON.parse(JSON.stringify(this.param));
        obj.riskPlanId = this.associationData.id;
        laboratoryRiskPlanSubjectRelationNoRelationSubList(obj).then(response => {
          response.data.records.forEach((item) => {
            item.buttonType = 0;
            item.buttonList = [];
          })
          this.$set(this, 'dialogTableData', response.data.records)
          this.$set(this, 'total', response.data.total)
          this.$set(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.subId
      },
      //勾选
      handleSelectionChange(selection) {
        this.$set(this, 'allNum', selection.length)
      },
    }
  }
</script>

<style scoped lang="scss">
  .newAssociatedPage {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
</style>
