<template>
  <div class="warning_list">
    <el-tabs v-model="activeTab" @tab-click="onChangeTab">
      <el-tab-pane label="预警事件" name="four" v-hasPermi="['home:notice:event']" />
      <el-tab-pane label="感知事件" name="first"  v-hasPermi="['home:notice:warningEvent']"/>
      <el-tab-pane label="待确认事件" name="second" v-hasPermi="['home:notice:warningEvent']" />
      <el-tab-pane label="处置中事件" name="third" v-hasPermi="['home:notice:disposeEvent']" />
      <el-tab-pane label="设备异常" name="fifth" v-hasPermi="['home:notice:deviceOffline']" />
    </el-tabs>
    <div>
      <Table :data="tableData" :show-header="false" @cell-click="onCellClick" height="400px">
        <ElTableColumn prop="remark" width="550">
          <template slot-scope="scope">

            <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top-start">
              <div class="markPanel">
                <div class="leftColumn">
                  <div class="device-icon" :style="{ backgroundImage: `url(${require(`@screen/images/event/${scope.row.icon? scope.row.icon : '交通拥堵'}.svg`)})` }" />
                  <p>{{ activeTab == 'first' ? WarningType[scope.row.warningType] : scope.row.stringEventType }}</p>
                </div>
                <p class="rightRemark">
                  {{ scope.row.remark }}
                </p>
              </div>
          </el-tooltip>
          </template>
        </ElTableColumn>
      </Table>
    </div>

    <div class="footer" style="width:100%;display:flex;justify-content: center;margin-top: 10px;">
      <Pagination @current-change="getMainData" @size-change="onSizeChange" width="'100%'"
        :page-sizes="[10, 20, 30, 40, 50]" :page-size="searchData.pageSize" :current-page.sync="searchData.pageNum"
        layout="total, sizes, prev, pager, next" :total="total">
      </Pagination>
    </div>

    <DialogDeviceOffline  :visible="modelDeviceVisible" :activeId="activeId"
    @update:value="handleDeviceDialogClose"  />
    <!-- "详情"弹出框 -->
    <EventDetailDialog :visible="eventDetailDialogVisible" :formData="detailDialogFormData" :activeName="activeName"
      @update:value="handleDialogClose" @queryData="reData" />
    <DialogWarning ref="refDigWarn" v-model="dialogWarningVisible"></DialogWarning>

    <!-- 设备异常弹窗 -->
  </div>
</template>

<script>
import request from "@/utils/request";
import Table from '@screen/components/Table.vue';
import Pagination from '@screen/components/Pagination.vue';
import { WarningType , deviceTypeOptions} from "@screen/utils/enum.js";
import { Message } from "element-ui";

import { WarningType as warningTypeMapping, DirectionTypes as gzDirectionMapping, warningSourceMapping, warningStateMapping } from "@screen/utils/enum.js"

