<template>
  <div class="reportBox">
    <div class="commandBox">
      <div class="commandRunLeft commandClass">
        <div class="headTitle">
          <span class="title">待下发终端</span>
          <el-select
            v-model="operateL"
            placeholder="筛选运操维作"
            @change="selectLeftChanged"
          >
            <el-option
              v-for="item in operateOptions"
              :key="item.key"
              :label="item.desc"
              :value="item.key"
            ></el-option>
          </el-select>
          <el-input
            class="cmdidClass"
            v-model="leftcmdVal"
            placeholder="请输入设备ID查询"
            @blur="leftInputChange"
          ></el-input>
          <span class="mlspan">命令:{{ leftCommand.length }}</span>
          <span class="time"
            >更新时间：{{
              $moment(updateTime).format("YYYY-MM-DD HH:mm:ss")
            }}</span
          >
          <el-button
            v-if="leftCommand.length > 0"
            class="deletebtn"
            type="danger"
            icon="el-icon-delete"
            @click="deleteml"
          ></el-button>
        </div>
        <div class="mlbpox" v-loading="leftComLoading">
        <div
          class="commandList"
         
          v-if="leftCommand.length != 0"
         
        >
          <p
            class="comLi"
            v-for="(item, index) in leftCommand"
            :key="index"
            @dblclick="handleShowCommand(item)"
          >
            <span class="indexClass">{{ index + 1 }}</span>
            <span class="comMsg"
              ><b>时间：{{ item.createTime }}</b>
              <b v-if="item.terminal && item.terminal.cmdid">设备ID：{{ item.terminal.cmdid }}</b>
              <b v-if="item.cmdMap &&item.cmdMap.fileName">apk版本：{{ item.cmdMap.fileName }}</b>
              <b>命令：{{ cmdCn[item.name] }}</b
              >
             
              <b v-if="item.estimatedPublishTime * 1000 - newupdatatime > 0"
                >命令预计拿走时间：

                {{
                  $moment(item.estimatedPublishTime * 1000).format(
                    "MM-DD HH:mm:ss"
                  )
                }}
                {{ remainingTime(item) }}
              </b>
            </span>
          </p>
        </div>
        <div class="commandList" v-else>
          <p>暂无下发命令</p>
        </div>
      </div>
      </div>
      <div class="commandRunRight commandClass">
        <div class="headTitle">
          <span class="title">已下发终端</span>
          <el-select
            v-model="operateR"
            placeholder="筛选运操维作"
            @change="selectRightChanged"
          >
            <el-option
              v-for="item in operateOptions"
              :key="item.key"
              :label="item.desc"
              :value="item.key"
            ></el-option>
          </el-select>
          <el-input
            class="cmdidClass"
            v-model="rightcmdVal"
            placeholder="请输入设备ID查询"
            @blur="rightInputChange"
          ></el-input>
          <span class="mlspan">命令:{{ rightCommand.length }}</span>
          <span class="time"
            >更新时间：{{
              $moment(updateTime).format("YYYY-MM-DD HH:mm:ss")
            }}</span
          >
          <el-button
            v-if="rightCommand.length > 0"
            class="deletebtn"
            type="danger"
            icon="el-icon-delete"
            @click="deletehis"
          ></el-button>
        </div>
        <div class="mlbpox" v-loading="rightComLoading">
        <div class="commandList" v-if="rightCommand.length != 0" >
          <p class="comLi" v-for="(item, index) in rightCommand" :key="index">
            <el-tooltip
              class="item"
              effect="dark"
              :open-delay="600"
              :content="item.status == '1' ? '已下发' : '已取消'"
              placement="top"
            >
              <span
                class="indexClass"
                :class="item.status == '1' ? 'normalClass' : 'cancelClass'"
                >{{ index + 1 }}</span
              >
            </el-tooltip>
            <span class="comMsg" 
              ><b>下发时间：{{ item.publishTime }}</b>
              <b v-if="item.terminal && item.terminal.cmdid">设备ID：{{ item.terminal.cmdid }}</b>
              <b>命令：{{ cmdCn[item.name] }}</b>
              <b v-if="item.cmdMap &&item.cmdMap.fileName">apk版本：{{ item.cmdMap.fileName }}</b>
              <b v-else>cmd：{{ item.cmdMap }}</b>
            </span>
          </p>
        </div>
        <div class="commandList" v-else>
          <p>暂无已下发命令</p>
        </div>
      </div>
      </div>
    </div>
    <el-dialog
      class="MsgDialog"
      title="命令信息"
      :visible.sync="commandShow"
      :close-on-click-modal="false"
      width="680px"
    >
      <div class="cmdMain">
        <!-- {{ deveceMsg }} -->
        <p>设备ID:{{ devCmdid }}</p>
        <p>操作时间：{{ deveceMsg.createTime }}</p>
        <p>待执行操作：{{cmdCn[deveceMsg.name]}}  {{ deveceMsg.name }}</p>
        <p>cmd：{{ deveceMsg.cmd }}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel(deveceMsg.id)">取消操作</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { cmdSendApi,getCmdActionApi,cmdActlistApi,cmdActHislistApi } from "@/utils/api/index";
