<template>
  <div style="padding-top: 110px;width: 100%;height: calc(100% - 110px)">
    <div style="height: 50px;padding-left: 20px">
      <el-form ref="form" :inline="true" :model="searchForm" size="small">
        <el-form-item label="隧道">
          <el-select v-model="searchForm.area" placeholder="请选择隧道" clearable style="width: 120px" size="small" :popper-append-to-body="false">
            <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.deviceType" placeholder="请选择类型" clearable style="width: 120px" size="small" :popper-append-to-body="false">
            <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input v-model="searchForm.deviceId" placeholder="输入设备编号模糊查询" style="width: 180px" size="small"></el-input>

        </el-form-item>
        <el-form-item label="在线状态">
          <el-select v-model="searchForm.status" placeholder="请选择在线状态" clearable style="width: 150px" size="small" :popper-append-to-body="false">
            <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchTable">搜索</el-button>
          <el-button @click="clearSearch">重置</el-button>
<!--          <el-button type="primary" @click="handleAddClick(1)" icon="el-icon-plus" size="small"></el-button>-->
        </el-form-item>
      </el-form>
    </div>
    <div style="width: calc(100% - 40px);height: calc(100% - 50px);padding: 0 20px">
      <el-table
          :data="tableData"
          v-loading="loading"
          element-loading-text="加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.3)"
          tooltip-effect="dark"
          style="width: 100%;"
          height="calc(100% - 100px)">
        <el-table-column
            prop="deviceType"
            label="设备类型"
            :formatter="(row) => filedFomatter(row.deviceType, typeList)"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="deviceId"
            label="设备编号"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="area"
            label="隧道"
            :formatter="(row) => filedFomatter(row.area, areaList)"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="pileNumShow"
            label="桩号"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="direction"
            label="方向"
            :formatter="(row) => filedFomatter(row.direction, directionList)"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="lane"
            label="断面位置"
            :formatter="(row) => filedFomatter(row.lane, laneList)"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="status"
            label="在线状态"
            :formatter="(row) => filedFomatter(row.status, statusList)"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop=""
            label="当前执行方案"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="120">
          <template slot-scope="scope">

            <el-button @click="handleClick(scope.row)" type="text">控制</el-button>

          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right;margin-top: 30px">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="total,prev, pager, next, sizes"
            :total="totalCount">
        </el-pagination>
      </div>
    </div>

    <el-dialog top="10vh" style="pointer-events: auto;" :title="addOrUpdateTitle" :visible.sync="deviceDialogVisible" width="900px" :close-on-click-modal="false" v-if="deviceDialogVisible" @close="deviceClose">
      <div v-show="deviceLoading" style="position: absolute;z-index: 9999;left: calc(50% - 60px);top: 48%;background: #ce811b;padding: 10px 20px;border-radius: 5px;">正在发送指令...</div>

      <div v-loading="deviceLoading"
           element-loading-text=""
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.5)" >
        <div v-show="dataForm.deviceType!=22" style="min-height: 70px">
          <div style="display: inline-block;vertical-align: top;padding: 10px;border-right: 2px solid rgb(20 164 180);height: 50px"><img src="../../assets/images/device.png"></div>
          <div style="display: inline-block;vertical-align: top;padding: 0 30px;border-right: 2px solid rgb(20 164 180);min-width: 130px;height: 70px">
            <!--              <p style="font-size: 23px;color: #1AFFF7;margin-bottom: 10px">
                            {{ filedFomatter(dataForm.status,statusList) }}
                            <span v-show="!dataForm.status">暂无状态</span>
                          </p>-->
            <p v-show="dataForm.deviceType!=26 && dataForm.deviceType!=27 && dataForm.deviceType!=40 && dataForm.deviceType!=41 && dataForm.deviceType!=42 && dataForm.deviceType!=43" style="font-size: 22px;color: #1AFFF7;">
              状态：<span v-if="dataForm.taskName == -1">离线</span>
              <span v-else>{{ filedFomatter(dataForm.taskName,taskList) }}</span>

            </p>
          </div>
          <div style="display: inline-block;vertical-align: top;width: calc(100% - 350px)">
            <template v-if="dataForm.deviceType == '15'">
              <div style="height: 60px;padding: 10px 0 0 10px;overflow: auto">
                <div style="display: inline-block;vertical-align: top" v-html="templateInfoHtml"></div>
              </div>
            </template>
            <template v-else-if="dataForm.deviceType == '26'">
              <el-row style="min-height: 30px;font-size: 16px;padding: 20px 0 0 50px">
                <el-col :span="10">风向：{{ dataForm.direction26 }}</el-col>
                <el-col :span="11">风速：{{ dataForm.speed26 }}<span v-show="dataForm.speed26">(m/s)</span></el-col>
              </el-row>
            </template>
            <template v-else-if="dataForm.deviceType == '27'">
              <el-row style="min-height: 30px;font-size: 16px;padding: 20px 0 0 10px">
                <el-col :span="15">co 浓度值：{{ dataForm.co27 }}<span v-show="dataForm.co27">(mg/m3)</span></el-col>
                <el-col :span="9">vi 能见度：{{ dataForm.vi27 }}<span v-show="dataForm.vi27">(m)</span></el-col>
              </el-row>
            </template>
            <template v-else-if="dataForm.deviceType == '28'">
              <el-row style="min-height: 30px;font-size: 16px;padding: 20px 0 0 10px">
                <el-col :span="15">光强：{{ dataForm.light28 }}</el-col>
              </el-row>
            </template>
            <template v-else-if="dataForm.deviceType == '43'">
              <div style="min-height: 30px;font-size: 16px;padding: 20px">
                <p>水位高度：{{ dataForm.height43 }}<span v-show="dataForm.height43">(m)</span></p>
              </div>
            </template>
            <template v-else-if="dataForm.deviceType == '40' || dataForm.deviceType == '41' || dataForm.deviceType == '42'">
              <div style="min-height: 30px;font-size: 16px;padding: 0px 20px">
                <p v-for="item in iotKeyData">
                    <span style="display: inline-block;width: 100px">
                      {{item.name}}
                    </span>
                  <span v-for="item1 in item.data" style="display: inline-block;width: 100px">
                      {{item1.name}}
                    </span>
                </p>
              </div>
            </template>
            <template v-else>
              <div v-show="dataForm.taskName != -1" style="min-height: 30px;font-size: 16px;padding: 20px 0 0 10px">
                {{ filedFomatter(dataForm.taskName,taskList) }}
              </div>
            </template>
          </div>
        </div>
        <el-divider></el-divider>
        <el-row style="min-height: 280px">
          <el-col :span="8">
            <p style="margin-bottom: 10px;font-size: 16px"><span style="float: left;width: 10px;height: 10px;background: #2b6bb6;margin: 7px 5px 0 0"></span>设备基本信息</p>
            <el-descriptions title="" :column="1" :labelStyle="{'width': '80px','text-align': 'right','display':'block','color': '#D5E0EE'}" :contentStyle="{'width': '95%'}">
              <el-descriptions-item label="设备类型">{{ filedFomatter(dataForm.deviceType,deviceTypeList) }}</el-descriptions-item>
              <el-descriptions-item label="所属隧道">{{ filedFomatter(dataForm.area,areaList) }}</el-descriptions-item>
              <el-descriptions-item label="设备编号">{{ dataForm.deviceId }}</el-descriptions-item>
              <el-descriptions-item label="物联key">{{ dataForm.iotKey }}</el-descriptions-item>
              <el-descriptions-item label="所属方向">{{ filedFomatter(dataForm.direction,directionList) }}</el-descriptions-item>
              <el-descriptions-item label="桩号">{{ dataForm.pileNumShow }}</el-descriptions-item>
              <el-descriptions-item label="断面位置">{{ filedFomatter(dataForm.lane,laneList) }}</el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="16">
            <div style="width: calc(100% - 20px);border-left: 2px solid rgba(70,148,255,0.42);padding: 0 10px">
              <div v-if="dataForm.deviceType==22" style="width: 75%;height: 340px;background: black;margin-left: 5%">

                <flv-player :videoUrl="videoUrl"></flv-player>
              </div>
              <div v-else-if="dataForm.deviceType==26 || dataForm.deviceType==27 || dataForm.deviceType==43">
                <p style="margin-bottom: 10px;font-size: 16px"><span style="float: left;width: 10px;height: 10px;background: #2b6bb6;margin: 7px 5px 0 0"></span>设备控制
                </p>
                <div style="min-height: 200px;padding-bottom: 20px;padding-top: 10px">无</div>
              </div>
              <div v-else>
                <p style="margin-bottom: 10px;font-size: 16px"><span style="float: left;width: 10px;height: 10px;background: #2b6bb6;margin: 7px 5px 0 0"></span>设备控制
                  <el-button type="primary" @click="handleCommitClick(0)" size="mini" style="float: right;margin-right: 20px">发送</el-button>
                </p>
                <div style="min-height: 200px;padding-bottom: 20px;padding-top: 10px">
                  <div v-if="dataForm.deviceType == '12'" style="padding-left: 20px">
                    <el-row>
                      <el-col :span="3">控制：</el-col>
                      <el-col :span="21">
                        <el-radio-group v-model="dataForm.command" style="padding-top: 3px">
                          <el-radio :label="item.id" v-for="item in taskList">{{ item.name }}</el-radio>
                        </el-radio-group>
                      </el-col>
                    </el-row>
                    <el-row style="margin-top: 5px">
                      <el-col :span="3" style="line-height: 36px">亮度：</el-col>
                      <el-col :span="21">
                        <el-slider style="width: calc(100% - 100px)" v-model="dataFormBody.light"></el-slider>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-else-if="dataForm.deviceType == '15'" style="padding-left: 20px">
                    <el-row>
                      <el-col :span="3">控制：</el-col>
                      <el-col :span="21" class="temlCheckClass">
                        <!--                          <div v-for="item in infoBoardTemplateList">
                                                    <div style="height: 30px">
                                                      <p style="float: left"><el-radio v-model="dataFormBody.templateId" :label="item.id"><span></span></el-radio></p><p style="float: left" @input="addComment($event,item)" v-html="item.templateHtml"></p>
                                                    </div>
                                                  </div>-->
                        <el-checkbox-group v-model="textInfoList">
                          <div v-for="item in infoBoardTemplateList" :key="item.id" style="margin-bottom: 5px">
                            <el-checkbox :label="item.id">
                              <span @input="addComment($event,item)" v-html="item.templateHtml"></span><br>
                              <span style="color: #a8a8a8;font-size: 12px">宽:{{item.cmsWidth}} 高:{{item.cmsHeight}} 字体大小:{{item.fontSize}} 字体颜色:{{item.fontColor}}</span>
                            </el-checkbox>
                          </div>
                        </el-checkbox-group>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-else-if="dataForm.deviceType == '40' || dataForm.deviceType == '41' || dataForm.deviceType == '42'" style="padding-left: 20px">
                    <el-row style="margin-bottom: 5px">
                      <el-col :span="3">设备：</el-col>
                      <el-col :span="21">
                        <el-checkbox-group v-model="dataForm.iotKeys">
                          <el-checkbox v-for="item in iotKeyList" v-show="item.show" :label="item.id">{{ item.name }}</el-checkbox>
                        </el-checkbox-group>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="3">控制：</el-col>
                      <el-col :span="21">
                        <el-radio-group v-model="dataForm.command" style="padding-top: 3px">
                          <el-radio :label="item.id" v-for="item in taskList">{{ item.name }}</el-radio>
                        </el-radio-group>
                      </el-col>
                    </el-row>
                  </div>

                  <div v-else style="padding-left: 20px">
                    <el-row>
                      <el-col :span="3">控制：</el-col>
                      <el-col :span="21">
                        <el-radio-group v-model="dataForm.command" style="padding-top: 3px">
                          <el-radio :label="item.id" v-for="item in taskList">{{ item.name }}</el-radio>
                        </el-radio-group>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>

      </div>

      <!--        <span slot="footer" class="dialog-footer">
                <el-button @click="deviceDialogVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="addOrUpdateSub" size="small">确 定</el-button>
              </span>-->
    </el-dialog>

  </div>