import { checkPermi } from "@/utils/permission.js";
import DialogWarning from './dialogWarn/DialogWarning.vue'
import {mokStakeWarning} from './dialogWarn/mock.js'
export default {
  components: {
    Table,
    Pagination,
    DialogWarning,
  },
  data() {
    return {
      activeTab: "four",
      WarningType,
      eventDetailDialogVisible: false,
      detailDialogFormData: {},
      activeName: '-1',
      tableData: [],
      total: 10,
      searchData: {
        pageSize: 10,
        pageNum: 1,
      },

      dialogWarningVisible: false,


      modelDeviceVisible:false,
      activeId:''
    };
  },
  computed: {
  },
  mounted() {
    // 判断初始化弹窗列表
    //预警事件
    if (checkPermi(["home:notice:event"])) {
      this.activeTab = "four";
    } else if(checkPermi(["home:notice:warningEvent"])){
      this.activeTab = "first";
    } else if(checkPermi(["home:notice:processingEvent"])){
      this.activeTab = "third";
    } else if(checkPermi(["home:notice:deviceOffline"])){
      this.activeTab = "fifth";
    }
    //添加全局事件监听
    this.$root.$on('refresh-event', this.getMainData);
    this.getMainData();
  },
  beforeDestroy() {
    // 在实例销毁前移除事件监听,防止内存泄漏
    this.$root.$off('refresh-event', this.getMainData);
  },
  methods: {
    onChangeTab(tab, event) {
      this.getMainData();
    },

    handleDeviceDialogClose() {
      this.modelDeviceVisible = false;
    },
    onCellClick(row, column, cell, event) {
      if(this.activeTab === 'fifth'){
        this.activeId = row.id;
        this.modelDeviceVisible = true;

        return;
      }
      if(this.activeTab === 'four'){
         if(row.warningType === '1'){

          this.dialogWarningVisible = true;
          this.$refs.refDigWarn.bind(row.id,row.remark)
        }
        return;
        // setTimeout(() => {
        //   this.dialogWarningData = mokStakeWarning
        // }, 500);
        // return;

      } else if (this.activeTab == 'first') {
        this.activeName = '-1'
      } else if(this.activeTab == 'third'){
        this.activeName = '1'
      } else {
        this.activeName = '0'
      }
      this.firstBtnClick(row.id);
    },
    handleDialogClose() {
      this.eventDetailDialogVisible = false;

      this.$root.$emit('refresh-event-list');
    },
    reData() {

    },
    getMainData() {
      if (this.activeTab == 'first') {
        request({
          url: `/perceivedEvents/warning/warningListPage?pageNum=${this.searchData.pageNum}&pageSize=${this.searchData.pageSize}`,
          method: "POST",
          data: {
            warningState: 1,
          }
        })
          .then((result) => {
            if (result.code != 200) return;
            this.tableData = result.rows;
            this.total = result.total;
          })
      } else if (this.activeTab == 'second' || this.activeTab == 'third') {
        request({
          url: `dc/system/event/list?eventState=${this.activeTab == 'second'?0:1}&pageSize=${this.searchData.pageSize}&pageNum=${this.searchData.pageNum}`,
          method: "GET",
          // params: {}
        })
          .then((result) => {
            if (result.code != 200) return;
            result.rows.forEach(item => {
              item.remark = (item.occurrenceTime || '') + " " + (item.stakeMark || '') + " " + (item.direction==='1'?'菏泽方向':'济南方向') + " 发生" + (item.stringEventType || '') + "( " + (item.eventSubclassName || '') + ")事件"
              // item.remark = item.stakeMark + " " + item.direction + " 发生" + item.stringEventType + "( " + item.eventSubclass + ")事件"
            })
            this.tableData = result.rows;
            this.total = result.total;
          })
      } else if(this.activeTab === 'four'){
        request({
          url: `/business/warning/meteorologicalList?pageSize=${this.searchData.pageSize}&pageNum=${this.searchData.pageNum}`,
          method: "Post",
          // url: `business/dcNoStakeWarningTable/list?pageSize=${this.searchData.pageSize}&pageNum=${this.searchData.pageNum}`,
          // method: "GET",
        })
          .then((result) => {
            if (result.code != 200) return;
            result.rows.forEach(item => {
              item.remark = item.warningDescription
              if (item.warningType === '1') {
                item.stringEventType = '交通流预警';
              } else if (item.warningType === '2') {
                item.stringEventType = '气象预警';
              } else if (item.warningType === '3') {
                item.stringEventType = '交通流异常预警';
              } else {
                item.stringEventType = '未知预警类型'; // 可选:处理未知的 warningType
              }
/*
              item.stringEventType = item.warningType === '1'?'交通流预警':'气象预警';
*/
              if(item.warningType === '2'){
                item.icon = '气象检测器'
              }
            })
            this.tableData = result.rows;
            this.total = result.total;
          })
      } else if(this.activeTab === 'fifth'){
        request({
          url: `/deviceOfflineRecord/list?status=0&orderByColumn=createTime&isAsc=desc&pageSize=${this.searchData.pageSize}&pageNum=${this.searchData.pageNum}`,
          method: "GET",
        })
          .then((result) => {
            if (result.code != 200) return;
            result.rows.forEach(item => {
              item.icon = '设备'
              item.remark = item.createTime+ ' '+item.stakeMark +' ' +item.deviceName+'发生故障'
              item.stringEventType = _.find(deviceTypeOptions,{value:parseInt(item.deviceType)}).label

            })
            this.tableData = result.rows;
            this.total = result.total;
          })
      }
    },
    firstBtnClick(id) {//点击去确认/详情/处置记录等第一个按钮
      if (this.activeName == '-1') {
        request({
          url: `/perceivedEvents/warning/getWarningById`,//感知事件
          method: "post",
          data: { id }
        }).then((result) => {
          if (result.code != 200) return Message.error(result?.msg);
          let data = result.data;

          data.stringEventSource = data?.warningSource ? warningSourceMapping[data.warningSource] : '';
          data.nickName = data.userName;
          // data.direction = gzDirectionMapping[data.direction] || data.direction;
          data.startTime = data.warningTime;
          data.stringEventState = warningStateMapping[data.warningState];
          data.stringEventType = warningTypeMapping[data.warningType];
          data.actionSource = this.activeName
          data.videoList = [];
          if (data.otherConfig) {
            let otherConfig = JSON.parse(data.otherConfig);

            data.waterFilmThickness = otherConfig.waterFilmThickness;
            data.windSpeed = otherConfig.windSpeed;
            data.visibility = otherConfig.visibility;

            data.pictures = otherConfig.pictures || otherConfig.imgUrl ||[];
            data.videoList = otherConfig.videoList || otherConfig.videoUrl|| [];
            // data.videoList = ['https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-480p.mp4',
            // 'https://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-480p.mp4']
          }
          data.videoType = "mp4";
          data.component = "Video";

          data.description = data.remark;
          this.detailDialogFormData = data;
          // console.log('data', this.detailDialogFormData)

          this.eventDetailDialogVisible = true;
        });
      } else {
        request({
          url: `/dc/system/event/${id}`,//交通事件
          method: "get",
        }).then(async (result) => {
          if (result.code != 200) return Message.error(result?.msg);
          let data = result.data;
          data.stringDirection = gzDirectionMapping[data.direction] || data.direction;
          data.startTime = data?.occurrenceTime || '';


          data.videoList = [];
          data.component = "VideoMulti";

          // const { downCamera, upCamera } = ((await getNearCameraNew(data.stakeMark))?.data || {});//新的上下游摄像头接口
          // data.downCamId = downCamera?.camId;
          // data.upCamId = upCamera?.camId;
          data.videoType = "flv";

          this.detailDialogFormData = data;

          this.eventDetailDialogVisible = true;
        });
      }

    },
    onSizeChange(pageSize) {
      this.searchData.pageSize = pageSize;
      this.getMainData();
    },
  }
};
</script>

<style lang="scss" scoped>
.warning_list {
  .markPanel{
    display: flex;

    justify-content: center;
    align-items: center;
  }
  .rightRemark{
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .leftColumn {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 8px;
    border: 1px solid #FF5F5F;
    width: 120px;
    height: 28px;
    p {
      color: #FF5F5F;
      font-size: 13px;
      margin-right: 3px;
    }

    .device-icon {
      height: 22px;
      width: 22px;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      background-position: center;
    }

  }
}
</style>