<template>
  <div class="hoistManage">
    <div class="left">
      <div class="layout">
        <el-input placeholder="请输入关键字" prefix-icon="el-icon-search" v-model="keyWord" maxlength="30"
          style="margin: 10px 10px 10px 0;width: 80%;" @keydown.enter="searchData"></el-input>
        <el-button type="primary" plain @click="searchData">查询</el-button>
      </div>
      <div class="dev-box" v-if="isShow">
        <div :class="getStyle(item)" @click="sendParams(item.devCode, index)" v-for="(item, index) in devArr"
          :key="item.id">
          <img :src="dz_dev_img">
          <div class="layout dev-info">
            <div>{{ item.proName }}</div>
            <div>班组：{{ item.teamName }}</div>
            <div>班组长：{{ item.teamLeader }}-{{ item.leaderPhone }}</div>
            <div>{{ item.devName }}</div>
            <div>{{ item.devCode }}</div>
          </div>
        </div>
      </div>
      <div class="no-data-box layout" v-if="!isShow">
        <el-empty description="暂无数据"></el-empty>
      </div>
    </div>
    <div class="center">
      <div class="center-1">
        <img :src="dz_dev_warn_img" />
      </div>
      <div class="center-2 layout">
        <!-- 吊装视频播放 -->
        <iframe ref="iframePage" scrolling="no" frameborder="0" allowfullscreen="true"></iframe>
      </div>
    </div>
    <div class="right">
      <div class="dev-config layout" v-if="isShow2">
        <div class="jd-dev-info layout" v-for="item in jdDevArr" :key="item.devId">
          <div class="jd-dev-detail layout">
            <img :src="jd_dev_img" alt="近电感应设备" style="margin-right: 5px;">
            <span>{{ item.devName }}</span>
          </div>
          <div class="jd-dev-elec layout">
            <img :src="battery1" alt="电量" v-if="parseFloat(item.electricQuantity) == 100">
            <img :src="battery2" alt="电量"
              v-if="parseFloat(item.electricQuantity) < 100 && parseFloat(item.electricQuantity) >= 20">
            <img :src="battery3" alt="电量" v-if="parseFloat(item.electricQuantity) < 20">
            <span style="margin-left: 5px;">{{ item.electricQuantity }}%</span>
          </div>
          <div class="jd-dev-img layout"><img :src="config" alt="配置" @click.stop="clickJdDev(item.devId)"></div>
        </div>
      </div>
      <div class="no-data-box layout" v-if="!isShow2">
        <el-empty description="暂无数据"></el-empty>
      </div>
      <div class="warn-info">
        <el-table :data="tableData" style="width: 100%" max-height="400">
          <el-table-column prop="devName" label="设备名称" align="center">
          </el-table-column>
          <el-table-column prop="warnTime" label="告警时间" align="center">
          </el-table-column>
          <el-table-column prop="warnContent" label="告警内容" align="center">
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog title="近电感应配置" :visible.sync="dialogVisible" :append-to-body="true" width="700px"
      @close="closeConfigItem">
      <el-form ref="form" :model="form" :rules="rules">
        <div class="form-box">
          <div v-for="(data, index) in form.configItems" :key="index">
            <h3>配置{{ index + 1 }}</h3>
            <el-form-item label="线路属性">
              <el-radio-group v-model="data.configType">
                <el-radio v-for="item in configTypeArr" :label="item.id" :key="item.id"
                  @change="chooseConfigType(index, data.configType)">{{ item.name }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="电压等级">
              <el-radio-group v-model="data.voltageLevel" v-if="data.configType === 'communication'">
                <el-radio v-for="item in jlArr" :label="item.id" :key="item.id">{{ item.name }}</el-radio>
              </el-radio-group>
              <el-radio-group v-model="data.voltageLevel" v-if="data.configType === 'direct_current'">
                <el-radio v-for="item in zlArr" :label="item.id" :key="item.id">{{ item.name }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="报警距离" :prop="'configItems.' + index + '.distance'" :rules="[
              {
                required: true, message: '报警距离不能为空', trigger: 'blur'
              },
              {
                pattern: /^(?:100(?:\.0{1,2})?|[1-9][0-9]?(?:\.\d{1,2})?|1(?:\.\d{1,2})?)$/,
                message: '距离为（1-100米）区间内,最多保留两位小数',
                trigger: 'blur'
              }
            ]">
              <el-col :span="12">
                <el-input v-model="data.distance"></el-input>
              </el-col>
              <el-col :span="5" style="margin-left: 10px;"><el-button type="danger" plain
                  @click.prevent="removeConfig(data)"><i class="el-icon-delete"></i></el-button></el-col>
            </el-form-item>
            <hr>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button type="primary" @click="addConfigItem">添加配置</el-button>
        <el-button @click="closeConfigItem">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { getDzWarnList, getJdList, getLineStats, getVoltageLevelByLineStats, configJdDevice, getConfigJdDevice, getJdWarnList } from "@/api/construction/manage/hoistManage.js";
import dz_dev_img from "@/assets/images/dz_dev.png";
import dz_dev_warn_img from "@/assets/images/test.jpg";
import jd_dev_img from "@/assets/images/jd_dev.png";
export default {
  name: 'hoistManage',
  data() {
    return {
      keyWord: '',
      dz_dev_img: dz_dev_img,
      dz_dev_warn_img: dz_dev_warn_img,
      jd_dev_img: jd_dev_img,
      //保存左侧 吊装设备信息
      devArr: [],
      // 近电感应设备
      jdDevArr: [],
      // 吊装预警设备无数据时处理
      isShow: false,
      // 近电感应设备无数据时处理
      isShow2: false,
      // 线路属性配置
      configTypeArr: [],
      // 交流属性的电压等级
      jlArr: [],
      // 直流属性的电压等级
      zlArr: [],
      loading: false,
      //电量图标
      battery1: require('../../../../assets/images/battery1.png'),
      battery2: require('../../../../assets/images/battery2.png'),
      battery3: require('../../../../assets/images/battery3.png'),
      config: require('../../../../assets/images/config.png'),
      //右侧表格数据
      tableData: [],
      //对话框开关
      dialogVisible: false,
      //保存近电感应设置信息
      form: {
        devId: null,
        configItems: [],
      },
      // 表单校验
      rules: {},
      htmlContent: '/zhgd-ht/dz_video.html',
      nocheckStyle: ['dev-info-box', 'layout', 'nocheck'],
      checkStyle: ['dev-info-box', 'layout', 'check'],
      warnStyle: ['dev-info-box', 'layout', 'warn'],
    };
  },
  created() {
    this.laodDzWarnList();
    this.loadJdList();
    this.loadJdWarnList();
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.iframePage.src = this.htmlContent;
    })
  },
  methods: {
    /* 吊装设备点击赋值 */
    getStyle(item) {
      if (item.status === "check") {
        return this.checkStyle;
      } else if (item.status === "warn") {
        return this.warnStyle;
      } else {
        return this.nocheckStyle;
      }
    },
    /* 向吊装视频传递参数 */
    sendParams(devCode, index) {
      this.devArr.forEach(item => {
        item.status = 'nocheck'
      })
      this.devArr[index].status = 'check'
      // 刷新dom
      this.$forceUpdate();
      this.$refs.iframePage.contentWindow.postMessage({ devCode: devCode }, '*');
    },
    /* 加载吊装预警设备列表 */
    laodDzWarnList() {
      let params = {
        'keyWord': this.keyWord
      };
      getDzWarnList(params).then((res) => {
        const data = res.data
        this.devArr = data;
        if (data && data.length > 0) {
          this.isShow = true;
        } else {
          this.isShow = false;
        }
      }).catch(() => { })
    },
    /* 加载近电感应设备 */
    loadJdList() {
      let params = {};
      getJdList(params).then((res) => {
        const data = res.data
        this.jdDevArr = data;
        if (data && data.length > 0) {
          this.isShow2 = true;
        } else {
          this.isShow2 = false;
        }
      }).catch(() => { })
    },
    /* 加载近电感应设备预警信息 */
    loadJdWarnList() {
      let params = {};
      getJdWarnList(params).then((res) => {
        const data = res.data
        this.tableData = data;
      }).catch(() => { })
    },
    /* 加载线路属性 */
    async loadLineStats() {
      let loading = this.$loading({
        lock: true,
        text: "数据加载中，请稍候...",
        background: 'rgba(0,0,0,0.2)'
      })
      // this.loading = true;
      let params = {};
      await getLineStats(params).then((res) => {
        const data = res.data
        this.configTypeArr = data;
      }).catch(() => { })
      await this.loadVoltageLevelByLineStats(this.configTypeArr[0].id);
      await this.loadVoltageLevelByLineStats(this.configTypeArr[1].id);
      await this.loadConfigJdDevice();
      if (this.form.configItems.length === 0) {
        this.form.configItems.push({
          configType: this.configTypeArr[0].id,
          voltageLevel: this.jlArr[0].id,
          distance: 1,
          key: Date.now()
        });
      }
      loading.close();
      // this.loading = false;
      this.dialogVisible = true;
    },
    /* 线路属性的电压等级 */
    async loadVoltageLevelByLineStats(param) {
      let params = {
        id: param
      };
      await getVoltageLevelByLineStats(params).then((res) => {
        const data = res.data
        if (param === 'communication') { // 交流
          this.jlArr = data;
        } else if (param === 'direct_current') { // 直流
          this.zlArr = data;
        }
      }).catch(() => { })
    },
    /* 加载近电感应设备配置 */
    async loadConfigJdDevice() {
      const params = {
        'devId': this.form.devId
      }
      await getConfigJdDevice(params).then((res) => {
        const data = res.data
        data.forEach((item, index) => {
          this.form.configItems.push({
            configType: item.configType,
            voltageLevel: item.voltageLevel,
            distance: item.distance,
            key: Date.now()
          })
        })
      }).catch(() => { })
    },
    searchData() {
      this.laodDzWarnList();
    },
    /* 近电感应设备点击事件 */
    clickJdDev(id) {
      this.form.devId = id;
      this.loadLineStats();
    },
    // 添加配置
    addConfigItem() {
      if (this.form.configItems.length >= 10) {
        return this.$message({
          message: '最多添加十个配置',
          type: 'warning'
        });
      }
      this.form.configItems.push({
        configType: this.configTypeArr[0].id,
        voltageLevel: this.jlArr[0].id,
        distance: 1,
        key: Date.now()
      });
    },
    // 删除配置
    removeConfig(item) {
      if (this.form.configItems.length === 1) {
        return this.$message({
          message: '最少保留一个配置',
          type: 'warning'
        });
      }
      var index = this.form.configItems.indexOf(item)
      if (index !== -1) {
        this.form.configItems.splice(index, 1)
      }
    },
    // 关闭配置
    closeConfigItem() {
      this.form.configItems.splice(0);
      this.form.devId = null;
      this.dialogVisible = false;
    },
    // 线路属性切换
    chooseConfigType(index, val) {
      if (val === 'communication') { // 交流
        this.form.configItems[index].voltageLevel = this.jlArr[0].id
      } else if (val === 'direct_current') { // 直流
        this.form.configItems[index].voltageLevel = this.zlArr[0].id
      }

    },
    //验证对话框确认按钮
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const flag = this.hasDuplicates();
          if (flag) {
            return this.$message({
              message: '存在相同配置',
              type: 'warning'
            });
          }
          const obj = {
            'devId': this.form.devId,
            'configItems': this.form.configItems
          }
          configJdDevice(obj).then((res) => {
            this.$modal.msgSuccess(res.msg);
            this.closeConfigItem();
          }).catch((res) => { });
        }
      });
    },

    // 判断是否存在相同数据
    hasDuplicates() {
      const configTypes = new Set();
      const voltageLevels = new Set();
      const distances = new Set();
      for (const item of this.form.configItems) {
        if (configTypes.has(item.configType) && voltageLevels.has(item.voltageLevel) && distances.has(item.distance)) {
          return true;
        }
        configTypes.add(item.configType);
        voltageLevels.add(item.voltageLevel);
        distances.add(item.distance);
      }
      return false;
    },
    //搜索框点击
    searchClick() {
      console.log(this.keyword)
    },
    //左侧设备点击
    hoistClick(id) {
      alert(id)
    },

    //对话框，线路类型单选按钮监听
    lineTypeRadioChange(item, index) {
    },
    //对话框，电压等级单选按钮监听
    levelRadioChange(item, index) {
    },
    //对话框，添加配置
    addHoistSetUp() {
      let json = { lineType: '1', level: '1', distance: 10 };
      this.hoistSetUpData.push(json)
    },
    //对话框，删除配置
    delHoistSetUp(index) {
      this.hoistSetUpData.splice(index, 1);
    },

    //验证对话框关闭
    provingDialogClose() {
      this.dialogVisible = false;
    },
    //验证对话框确认按钮
    provingDialogConfirm() {
      this.dialogVisible = false;
    }
  }
};
</script>

