<template>
  <div id="aiBell w-full" style="width:100%;">
    <div class="page-header">
      <div class="page-title flex align-center">
        <el-button icon="el-icon-back" size="mini" style="font-size: 20px; color: #000;" type="text" @click="toBack" ></el-button>
        <el-divider direction="vertical"></el-divider>
        预警中心
      </div>
      <div class="page-header-btn">
        <el-button @click="markAllEventRead">一键忽略</el-button>
        <el-tooltip class="item" effect="dark" content="..." placement="left-start">
          <el-button icon="el-icon-plus" circle size="mini" ></el-button>
        </el-tooltip>
      </div>
    </div>
    <div class="tab-box" style="width: 100%;">
      <el-tabs class="tab-switch" v-model="aiTypeVal" @tab-click="handleAiTypeClick">
        <el-tab-pane v-for="item in aiTypeArr"
                     :key="'ai-'+item.val"
                     :label="item.text"
                     :name="`${item.val}`"/>
      </el-tabs>
      <div class="tab-header">
        <el-input class=" input-with-select" placeholder="输入算法名片段" v-model="key" >
          <el-select v-model="triggerTypeVal"
                     style="width: 120px;"
                     slot="prepend"
                     @change="getNowTriggerType" placeholder="触发类型">
            <el-option
              :key="'trigger-0'"
              label="全部类型"
              :value="0">
            </el-option>
            <el-option
              v-for="item in triggerTypeArr"
              :key="'trigger-'+item.val"
              :label="item.text"
              :value="item.val"
              :disabled="item.disabled">
            </el-option>
          </el-select>

        </el-input>
        <el-select v-model="alarmState" style="width: 120px;"
                   slot="prepend"
                   @change="getNowTriggerType" placeholder="已读状态">
          <el-option
            :key="'read-0'"
            label="全部"
            :value="0"/>
          <el-option
            v-for="item in alarmStateArr"
            :key="'read-'+item.val"
            :label="item.text"
            :value="item.val"
            :disabled="item.disabled"/>
        </el-select>

        <el-button slot="append"
                   style="width: 80px;"
                   icon="el-icon-search"
                   type="primary"
                   :loading="isLoading"
                   @click="searchClickHandle">搜索</el-button>
      </div>
      <div class="tab-content">
        <el-table
            class="table"
            style="overflow-y: auto;"
            :data="tabList"
            header-row-class-name="table-header"
            @sort-change="tableSortChange"
        >
          <el-table-column label="是否识别" v-if="aiTypeVal == '1'">
            <template slot-scope="scope">
              <span>{{ parseAlarmType(scope.row.alarmType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="识别类型" min-width="120">
            <template slot-scope="scope">
              <el-tag
                  class="mx-025"
                  v-for="item in scope.row.arithmetic.split(',')"
                  :key="`${scope.row.arithmetic.id}-${item}`">
                {{ getArithmeticName(item) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deviceId" label="设备号"></el-table-column>
          <el-table-column prop="firmware_version" label="固件版本号"></el-table-column>
          <el-table-column prop="signal" label="信号" :sortable="'signal'" width="75">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark"
                          :content="scope.row.signal+' '+signalTransform(scope.row.signal,false)"
                          placement="left-start">
                <signal-info :signal-text="scope.row.signal"></signal-info>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="上传时间" :sortable="'createTime'">
            <template slot-scope="scope">
              <span>{{ getTimeText(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="alarmState" label="状态" width="80">
            <template slot-scope="scope">
              <span>{{ getAlarmState(scope.row.alarmState) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" >
            <template slot-scope="scope">
              <el-button size="medium" @click="editAlarmHandle(scope.row)">忽略</el-button>
              <el-button size="medium" type="primary" @click="moreAlarmHandle(scope.row)">
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="tab-page">
        <el-pagination
          style="float: right"
          @size-change="handleSizeChange"
          @current-change="currentChange"
          :current-page="currentPage"
          :page-size="count"
          :page-sizes="[5,10,15, 25, 35, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>

    </div>
  </div>
</template>

<script>
import {
  triggerTypes,
  getTriggerTypeArr,
  getAITypeArr,
  toAlarmState,
  alarmStates,
  getAlarmStateArr,
  toAlarmKey
} from "@/map/ai.js"
import handle from "@/until/handle";
import timeUntil from "@/until/time";
import SignalInfo from "@/components/common/signalInfo";
import devTool from "@/hfyUntil/devTool";
let bellSearchSource = null;
export default {
  name: "bell",
  components: {SignalInfo},
  data(){
    return {
      isLoading: false,
      triggerTypeVal: 0,
      triggerTypes: triggerTypes,
      triggerTypeArr: getTriggerTypeArr(),
      aiTypeVal: "1",
      aiTypeArr: getAITypeArr(),
      alarmStates: alarmStates,
      alarmStateArr: getAlarmStateArr(),
      key: '',
      searchKey: '',
      alarmState: 0,
      searchAlarmState: '',
      searchOrder: "descending",
      searchSort: 'alarmId',
      lastPage: 1,
      currentPage: 1,
      count: 15,
      total: 1,
      tabList: [],

    }
  },
  beforeDestroy() {
    this.stopQuest();
    this.alarmState = this.$route.query.alarmState
  },
  beforeMount() {
    console.log("beforeMount")
    // 尝试从临时存储中获取搜索条件
    let searchParam = window.sessionStorage.getItem("bellSearchParam");
    searchParam = JSON.parse(searchParam);
    if (searchParam) {
      this.searchKey = searchParam.searchKey;
      this.alarmState = searchParam.alarmState;
      this.aiTypeVal = searchParam.aiTypeVal;
      this.triggerTypeVal = searchParam.triggerTypeVal;
      this.count = searchParam.count;
      this.currentPage = searchParam.currentPage;
    }
  },
  mounted() {
    console.log("mounted")
    this.searchClickHandle();
  },
  methods:{
    signalTransform:devTool.signalTransform,
    toBack(){
      this.$router.back();
      if (this.deviceId === "" ) {
        this.beforeUrl = "/"
      }
    },
    getNowTriggerType(){

    },
    stopQuest(){
      if(bellSearchSource){
        bellSearchSource.cancel();
        bellSearchSource = null;
      }
    },
    getAlarmState(stateCode){
      let state = toAlarmState(stateCode);
      return state?state.text:"null";
    },
    getTimeText(timeStamp){
      return timeUntil.dateFormat(
        timeUntil.timeStamp_to_Date(timeStamp),
      )
    },

    async searchData(searchParam){
      if(bellSearchSource){
        this.$message.warning("请等待请求完成");
      }
      searchParam.arithmetic = this.aiTypeVal;
      searchParam.alarmState = toAlarmKey(searchParam.alarmState);
      bellSearchSource = this.$axios.axios.CancelToken.source();
      this.isLoading = true;
      let [err,res] = await handle(
        this.$axios.axios.post('/ai/alarms',
          searchParam,
          {
            cancelToken: bellSearchSource.token
          })
      );
      this.isLoading = false;
      bellSearchSource = null;
      if(err){
        return this.$message.error(err.message);
      }
      console.log(res);
      let result = res.data;
      if(result.code === 0){
        this.tabList = result.data;
        this.total = result.total;
        this.libList = result.list;
        // 存储搜索条件
        window.sessionStorage.setItem("bellSearchParam",JSON.stringify({
          searchKey: this.searchKey,
          alarmState: this.alarmState,
          aiTypeVal: this.aiTypeVal,
          triggerTypeVal: this.triggerTypeVal,
          count: this.count,
          currentPage: this.currentPage,
        }));
      }else{
        this.$message.warning(result.msg);
      }
    },

    handleAiTypeClick(tab, event){
      console.log(tab, event);
      console.log(this.aiTypeVal);
      console.log(tab.name);
      this.searchClickHandle();
    },
    currentChange: function (val) {
      this.currentPage = val;
      this.changePage();
    },
    handleSizeChange: function (val) {
      this.count = val;
      this.changePage();
    },
    changePage(){
      // 使用当前配置进行搜索
      let searchParam = {
        p: this.currentPage,
        l: this.count,
        key: this.searchKey,
        alarmState: this.searchAlarmState,
        order: this.searchOrder,
        sort: this.searchSort,
      }
      this.searchData(searchParam);
    },
    searchClickHandle(){
      let searchParam = {
        p: 1,
        l: this.count,
        key: this.key,
        alarmState: this.alarmState
      }
      this.searchKey = this.key;
      this.searchAlarmState = this.alarmState;
      this.searchData(searchParam);
    },
    async editAlarmHandle(row){
      let [err,res] = await handle(this.$axios.get(`/ai/alarm/ignore/${row.alarmId}`))
      if(err){return this.$message.error(err.msg)}
      if(res.data.code!==0){return this.$message.warning(res.data.msg)}
      this.$message.success("操作成功!!!");
    },
    moreAlarmHandle(row){
      this.$router.push(`/alarm/${row.alarmId}`)
    },
    // 改变排序结构
    tableSortChange(v,v1){
      console.log("sort change");
      console.log(v,v1);
      let prop = v.prop,
          order = v.order;
      // 构建新搜索数据体进行搜索
      let searchParam = {
        order: order,
        sort: prop,
        p: 1,
        l: this.count,
        key: this.searchKey,
        alarmState: this.searchAlarmState
      }
      this.searchSort = prop;
      this.searchOrder = order;
      this.searchData(searchParam);
    },

    // 全部忽略
    markAllEventRead(){
      this.$confirm('此操作将忽略全部告警内容,请再次确认?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let [err, res] = await handle(this.$axios.get(`/ai/markAll?arithmetic=${this.aiTypeVal}`))
        if (err) {
          return this.$message.error(err.msg)
        }
        if (res.data.code !== 0) {
          return this.$message.warning(res.data.msg)
        }
        this.$message.success("操作成功!!!");
      })
    },
    getArithmeticName(text) {
      let res = this.aiTypeArr.find(item => item.val == text)
      return res ? res.text : "未知";
    },
    parseAlarmType(text) {
      let r = ""
      if (text == "1") {
        r = "设备名单人员";
      } else {
        r = "陌生人"
      }
      return r
    }
  }
}
</script>

<style scoped>
.mx-025 {
  margin-left: 0.25rem;
  margin-right: 0.25rem;
}

.page-header {
  height: 45px;
  box-sizing: border-box;
  margin-bottom: 5px;
}
.tab-box{
  width: 100%;
  height: calc(100vh - 135px);
  background-color: #fff;
  border-radius: 0.25rem;
  padding: 5px;
  box-sizing: border-box;
  overflow: hidden;
}
.tab-box .tab-switch{
  height: 45px;
}
.tab-box .tab-header{
  height: 40px;
  width: 99%;
  display: flex;
}
.tab-box .tab-header > *{
  height: 40px;
}
.tab-box .tab-content{
  height: calc(100% - 118px);
  overflow-y: auto;
}
.tab-box .tab-content .table{
  height: 100%;
}
.tab-box .tab-page{
  height: 35px;
}

</style>