</template>
<script>

import {addOrModDevice, deviceList, deviceStatus, getPlayAddressByPid, infoBoardTemplateList, iotControl} from "@/api";
import FlvPlayer from "@/components/FlvPlayer.vue";

export default {
  name: "index",
  components: {FlvPlayer},
  data() {
    return {
      areaList:window.config.areaList,
      typeList:window.config.deivceTypeList,
      statusList:window.config.statusList,
      laneList:window.config.laneList,
      directionList:window.config.directionList,
      deviceTypeList:window.config.deivceTypeList,
      colorList:[{id: 'c255000000000', name: '红'},{id: 'c255255000000', name: '黄'},{id: 'c000255000000', name: '绿'}],
      loading:false,
      searchForm: {},
      currentPage: 1,
      totalCount: 0,
      pageSize: window.config.pageSize,
      tableData: [],
      dataForm:{},
      deviceDialogVisible:false,
      addOrUpdateTitle:'',

      taskList: [],
      dataFormBody:{},
      infoBoardTemplateList:[],
      tempMap:{},
      statusTimer:null,
      deviceLoading:false,
      templateHtmlList:[],
      templateInfoHtml:'',
      videoForm : window.config.videoForm,
      videoUrl:''
    }
  },
  methods: {
    init() {
      var that = this;
      that.loadTable()
    },
    clearSearch(){     //重置查询条件
      var that = this;
      that.searchForm = {};
      that.searchTable();
    },
    searchTable(){
      this.currentPage = 1;
      this.totalCount = 0;
      this.loadTable();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.loadTable();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadTable();
    },
    loadTable(){
      var that = this;
      that.tableData = []
      that.loading = true;
      that.searchForm.needPage = 1;
      that.searchForm.pageSize = that.pageSize;
      that.searchForm.pageNumber = that.currentPage;
      deviceList(that.searchForm).then(res=>{
        that.loading = false;
        if (res.status == 200) {
          if (res.data.retCode == 0) {
            that.tableData = res.data.result
            that.totalCount = res.data.total
          } else {
            that.$message.warning(res.data.message);
          }
        }
      })
    },
    handleClick(row){
      var that = this;
      if(row.deviceType == '55' || row.deviceType == '56'){
        return '';
      }
      that.dataForm = {}
      that.textInfoList = [];
      that.dataFormBody = {}
      that.dataForm = JSON.parse(JSON.stringify(row));
      that.addOrUpdateTitle = that.filedFomatter(that.dataForm.area,that.areaList) + ' / ' + that.filedFomatter(that.dataForm.deviceType,that.deviceTypeList) + ' / ' + that.dataForm.deviceId;
      that.tempMap = {}
      that.templateInfoHtml = '';
      that.iotKeyList = [];
      that.taskList = window.config.taskEnum[that.dataForm.deviceType].taskList
      if(that.dataForm.refresh == '1'){
        that.deviceStatus()
      }

      if(that.dataForm.deviceType == '15') {
        if (that.dataForm.task) {
          var j = JSON.parse(that.dataForm.task)
          if (j.body) {
            j.dataFormBody = JSON.parse(j.body)
          }
          that.$set(that.dataForm,'taskName',j.command)

          that.loadinfoBoardTemplate(1,j.dataFormBody.textInfoList);
        }
        that.loadinfoBoardTemplate(0)
      }else if(that.dataForm.deviceType == '22') {
        if(that.dataForm.iotKey){
          that.videoForm.pid = that.dataForm.iotKey
          that.videoUrl = ''
          getPlayAddressByPid(that.videoForm).then(res => {
            if (res.status == 200) {
              if (res.data.ret == 0) {
                that.videoUrl = res.data.data.flv
              }else {
                that.$message.warning(res.data.message);
              }
            }
          })


        }
      }else if(that.dataForm.deviceType == '40' || that.dataForm.deviceType == '41' || that.dataForm.deviceType == '42') {
        that.$set(that.dataForm,'iotKeys',[])
        var arr = that.dataForm.iotKey.split('|')
        arr.forEach(item=>{
          var arr1 = item.split(':')
          var name = window.config.pumpMap[arr1[0]]
          var arr2 = arr1[1].split(',')
          if(arr2.length > 1){
            arr2.forEach((item2,i)=>{
              var json = {}
              if(arr1[0] == 'cd' || arr1[0] == 'ps' || arr1[0] == 'hs'){
                json.show = false
              }else{
                json.show = true
              }
              json.name = name + (i+1)
              json.id = arr1[0] + ':' +item2
              that.iotKeyList.push(json)
            })
          }else{
            var json = {}
            if(arr1[0] == 'cd' || arr1[0] == 'ps' || arr1[0] == 'hs'){
              json.show = false
            }else{
              json.show = true
            }
            json.name = name
            json.id = arr1[0] + ':' +arr[0]
            that.iotKeyList.push(json)
          }
        })
      }
      that.deviceDialogVisible = true
    },
    /*initTimer(){
      var that = this
      that.statusTimer = setInterval(_ => {
        that.deviceStatus()
      }, 2000)
    },*/
    deviceClose(){
      var that = this
      if(that.statusTimer){
        clearInterval(that.statusTimer)
        that.statusTimer = null
      }
      that.deviceDialogVisible = false
    },
    deviceStatus(){
      var that = this
      deviceStatus({deviceId: that.dataForm.deviceId,deviceType: that.dataForm.deviceType}).then(res => {
        if (res.status == 200) {
          if (res.data.retCode == 0) {
            that.$set(that.dataForm,'status',res.data.result.status)

            if(res.data.result.task){
              that.$set(that.dataForm,'task',res.data.result.task)
              var j = JSON.parse(that.dataForm.task)
              that.$set(that.dataForm,'taskName',j.command)

              if(j.command != -1){
                if(that.dataForm.deviceType == '13'){
                  let imgForm = window.config.drapLeftElMap[that.dataForm.deviceType];
                  that.componentsList.forEach(item=>{
                    if(item.deviceId == that.dataForm.deviceId){
                      item.imgUrl = imgForm['url'+item.direction + '' + item.direction][j.command]
                    }
                  })
                }else if(that.dataForm.deviceType == '14'){
                  let imgForm = window.config.drapLeftElMap[that.dataForm.deviceType];
                  that.componentsList.forEach(item=>{
                    if(item.deviceId == that.dataForm.deviceId){
                      item.imgUrl = imgForm['urls'][j.command]
                    }
                  })
                }else if(that.dataForm.deviceType == '11'){
                  let imgForm = window.config.drapLeftElMap[that.dataForm.deviceType];
                  that.componentsList.forEach(item=>{
                    if(item.deviceId == that.dataForm.deviceId){
                      item.imgUrl = imgForm['urls'][j.command]
                    }
                  })
                }else if(that.dataForm.deviceType == '40' || that.dataForm.deviceType == '41' || that.dataForm.deviceType == '42'){
                  that.iotKeyData = [];
                  const str1 = that.dataForm.iotKey.split('|');
                  const str2 = that.dataForm.taskName.split('|');
                  str1.forEach((item,i)=>{
                    const [name, values] = item.split(':');
                    const name1 = window.config.pumpMap[name]
                    const [name2, values2] = str2[i].split(':');
                    var arr = values.split(',')
                    var arr2 = values2.split(',')
                    if(arr.length > 1){
                      arr.forEach((item2,i2)=>{
                        that.iotKeyData.push({ id: `${name}:${item2}`, name:name1+(i2+1) , status: arr2[i2] })
                      })
                    }else{
                      that.iotKeyData.push({ id: `${name}:${arr[0]}`, name:name1 , status: arr2[0] })
                    }

                  })
                }
              }

              //that.$set(that.dataForm,'command',j.command)
              if(j.body){
                j.dataFormBody = JSON.parse(j.body)
              }

              if(that.dataForm.deviceType == '15'){
                //that.loadinfoBoardTemplate(1,j.dataFormBody.textInfoList);
              }else if(that.dataForm.deviceType == '26'){
                that.dataForm.speed26 = j.speed ? j.speed.toFixed(1) : ''
                that.dataForm.direction26 = j.direction == '0' ? '正向':'反向'
              }else if(that.dataForm.deviceType == '27'){
                that.dataForm.co27 = j.co ? j.co.toFixed(1) : ''
                that.dataForm.vi27 = j.vi ? j.vi.toFixed(1) : ''
              }else if(that.dataForm.deviceType == '28'){
                that.dataForm.light28 = j.light ? j.light.toFixed(1) : ''
              }else if(that.dataForm.deviceType == '43'){
                that.dataForm.height43 = j.height ? j.height.toFixed(1) : ''
              }

            }
            if(that.statusTimer){
              clearTimeout(that.statusTimer)
              that.statusTimer = null
            }
            that.statusTimer = setTimeout(()=>{
              that.deviceStatus()
            },2000)
          } else {
            that.$message.warning(res.data.message);
          }
        }
      })
    },
    loadinfoBoardTemplate(index,list){
      var that = this
      infoBoardTemplateList().then(res => {
        if (res.status == 200) {
          if (res.data.retCode == 0) {
            if(index){
              that.templateHtmlList = []
              res.data.result.forEach((item,i)=>{
                list.forEach(item1=>{
                  if(item.id == item1.id){
                    var str = that.domRender(item.textInfo,item1.fillInfo,item.id,1)
                    var html = '';
                    var backColor = ''
                    var fontColor = ''
                    var fontFormat = ''
                    var fontFormatUpDown = ''
                    let fontSize = item.fontSize.split('*')[0]
                    switch (item.backColor) {
                      case '红色':
                        backColor = 'red'
                        break;
                      case '黄色':
                        backColor = 'yellow'
                        break;
                      case '绿色':
                        backColor = 'green'
                        break;
                      case '黑色':
                        backColor = 'black'
                        break;
                    }
                    switch (item.fontColor) {
                      case '红色':
                        fontColor = 'red'
                        break;
                      case '黄色':
                        fontColor = 'yellow'
                        break;
                      case '绿色':
                        fontColor = 'green'
                        break;
                      case '黑色':
                        fontColor = 'black'
                        break;
                    }
                    switch (item.fontFormat) {
                      case '居中':
                        fontFormat = 'center'
                        break;
                      case '居左':
                        fontFormat = 'left'
                        break;
                      case '居右':
                        fontFormat = 'right'
                        break;
                    }
                    switch (item.fontFormatUpDown) {
                      case '居中':
                        fontFormatUpDown = 'center'
                        break;
                      case '居左':
                        fontFormatUpDown = 'left'
                        break;
                      case '居右':
                        fontFormatUpDown = 'right'
                        break;
                    }
                    html += `<div style="background-color: ${backColor};color: ${fontColor};width: ${item.cmsWidth}px;height: ${item.cmsHeight}px;display: flex;justify-content: ${fontFormat};align-items: ${fontFormatUpDown};font-size: ${Number(fontSize)}px;font-family: ${item.fontName}">${str}</div>`
                    that.templateHtmlList.push({
                      html:html,
                      intervaly:item.intervaly
                    })
                  }
                })
              })
              if(that.templateHtmlList.length > 0){
                if(that.tempTimer){
                  clearTimeout(that.tempTimer)
                  that.tempTimer = null;
                }
                that.templateDisplay(0); // 递归调用显示函数
              }
            }else{
              that.infoBoardTemplateList = []
              res.data.result.forEach((item,i)=>{
                var form = {
                  ...item,
                  templateHtml:that.domRender(item.textInfo),
                }
                that.infoBoardTemplateList.push(form)
              })
            }
          } else {
            that.$message.warning(res.data.message);
          }
        }
      })
    },
    templateDisplay(index) {
      var that = this;
      that.templateInfoHtml = that.templateHtmlList[index].html; // 显示当前索引的名称
      let nextIndex = (index + 1) % that.templateHtmlList.length; // 计算下一个索引
      let nextTime = parseInt(that.templateHtmlList[nextIndex].intervaly) * 1000; // 下一个元素的显示时间
      that.tempTimer = setTimeout(() => {
        that.templateDisplay(nextIndex); // 递归调用显示函数
      }, nextTime);
    },
    addComment(event,row){
      this.tempMap[row.id] = {
        ...this.tempMap[row.id],
        [event.target.attributes.idData.value]:event.target.value
      }
    },
    handleCommitClick(index){
      var that = this
      that.deviceLoading = true;
      /*if(that.statusTimer){
        clearTimeout(that.statusTimer)
        that.statusTimer = null
      }*/
      var json = {
        //deviceId: that.dataForm.deviceId,
        deviceType: that.dataForm.deviceType,
        command: that.dataForm.command,
      }
      if(index){  //批量控制
        if(that.multipleSelection.length > 0){
          var deviceIds = []
          that.multipleSelection.forEach(item=>{
            deviceIds.push(item.deviceId)
          })
          json.deviceId = deviceIds.toString()
        }else {
          that.$message.info('请选择');
          return '';
        }
      }else{
        json.deviceId = that.dataForm.deviceId
      }

      if(that.dataForm.deviceType == '12'){
        json.body = JSON.stringify(that.dataFormBody)
      }else if(that.dataForm.deviceType == '15'){
        json.command = '15_01'
        var ids = Object.keys(this.tempMap)
        var arr = []
        that.textInfoList.forEach(item1=>{
          var a = {
            id:item1,
            fillInfo:''
          }
          ids.forEach(item=>{
            if(item == item1){
              var fillInfos = Object.values(this.tempMap[item])
              a.fillInfo = fillInfos.join(';')
            }
          })
          arr.push(a)
        })
        json.body = JSON.stringify({textInfoList:arr})
      }else if(that.dataForm.deviceType == '40' || that.dataForm.deviceType == '41' || that.dataForm.deviceType == '42'){

        const convertedArray = that.dataForm.iotKeys.reduce((acc, curr) => {
          const [key, value] = curr.split(":");
          const existing = acc.find(item => item.startsWith(key));

          if (existing) {
            const index = acc.indexOf(existing);
            acc[index] = `${existing},${value}`;
          } else {
            acc.push(`${key}:${value}`);
          }

          return acc;
        }, []);
        json.iotKey = convertedArray.join("|")
      }
      iotControl(json).then(res => {
        that.deviceLoading = false;
        /*if(!index && that.dataForm.refresh == '1'){
          that.deviceStatus()
        }*/
        if (res.status == 200) {
          if (res.data.retCode == 0) {
            that.$message.success('成功')
            that.dataForm.status = res.data.result.status
            that.dataForm.task = res.data.result.task
            if(that.dataForm.task){
              var j = JSON.parse(that.dataForm.task)
              that.$set(that.dataForm,'taskName',j.command)
              //that.$set(that.dataForm,'command',j.command)

              if(j.command != -1){
                if(that.dataForm.deviceType == '13'){
                  let imgForm = window.config.drapLeftElMap[that.dataForm.deviceType];
                  that.componentsList.forEach(item=>{
                    if(item.deviceId == that.dataForm.deviceId){
                      item.imgUrl = imgForm['url'+item.direction + '' + item.direction][j.command]
                    }
                  })
                }else if(that.dataForm.deviceType == '14'){
                  let imgForm = window.config.drapLeftElMap[that.dataForm.deviceType];
                  that.componentsList.forEach(item=>{
                    if(item.deviceId == that.dataForm.deviceId){
                      item.imgUrl = imgForm['urls'][j.command]
                    }
                  })
                }else if(that.dataForm.deviceType == '40' || that.dataForm.deviceType == '41' || that.dataForm.deviceType == '42'){
                  that.iotKeyData = [];
                  const str1 = that.dataForm.iotKey.split('|');
                  const str2 = that.dataForm.taskName.split('|');
                  str1.forEach((item,i)=>{
                    const [name, values] = item.split(':');
                    const name1 = window.config.pumpMap[name]
                    const [name2, values2] = str2[i].split(':');
                    var arr = values.split(',')
                    var arr2 = values2.split(',')
                    if(arr.length > 1){
                      arr.forEach((item2,i2)=>{
                        that.iotKeyData.push({ id: `${name}:${item2}`, name:name1+(i2+1) , status: arr2[i2] })
                      })
                    }else{
                      that.iotKeyData.push({ id: `${name}:${arr[0]}`, name:name1 , status: arr2[0] })
                    }

                  })
                }
              }

              if(j.body){
                var b = JSON.parse(j.body)
                if(that.dataForm.deviceType == '12'){
                  that.$set(that.dataForm,'light',b.light)
                }
                if(that.dataForm.deviceType == '15'){
                  that.loadinfoBoardTemplate(1,b.textInfoList);
                }
              }
            }
            //that.loadTable()
            //that.loadDevice2(that.dataForm.deviceType)
          } else {
            that.$message.warning(res.data.message);
          }
        }
      })
    },
    filedFomatter(value, list) {
      if (value === "" || value == undefined) return "";
      const item = list.find((item) => item.id == value);
      return item ? item.name : "";
    },
    domRender(str,fillInfo,id,index) {
      var that = this
      let strData = str
      //var reg = /\{.*?\}/g
      let charCount = str.split('{}').length - 1;
      var arr = []
      if(fillInfo){
        arr = fillInfo.split(';')
      }
      for(var i = 0;i < charCount; i++){
        if(arr.length>0){
          if(index){
            strData = strData.replace('{}', arr[i]);
          }else{
            strData = strData.replace('{}', '<input idData=temp' + i + ' value="'+arr[i]+'" class="emptyOut" type="text" />');
          }
          that.tempMap[id] = {
            ...this.tempMap[id],
            ['temp'+i]:arr[i]
          }
        }else{
          strData = strData.replace('{}', '<input idData=temp' + i + ' class="emptyOut" type="text" />');
        }
      }
      return strData
    },
  },
  mounted() {
    this.init()
  }

}
</script>
<style scoped>

/deep/.temlCheckClass .el-checkbox__input{
  vertical-align: top;
  padding-top: 2px;
}
</style>
<style>

.emptyOut{
  width: 60px;
  margin: 0 5px;
}
</style>