<style>
.hoistManage {
  width: 100%;
  height: 80vh;
  background-color: #fff;
  box-shadow: 10px 10px 5px #000;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.layout {
  display: flex;
  align-items: center;
  justify-content: start;
}

.hoistManage .left {
  width: 20%;
  height: 100%;
}

.dev-box {
  width: 100%;
  height: calc(100% - 50px);
  overflow-y: auto;
}

.dev-info-box {
  width: 100%;
  margin: 0 0 4% 0;
  height: 160px;
  border-radius: 6px;
  font-size: 15px;
  justify-content: space-evenly;
  align-items: start;
  align-items: center;
  letter-spacing: 1px;
  box-sizing: border-box;
  cursor: pointer;
}

.nocheck {
  border: 1px solid #cccccc;
}

.check {
  border: 1px solid green;
}

.warn {
  border: 1px solid red;
}

.dev-info {
  width: calc(100% - 104px);
  height: 100%;
  flex-direction: column;
  align-items: start;
  justify-content: space-evenly;
}

.no-data-box {
  width: 100%;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.hoistManage .center {
  width: 56%;
  height: 100%;
}

.hoistManage .center-1 {
  width: 100%;
  height: 40%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center center !important;
}

.hoistManage .center-1 img {
  background-position: center center !important;
  background-size: 100% 100%;
}

.hoistManage .center-2 {
  width: 100%;
  height: 60%;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
}

.hoistManage .center-2 iframe {
  width: 100%;
  height: 100%;
  border: none;
}

#VideoRealPlayBox {
  width: 100%;
  height: 100%;
}

.dz-video-box {
  width: 100%;
  height: 24%;
}

.dz-video-box>div {
  width: 40px;
  height: 100%;
  border-left: 1px solid #4688BB;
  border-top: 1px solid #4688BB;
  border-bottom: 1px solid #4688BB;
}

.ball-content {
  width: calc(100% - 40px);
  height: 100%;
  pointer-events: none;
  object-fit: fill;
}

.hoistManage .right {
  width: 20%;
  height: 100%;
}

.dev-config {
  width: 100%;
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #cccccc;
  border-radius: 6px;
  flex-direction: column;
}

.jd-dev-info {
  width: 100%;
  min-height: 50px;
  flex-direction: row;

}

.jd-dev-detail {
  width: calc(100% - 130px);
  height: 100%;
}

.jd-dev-elec {
  width: 100px;
  height: 100%;
  align-items: center;
  justify-content: flex-start;
}

.jd-dev-img {
  width: 30px;
  height: 100%;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.warn-info {
  width: 100%;
  margin-top: 10px;
  min-height: calc(100% - 300px);
  max-height: calc(100% - 150px);
  overflow-y: auto;
}

.form-box {
  min-height: 12vh;
  max-height: 70vh;
  overflow-y: auto;
}
</style>
