<template>
  <el-dialog
    class="setTimeDialog"
    title="拍照时间表设置"
    :visible.sync="isShow"
    :close-on-click-modal="false"
    @close="handleclose"
    width="1000px"
  >
    <el-tabs v-model="activeName" @tab-click="handleClick" v-loading="loading">
      <el-tab-pane label="拍照时间表" name="1">
        <div class="timebox">
          <div class="flexnr">
            <div class="w8">选择通道:</div>
            <el-select
              v-model="selaccess"
              placeholder="请选择"
              class="mr20"
              @change="changeSelect"
            >
              <el-option
                v-for="item in accesslist"
                :key="item.channelid"
                :label="
                  item.alias !== null && item.alias !== ''
                    ? item.alias
                    : item.channelname
                "
                :value="item.channelid"
              >
                {{
                  item.alias !== null && item.alias !== ""
                    ? item.alias
                    : item.channelname
                }}
              </el-option>
            </el-select>

            <!-- <el-button type="primary" @click="inquireRealbtn()"
            >查询实际时间表</el-button
          > -->
          </div>
          <div class="flexno bt30">
            <!-- <div class="timehead">
              <label>时间表规则:</label>
              <p>ssssssssssss</p>
            </div> -->
            <div class="timeShow" v-loading="loading">
              <div class="leftTime" v-if="shedulenr.length !== 0">
                <div class="w8">时间表:</div>
                <div class="w80 flexonly" v-loading="timeloading">
                  <el-tag
                    class="mr10 mt10"
                    size="mini"
                    v-for="(val, index) in this.shedulenr"
                    :key="index"
                    >{{ val.substring(0, val.lastIndexOf(":")) }}</el-tag
                  >
                </div>
              </div>
              <div class="rightTime" v-if="newshedulenr.length !== 0">
                <div class="w8">装置时间表:</div>
                <span class="offtime" v-if="offsetnum !== ''"
                  >(偏移时间{{ offsetnum }}分钟)</span
                >
                <div class="w80 flexonly" v-loading="timeloading">
                  <el-tag
                    class="mr10 mt10"
                    size="mini"
                    v-for="(val, index) in this.newshedulenr"
                    :key="index"
                    >{{ val.substring(0, val.lastIndexOf(":")) }}</el-tag
                  >
                </div>
              </div>
              <div v-if="shedulenr.length == 0 && newshedulenr.length == 0">
                暂无拍照时间表
              </div>
            </div>
          </div>

          <el-button
            class="searchBtn"
            type="text"
            :loading="compareloading"
            @click="inquirebtn()"
            >装置时间表对比</el-button
          >
        </div>
      </el-tab-pane>
      <el-tab-pane label="拍照时间表下发" name="2">
        <div class="deviceTable">
          <el-table
            ref="multipleTable"
            :data="deviceTableData"
            tooltip-effect="dark"
            stripe
            style="width: 100%"
            height="calc(100% - 40px)"
          >
            <el-table-column label="名称" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column label="时间表类型" show-overflow-tooltip>
              <template>按时间段</template>
            </el-table-column>
            <el-table-column label="时间表规则" width="300">
              <template slot-scope="scope">
                <p
                  class="timeGz"
                  v-for="(val, index) in scope.row.list"
                  :key="index"
                >
                  <span>
                    {{
                      val.startTime.substring(0, val.startTime.lastIndexOf(":"))
                    }}</span
                  >
                  ~
                  <span>{{
                    val.endTime.substring(0, val.endTime.lastIndexOf(":"))
                  }}</span>
                  间隔：<b>{{ val.span }}分钟</b>
                </p>
              </template>
            </el-table-column>

            <el-table-column
              prop="remark"
              label="备注"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click.native.stop="handleSet(scope.row)"
                  >设置</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pageNation">
            <el-pagination
              :current-page="page"
              :page-size="pageSize"
              layout=" prev, pager, next, jumper,total"
              @current-change="handleCurrentChange"
              :total="total"
              background
            >
            </el-pagination>
          </div>
        </div>
        <el-dialog
          class="setRoadDialog"
          title="设置"
          :visible.sync="isShowset"
          :close-on-click-modal="false"
          width="680px"
          append-to-body
          @close="closebtn"
        >
          <div class="setTimeTd">
            <div class="tdSetBox">
              <h3>装置信息</h3>
              <el-descriptions title="" :column="3" border>
                <el-descriptions-item label="电压等级">{{
                  deviceListData.dyname
                }}</el-descriptions-item>
                <el-descriptions-item label="线路名称">
                  {{ deviceListData.xlname }}</el-descriptions-item
                >
                <el-descriptions-item label="装置名称">
                  {{ deviceListData.zzname }}
                </el-descriptions-item>
              </el-descriptions>
              <h3>时间表规则</h3>
              <p class="timename">时间表名称：{{ timeName }}</p>
              <div class="flexTimeGz">
                <p
                  class="timeGz"
                  v-for="(val, index) in scheduleInfo"
                  :key="index"
                >
                  <span>{{ val.startTime }}</span> ~
                  <span>{{ val.endTime }}</span>
                  间隔：<b>{{ val.span }}分钟</b>
                </p>
              </div>
              <div class="math">
                偏移时间(分)：
                <el-input-number
                  v-model="setNum"
                  :min="0"
                  :max="9"
                ></el-input-number>
              </div>
              <h3>选择通道</h3>
              <div class="checkBox">
                <el-radio-group v-model="checkList" @change="handleChange">
                  <el-radio
                    :label="val.id"
                    border
                    v-for="val in zzchannel"
                    :key="val.id"
                    >{{ val.name }}</el-radio
                  >
                </el-radio-group>
                <!-- <el-checkbox-group v-model="checkList" @change="handleChange">
                  <el-checkbox
                    :label="val.id"
                    border
                    v-for="val in zzchannel"
                    :key="val.id"
                    >{{ val.name }}</el-checkbox
                  >
                </el-checkbox-group> -->
              </div>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closebtn">取 消</el-button>
            <el-button
              type="primary"
              v-debounce="submitForm"
              :loading="sureloading"
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>
<script>
import {
  getChannelListJoggle,
  getSchedulenr,
  getScheduleRulelListJoggle,
  setScheduleRulel,
  getScheduleRulelAccessList,
  cmaSchelduleDetials,
  getCmaSchelduleDetials,
  getCmaSchelduleUpload,
} from "@/utils/api/index";
export default {
  props: {
    title: String,
  },
  data() {
    return {
      loading: false,
      isShow: false,
      isShowset: false,
      activeName: "1", //选项卡
      accesslist: [], //通道选择器
      selaccess: "", //选中的通道
      shedulenr: [], //查询的时间表
      deviceTableData: [], //时间表-表格
      page: 1, // 当前页数
      pageSize: 10, // 每页数量
      total: 0, //总条数
      listnr: [], //通道树结构
      defaultProps: {
        children: "list",
        label: "name",
      },
      selfacilityId: "", //所选设备id
      ruleid: "", //线路id
      parmsList: [], //所选装置下通道参数
      scheduleid: 0, //所选时间表id

      //设置-获取所有通道
      timeName: "",
      scheduleInfo: [],
      //获取当前装置内容
      deviceListData: {}, //当前装置信息
      zzchannel: [], //当前装置通道
      checkList: "", //选中的通道
      newcmdzzid: "",
      newrequestId: "",
      timer: null, //定时器
      timers: null,
      timernum: 0,
      i: 0,
      timeloading: false,

      requestId: "",
      newshedulenr: [], //装置时间表
      requestList: [],
      requestArr: [], //通过requestid获取状态
      sureloading: false,
      offsetnum: "",
      setNum: Math.floor(Math.random() * 10),
      compareloading: false,
    };
  },
  mounted() {
    console.log(this.selaccess);
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    //获取单个设备通道
    getSingleAccess(id, zzid) {
      this.newcmdzzid = zzid;
      this.selfacilityId = id;
      getChannelListJoggle({ termid: id })
        .then((res) => {
          this.accesslist = res.data.list;
          console.log(this.accesslist);
          this.selaccess = res.data.list[0].channelid;
          //this.inquireRealbtn();
          console.log(this.selaccess);
          this.loading = true;
          getSchedulenr({
            channelid: this.selaccess,
            terminalid: this.selfacilityId,
          })
            .then((res) => {
              // this.$message.success("查询成功");
              // this.shedulenr = res.data.list.join("; ")
              this.shedulenr = res.data.list;
              this.offsetnum = res.data.offset;
              this.loading = false;
            })
            .catch((err) => {
              this.$message.error("查询失败");
            });
        })
        .catch((err) => {});
    },
    //changeSelect\选择通道
    changeSelect() {
      console.log(this.selaccess);
      this.loading = true;
      this.newshedulenr = [];
      getSchedulenr({
        channelid: this.selaccess,
        terminalid: this.selfacilityId,
      })
        .then((res) => {
          // this.$message.success("查询成功");
          // this.shedulenr = res.data.list.join("; ")
          this.shedulenr = res.data.list;
          this.offsetnum = res.data.offset;
          this.loading = false;
        })
        .catch((err) => {
          this.$message.error("查询失败");
        });
    },
    //查询时间表
    inquirebtn() {
      console.log(this.selaccess, this.selfacilityId);
      this.compareloading = true;
      cmaSchelduleDetials({
        channelid: this.selaccess,
        terminalid: this.selfacilityId,
      })
        .then((res) => {
          console.log(res);
          this.requestId = res.data.requestId;
          this.realNewtime();
          this.timer = window.setInterval(() => {
            //console.log(this.requestList);
            this.realNewtime();
            this.timernum++;
          }, 3000);
        })
        .catch((err) => {
          this.$message.error("查询失败");
        });
    },
    //查询真是时间时间表
    realNewtime() {
      getCmaSchelduleDetials({
        requestid: this.requestId,
      })
        .then((res) => {
          if (res.code == 200) {
            if (res.data.isNew == true) {
              // this.shedulenr = res.data.list.join("; ")
              this.compareloading = false;
              this.newshedulenr = res.data.list;
              this.timernum = 0;
              // this.$message.success("查询成功");
              clearInterval(this.timer);
              this.timer = null;
            } else if (this.timernum > 9) {
              this.compareloading = false;
              this.searchloading = false;
              this.timernum = 0;
              this.$message.warning("暂无拍照时间表！");
              clearInterval(this.timer);
              this.timer = null;
            }
          } else {
            this.$message.error(res.code.msg);
          }
        })
        .catch((err) => {
          this.compareloading = false;
          this.$message.error("查询失败");
          clearInterval(this.timer);
          this.timer = null;
        });
    },
    //获取线路列表数据
    deviceList() {
      getScheduleRulelListJoggle({
        pageindex: this.page,
        pagesize: this.pageSize,
      })
        .then((res) => {
          this.deviceTableData = res.data.list;
          this.total = res.data.total;
          console.log(this.deviceTableData);
          this.loading = false;
        })
        .catch((err) => {});
    },
    //点击分页
    handleCurrentChange(val) {
      this.page = val;
      this.deviceList();
    },
    //设置-获取所有通道
    handleSet(val) {
      this.loading = true;
      this.scheduleid = val.id;
      this.isShowset = true;
      console.log(val);
      this.scheduleInfo = val.list;
      this.timeName = val.name;
      getScheduleRulelAccessList({ termid: this.selfacilityId })
        .then((res) => {
          this.listnr = res.data.list;
          console.log("1111111111111111111");
          console.log(this.listnr);
          this.deviceListData = {
            dyname: this.listnr[0].name,
            dyid: this.listnr[0].id,
            xlname: this.listnr[0].list[0].name,
            xlid: this.listnr[0].list[0].id,
            zzname: this.listnr[0].list[0].list[0].name,
            zzcmid: this.listnr[0].list[0].list[0].cmdid,
            zzid: this.listnr[0].list[0].list[0].id,
          };
          this.zzchannel = this.listnr[0].list[0].list[0].list;
          console.log(this.deviceListData);
          console.log(this.zzchannel);
          this.this.loading = false;
        })
        .catch((err) => {});
    },
    //获取所选值
    getCheckedNodes() {
      this.parmsList = [];
      const checkedNodes = this.$refs.tree.getCheckedNodes(false, true); //若节点可被选择，则返回目前被选中的节点所组成的数组
      //const checkedParam = []; //定义选中的数组
      let index = -1;
      // console.log(checkedNodes);
      if (checkedNodes.length !== 0) {
        checkedNodes.forEach((item) => {
          // 父节点结构的情况 判断是否有list子节点，如果有定义数组结构
          if (item.list !== undefined) {
            index++;
            this.parmsList[index] = {
              //name: item.name,
              termid: item.id,
              channelidlist: [],
            };
          } else {
            //如果没有list 把子节点id push到 定义的数组channelidlist中
            this.parmsList[index].channelidlist.push(item.id);
          }
          //通过bsManufacturer 判断是否是  线路 获取线路id
          // if (item.bsManufacturer !== undefined) {
          //   this.ruleid = item.id;
          //   console.log(this.ruleid);
          // }
        });
      }
      // console.log(this.parmsList);
      //遍历删除没有channelichilddlist的数据，只留下通道
      this.parmsList = this.parmsList
        .filter((item) => item.channelidlist.length !== 0)
        .map((item) => {
          return {
            termid: item.termid,
            channelidlist: item.channelidlist,
          };
        });
      // console.log(this.parmsList);
      return this.parmsList;
    },
    //选择通道
    handleChange() {
      //console.log(this.listnr);
      console.log(this.checkList);
      // this.$refs.tree.setCheckedKeys(this.checkedAisle);
    },
    // 保存确定操作
    submitForm() {
      //this.getCheckedNodes();

      console.log(this.deviceListData);
      console.log(this.checkList);
      console.log(this.scheduleid);

      if (this.checkList.length == 0) {
        this.$message.error("请选择通道");
      } else {
        setScheduleRulel({
          scheduleid: this.scheduleid,
          list: [
            {
              termid: this.deviceListData.zzid,
              channelidlist: [this.checkList],
              offset: this.setNum,
            },
          ],
        })
          .then((res) => {
            console.log(res);
            this.requestList = res.data.list;
            this.requestTime();
            this.timers = window.setInterval(() => {
              //console.log(this.requestList);
              this.requestTime();
              this.i++;
            }, 3000);
          })
          .catch((err) => {
            this.$message({
              showClose: true,
              message: "添加失败",
              type: "error",
            });
          });
      }
    },
    //下发时间表
    requestTime() {
      //
      this.sureloading = true;
      getCmaSchelduleUpload({
        list: this.requestList,
      })
        .then((res) => {
          console.log("aaaaaaaaaaaaaaaaaaaaaaaa");
          this.requestArr = res.data.list;
          this.requestList = this.requestArr.filter(function (
            value,
            index,
            arr
          ) {
            console.log(value, index, arr);
            return value.status !== 1;
          });
          console.log(this.requestArr);
          if (this.requestList.length == 0) {
            this.isShowset = false;
            this.sureloading = false;
            this.$message.success("下发成功");
            clearInterval(this.timers);
            this.timers = null;
          } else if (this.i > 9) {
            this.isShowset = false;
            this.sureloading = false;
            this.i = 0;
            this.$message.warning("下发失败，请稍后再试！");
            clearInterval(this.timers);
            this.timers = null;
          }
        })
        .catch((err) => {});
    },
    closebtn() {
      this.isShowset = false;
      this.checkList = "";
      this.setNum = Math.floor(Math.random() * 10);
      this.deviceList();

      clearInterval(this.timers);
      this.timers = null;
    },
    display() {
      this.isShow = true;
    },
    hide() {
      this.isShow = false;
    },
    handleclose() {
      this.newshedulenr = [];
      this.shedulenr = [];

      console.log("关闭轮询");
      clearInterval(this.timers);
      this.timers = null;
    },
  },
};
</script>
<style lang="less">
.setTimeDialog {
  .el-tabs__content {
    height: 400px;
    overflow: auto;
    .el-tab-pane {
      height: calc(100% - 16px);
    }
  }
  .timebox {
    //width: 410px;
    margin: auto;
  }
  .flexonly {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
  }
  .flexno {
    display: flex;
    margin-top: 16px;
    padding: 0px 8px;
    flex-direction: column;
    height: 294px;
    .timehead {
      display: flex;

      line-height: 32px;
      margin-bottom: 8px;
      label {
        margin-right: 6px;
        width: 80px;
      }
    }
    .timeShow {
      display: flex;
      .leftTime {
        width: 50%;
      }
      .rightTime {
        width: 50%;
        position: relative;
        .offtime {
          position: absolute;
          top: 0px;
          left: 78px;
        }
      }
    }
  }
  .searchBtn {
    font-size: 14px;

    display: flex;
    margin-left: auto;
    span {
      text-decoration-line: underline;
    }
  }
  .flexnr {
    display: flex;
    align-items: center;
    margin-top: 16px;
    padding: 0px 8px;
  }
  .mt10 {
    margin-bottom: 10px;
  }
  .mr10 {
    margin-right: 10px;
  }
  .w8 {
    width: 80px;
    margin-bottom: 8px;
  }
  .w80 {
    width: 80%;
    overflow-y: auto;
    height: 210px;
  }
  .mr20 {
    margin-right: 20px;
  }

  .deviceTable {
    padding: 16px 8px 0 8px;
    height: calc(100% - 16px);

    .el-table--small {
      margin-bottom: 8px;
    }
    .rulesBox {
      display: flex;
      flex-direction: row;
      li {
        list-style: none;
        margin-right: 24px;
        line-height: 24px;
        span {
          margin-right: 4px;
        }
        .el-tag--small {
          height: 16px;
          padding: 0 8px;
          line-height: 16px;
        }
      }
    }

    .timeGz {
      line-height: 26px;

      span {
        margin: 0px 8px;
      }
      b {
        font-weight: normal;
        color: @color-primary;
      }
    }

    .pageNation {
      justify-content: flex-start;
    }
  }
}
.setRoadDialog {
  .el-dialog__body {
    height: 400px;
    overflow: auto;
    .el-form {
      height: 100%;
      //background: #fcc;
    }
    .setTimeTd {
      h3 {
        margin: 8px 0px;
        font-size: 16px;
        line-height: 24px;
      }
      .timename {
        margin: 8px 0px;
      }
      .flexTimeGz {
        display: flex;
        flex-wrap: wrap;
        .timeGz {
          line-height: 32px;
          margin-right: 16px;
          span {
            margin: 0px 8px;
          }
          b {
            font-weight: normal;
            color: @color-primary;
          }
        }
      }
      .math {
        margin-top: 12px;
        margin-bottom: 12px;
      }
    }
  }
}
</style>