export default {
  name: "report",
  components: {},
  data() {
    return {
      leftComLoading: false, //左侧loading
      rightComLoading:false,//右侧loiading
      // runCommand: [],
      // endCommand: [],
      leftCommand: [],
      rightCommand: [],
      commandShow: false,
      deveceMsg: {},
      devCmdid:'',
      cmdCn: {
        yw_cmd_android_reboot: "重启设备",
        yw_cmd_mcu_reboot: "MCU单片机重启",
        i1_cmd_set_i1_server_ip_port: "设置I1服务器",
        i1_cmd_set_xy_yw_ip_port: "设置运维服务器",
        i1_cmd_set_i1_heart_beat_time: "设置心跳周期",
        yw_cmd_upload_i1_zip_log: "上传日志",
        upgrade: "升级",
        yw_upd_ota: "Ota升级",
        yw_cmd_start_frpc: "开启frpc",
        yw_cmd_stop_frpc: "停止frpc",
        i1_cmd_stop_aging_test: "停止老化测试",
        del_file: "删除文件",
        upload_file: "上传文件",
        download_file: "下发文件",
      },
      cmdtimer: null,
      endtimer: null,
      updateTime: null,
      newupdatatime: null,
      //运维操作列表
      operateOptions: [
        {id: 0, key: "all", desc: "全部"}
      ],
      operateL: 'all',
      operateR: 'all',
      leftcmdVal: "",
      rightcmdVal: "",
      intervalId: null, // 用于存储setInterval返回的ID
    };
  },
  computed: {},
  created() {
    this.cmdtimer = setInterval(this.getCmdList, 60000); // 每60秒刷新数据
    this.endtimer = setInterval(this.getEndList, 60000); // 每60秒刷新数据
  },
  mounted() {
    this.getCmdList();
    this.getEndList();
    this.getCmdOptionsFun()
    this.startCountdown(); // 在组件挂载后开始倒计时
  },

  methods: {
    getCmdOptionsFun(){
      getCmdActionApi()
          .then((res) => {
            console.log(res);
            this.operateOptions = this.operateOptions.concat(res.data);
           // this.operateL = this.operateOptions[0].desc;
          })
          .catch((err) => {});
    },
    startCountdown() {
      this.newupdatatime = new Date().getTime(); // 更新当前时间
      // 清空之前可能存在的定时器
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
      // 开始倒计时，每秒执行一次remainingTime方法
      this.intervalId = setInterval(() => {
        this.newupdatatime = new Date().getTime(); // 更新当前时间
        this.leftCommand.forEach((item) => {
          this.remainingTime(item); // 重新计算每个项目的剩余时间
        });
      }, 1000); // 每秒执行一次
    },
    remainingTime(item) {
      if (!this.newupdatatime) {
        // 更新时间尚未设置，返回默认的倒计时时间或者不执行任何操作
        return "计算中...";
      }
      const estimatedPublishTime = item.estimatedPublishTime * 1000;
      const difference = estimatedPublishTime - this.newupdatatime;
      const minutes = Math.floor(difference / 60000);
      const seconds = Math.floor((difference % 60000) / 1000);
      if (minutes == 0 && seconds == 0) {
        this.getCmdList();
        this.getEndList();
        return `命令已下发`;
      } else {
        return ` 预估剩余：${minutes} 分钟 ${seconds} 秒`;
      }
    },
    getCmdList() {
      this.leftComLoading = true;
      let params = {
        pageNum:1,
        pageSize:300,
      };
      console.log(this.operateL)
      // 根据条件添加参数
      if (this.operateL!=='all') {
        params.action = this.operateL;
      }
      if (this.leftcmdVal !== "") {
        params.cmdid = this.leftcmdVal;
      }
      cmdActlistApi(params)
        .then((res) => {
          console.log(res);
           //this.runCommand = res.data.list;
          this.leftCommand = res.data.list;
          this.leftComLoading = false;
          
          this.updateTime = new Date();
        })
        .catch((err) => {});
    },
    handleShowCommand(val) {
      console.log(val);
      this.commandShow = true;
      console.log(this.commandShow);
      this.deveceMsg = val;
      this.devCmdid = val.terminal.cmdid
    },
   
    //获取已取走列表
    getEndList() {
      this.rightComLoading = true;
      let params = {
        pageNum:1,
        pageSize:300,
      };
      // 根据条件添加参数
      if (this.operateR!== 'all') {
        params.action = this.operateR;
      }
      if (this.rightcmdVal!== "") {
        params.cmdid = this.rightcmdVal;
      }
      cmdActHislistApi(params)
        .then((res) => {
          console.log(res);
          //this.endCommand = res.data;
           //this.endCommand = res.data.list
          this.rightCommand = res.data.list;
          
          this.rightComLoading = false;
          this.updateTime = new Date();
        })
        .catch((err) => {});
    },
    //左侧筛选
    selectLeftChanged() {
      this.getCmdList()
    },
    leftInputChange() {
      console.log(this.leftcmdVal);
      this.getCmdList()
    },

    //右侧筛选
    selectRightChanged() {
      this.getEndList()
    },
    rightInputChange() {
      this.getEndList()
    },
     //取消操作
     handleCancel(val) {
      console.log(val)
      cmdSendApi({
        action: "cancel",
        id: val,
      })
        .then((res) => {
          console.log(res);

          this.$confirm("确定取消该命令？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                duration: 1500,
                showClose: true,
                message: "命令已取消",
                type: "success",
              });
              this.commandShow = false;
              this.getCmdList();
              this.getEndList();
            })
            .catch(() => {
              this.commandShow = false;
            });
        })
        .catch((err) => {});
    },

    deleteml() {
      cmdSendApi({
        action: "clear",
      })
        .then((res) => {
          console.log(res);

          this.$confirm("确定清除所有命令？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                duration: 1500,
                showClose: true,
                message: "命令已清除",
                type: "success",
              });
              this.commandShow = false;
              this.getCmdList();
              this.getEndList();
            })
            .catch(() => {
              this.commandShow = false;
            });
        })
        .catch((err) => {});
    },
    deletehis() {
      cmdSendApi({
        action: "clearHis",
      })
        .then((res) => {
          console.log(res);

          this.$confirm("确定清除所有命令？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                duration: 1500,
                showClose: true,
                message: "命令已清除",
                type: "success",
              });

              this.getCmdList();
              this.getEndList();
            })
            .catch(() => {});
        })
        .catch((err) => {});
    },
  },
  beforeDestroy() {
    //清除定时器
    clearInterval(this.cmdtimer);
    clearInterval(this.endtimer);
    this.cmdtimer = null;
    this.endtimer = null;
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  },
};
</script>
<style lang="less">
.reportBox {
  height: calc(100% - 24px);
  width: calc(100% - 24px);
  padding: 12px;
  .commandBox {
    display: flex;
    height: calc(100% - 18px);
    .commandClass {
      width: 50%;
      padding: 12px;
      height: calc(100% - 24px);
      border: 1px solid #dcdfe6;
      margin-right: 12px;
      border-radius: 4px;
      .headTitle {
        height: 40px;
        line-height: 40px;
        display: flex;
        align-items: center;
        .title {
          font-size: 16px;
          font-weight: normal;
        }
        .el-select {
          margin: 0px 12px;
          width: 150px;
        }
        .cmdidClass {
          width: 180px;
        }
        .mlspan {
          font-size: 14px;
          margin-left: 8px;
        }
        .time {
          font-size: 12px;
          margin-left: 8px;
        }
        .deletebtn {
          margin-left: auto;
          padding: 4px;
        }
      }
      .mlbpox{
        height: calc(100% - 40px);
      }
      .commandList {
        width: 100%;
        height: calc(100% - 0px);
        //background: #fcc;
        overflow: auto;
        p {
          background: #fdf6ec;
          margin-bottom: 8px;
          line-height: 24px;
          color: #333;
          font-size: 14px;
          padding: 6px;
          cursor: pointer;
          display: flex;
          align-items: center;
          &:hover {
            background: #faecd8;
          }
          .indexClass {
            padding: 4px;
            font-size: 14px;
            color: #000;
            background: #d3d3d3;
            min-width: 18px;
            text-align: center;
            margin-right: 8px;
          }
          .normalClass {
            background: #d3d3d3;
          }
          .cancelClass {
            background: #fde2e2;
          }
          .comMsg {
            display: flex;
            flex-wrap: wrap;
            b {
              font-weight: normal;
              margin-right: 12px;
            }
          }
        }
      }
    }
    .commandRunLeft {
    }
    .commandRunRight {
      .commandList {
        p {
          cursor: default;
          background: #e1f3d8;
          &:hover {
            background: #e1f3d8;
          }
        }
      }
    }
  }
  .MsgDialog {
    .cmdMain {
      p {
        font-size: 16px;
        line-height: 32px;
      }
    }
    .dialog-footer {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.el-dialog__headerbtn {
  top: 18px;
  .el-dialog__close {
    font-size: 26px;
    &:hover {
      background: #e2e2e2;
    }
  }
}
</style>
