<template>
  <el-scrollbar height="100vh">
    <div class="wrapper">
      <datav-header/>
      <main>
        <el-row :gutter="16">
          <el-col :span="6">
            <datav-card title="内部视频">
              <div class="row mt-4 mb-20">
                <div class="col col-8">
                  <label>视频总数</label>
                  <span>107</span>
                </div>
                <div class="col col-8">
                  <label>在线数</label>
                  <span>97</span>
                </div>
                <div class="col col-8">
                  <label>在线率</label>
                  <span>91%</span>
                </div>
              </div>
              <div class="mb-12">
                <video
                    width="100%"
                    height="250"
                    controls="controls"
                    autoplay
                >
                  <source src="/mp4/1.mp4" type="video/ogg"/>
                </video>
              </div>
              <el-row :gutter="12">
                <el-col :span="8">
                  <img src="/imgs/datav/1.png" class="active" alt=""/>
                </el-col>
                <el-col :span="8">
                  <img src="/imgs/datav/2.jpg" alt=""/>
                </el-col>
                <el-col :span="8">
                  <img src="/imgs/datav/3.jpeg" alt=""/>
                </el-col>
              </el-row>
            </datav-card>
            <datav-card title="问题数排名" sub-title="问题数" style="height: 370px;">
              <datav-tabs
                  type="bottom-button"
                  v-model="subOneProRankTab"
              >
                <datav-tab-item label="派出所" name="1">
                  <el-scrollbar height="280px">
                    <datav-chart-bar
                        :data="fxsjRankList"
                        size="large"
                        :color="colors"
                    />
                  </el-scrollbar>
                </datav-tab-item>
                <datav-tab-item label="大队" name="2">
                  <el-scrollbar height="280px">
                    <datav-chart-bar
                        :data="jsdwRankList"
                        :max="11"
                        size="large"
                        :color="colors"
                    />
                  </el-scrollbar>
                </datav-tab-item>
              </datav-tabs>

            </datav-card>
          </el-col>

          <el-col :span="12">
            <datav-date-picker v-model="time"/>
            <div class="flex gap-42">
              <datav-statistic
                  :value="overview.discoverProblem"
                  title="发现问题数"
                  style="width: 20%"
              />
              <datav-statistic
                  :value="overview.changedProblem"
                  title="整改问题数"
                  style="width: 20%"
              />
              <datav-statistic
                  :value="overview.relativeOrg"
                  title="涉及单位数"
                  style="width: 20%"
              />
              <datav-statistic
                  :value="overview.relativePer"
                  title="涉及人数"
                  style="width: 20%"
              />
              <datav-statistic
                  :value="overview.changedRate"
                  value-unit="%"
                  title="整改率"
                  style="width: 20%"
              />
            </div>
            <v-charts
                style="height: 420px"
                :option="option"
                autoresize
                ref="subOneVideoInspMapChart"
            />
            <datav-card title="问题趋势">
              <v-charts
                  style="height: 250px"
                  :option="proTrend"
                  autoresize
              />
              <div class="gobal-dropdown-container">
                <el-dropdown class="test" @command="handleCommand">
                   <span class="el-dropdown-link my-gobal-yearselect">
                      {{ selectedYear + ' 年' }}
                    </span>
                  <template #dropdown>
                    <el-dropdown-menu style="width: 90px">
                      <el-dropdown-item v-for="year in years" :key="year" :command="year">{{ year + " 年" }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </datav-card>
          </el-col>

          <el-col :span="6">
            <datav-card title="实时预警">
              <el-scrollbar height="450px">
                <div class="message message-error">
                  <div class="message-title">待处理</div>
                  <div>
                    芙蓉-定王台-办案区-询（讯）问室 （湖南省长沙市公安局芙蓉分局定王台派出所 ） &emsp; “民警单人询（讯）问”的违规问题
                  </div>
                  <div class="message-footer flex between">
                    <span>芙蓉分局定王台派出所</span>
                    <span>2024-11-18 20:12</span>
                  </div>
                </div>
                <div class="message message-info">
                  <div class="message-title">待处理</div>
                  <div>
                    望城-管理中心-办案区-询问室（湖南省长沙市望城区公安局法制大队）&emsp; 民警单人询（讯）问”的违规问题。
                  </div>
                  <div class="message-footer flex between">
                    <span>望城区公安局法制大队</span>
                    <span>2024-11-18 19:12</span>
                  </div>
                </div>
                <div class="message">
                  <div class="message-title">待处理</div>
                  <div>
                    执法办案中心-询问室7（湖南省长沙市公安局芙蓉分局蓉园派出所） &emsp;同时讯（询）问多名嫌疑对象
                  </div>
                  <div class="message-footer flex between">
                    <span>芙蓉分局蓉园派出所</span>
                    <span>2024-11-18 16:12</span>
                  </div>
                </div>
                <div class="message">
                  <div class="message-title">待处理</div>
                  <div>
                    开福-直属-执法办案管理-讯询问室（湖南省长沙市公安局开福分局法制大队） &emsp;“民警单人询（讯）问”的违规问题
                  </div>
                  <div class="message-footer flex between">
                    <span>开福分局法制大队</span>
                    <span>2024-11-18 15:12</span>
                  </div>
                </div>
              </el-scrollbar>
            </datav-card>
            <datav-card title="问题类型占比">
              <v-charts
                  style="height: 300px"
                  :option="ProblemTypeRateChart"
                  autoresize
              />
            </datav-card>
          </el-col>
        </el-row>
      </main>
    </div>
  </el-scrollbar>
</template>

<script setup>
import changshaMap from "@/assets/data/changsha.json";
import vCharts from "vue-echarts";
import * as echarts from "echarts/core";
import {
  getVideoSuperviseMap
} from "@/api/screen/videoSupervise.ts";
import moment from "moment/moment.js";
import {getSubOneStreetMap} from "@/api/screen/subScreen/subOneGlobal.ts";
import {
  getSubOneAllVideoSuperviseCount, getSubOneVideoSuperviseMap,
  getSubOneVideoSuperviseProblemRank, getSubOneVideoSuperviseProblemTypeRate, getSubOneVideoSuperviseTrend
} from "@/api/screen/subScreen/subOneVideoSupervise.ts";
// region 所有变量
const time = ref([
  moment().subtract(1, "year").format("YYYY-MM-DD"),
  moment().format("YYYY-MM-DD"),
]);
const fxsjRankList = ref([]);
const jsdwRankList = ref([]);
const overview = ref({
  discoverProblem: 0,
  changedProblem: 0,
  relativeOrg: 0,
  relativePer: 0,
  changedRate: 0,
});
const mapIconList = ref([{
  originalName: "浏阳市局",
  name: "浏阳市",
  discoverProblem: 135,
  changedProblem: 135,
  relativeOrg: 89,
  relativePer: 152,
  changedRate: 100
}])
const currentYear = new Date().getFullYear();
const years = ref([currentYear.toString(), (currentYear - 1).toString(), (currentYear - 2).toString()]); // 年份列表
const selectedYear = ref('2024'); // 当前选中的年份
const currentMapData = ref({})
const subOneVideoInspMapChart = ref(null);  // 地图
const route = useRoute();
const currentDepartId = route.query.departId;
const subOneProRankTab=ref("1")
let subOneVideoMapIntervalId;
const colors = [
  {
    color: "linear-gradient( 270deg, #FB002D 0%, #822232 100%)",
    percentage: 80,
  },
  {
    color: "linear-gradient( 270deg, #FFB90E 0%, #71501D 100%)",
    percentage: 60,
  },
  {
    color: "linear-gradient( 270deg, #63E700 0%, #19674C 100%)",
    percentage: 40,
  },
];
// endregion

// region 所有图表
const proTrend = ref({
  xAxis: {
    type: "category",
    boundaryGap: true,
    data: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月",],
    axisTick: {
      // 去掉X轴刻度线
      show: false
    },
  },
  yAxis: {
    type: "value",
    splitLine: {
      show: true,
      lineStyle: {
        color: "#193775",
      },
    },
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  series: [
    {
      type: "line",
      smooth: true,
      lineStyle: {
        color: "#28E6FF",
        width: 4,
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: "rgba(40,230,255,0.47)", // 渐变起始颜色
          },
          {
            offset: 1,
            color: "rgba(40,230,255,0)", // 渐变结束颜色
          },
        ]),
      },
      data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    },
  ],
  grid: {
    left: '5%', // 图表距离容器左边的距离
    right: '2%', // 图表距离容器右边的距离
    top: '10%', // 图表距离容器上边的距离
    bottom: '20%', // 图表距离容器下边的距离
    containLabel: false // 是否包含坐标轴的标签
  },

});
echarts.registerMap("changsha", changshaMap);
const option = ref({
  tooltip: {
    trigger: 'item',
    position: 'bottom',
    formatter: function (params) {
      const dataItem = mapIconList.value.find(item => item.name === params.name) || {}; // 找到对应的数据项
      console.log("Data item:", dataItem);
      if (dataItem.name === params.name) {
        return `
        <div class="tooltip">
          <div class="tooltip-title">${params.name}</div>
          <div class="tooltip-content">
            <ul class="tooltip-ul" >
              <li>发现问题数 <span>${dataItem.discoverProblem}</span></li>
              <li>整改问题数 <span>${dataItem.changedProblem}</span></li>
              <li>涉及单位数 <span>${dataItem.relativeOrg}</span></li>
              <li>涉及人数 <span>${dataItem.relativePer}</span></li>
              <li>整改率 <span>${dataItem.changedRate}%</span></li>
            </ul>
          </div>
        </div>`;
      } else {
        return `<div class="tooltip">
          <div class="tooltip-title">${params.name}</div>
          <div class="tooltip-content">
            <ul class="tooltip-ul"">
              <li>发现问题数 <span>-</span></li>
              <li>整改问题数 <span>-</span></li>
              <li>涉及单位数 <span>-</span></li>
              <li>涉及人数 <span>-</span></li>
              <li>整改率 <span>-</span></li>
            </ul>
          </div>
        </div>`;
      }
    },
  },
  visualMap: {
    type: "piecewise",
    bottom: 10,
    pieces: [
      {gte: 0, lte: 200, label: "低于平均问题30%", color: "#4987F6"},
      {gte: 200, lte: 400, label: "平均问题上下浮动30%内", color: "#F6A149"},
      {gte: 400, label: "高于平均问题30%", color: "#D34343"},],
    right: 10,
    realtime: false,
    orient: "horizontal",
    textStyle: {
      color: "#fff",
    },
    calculable: true,
    inRange: {
      color: ["#4987F6", "#F6A149", "#D34343"],
    },
  },
  series: [
    {
      name: "长沙",
      type: "map",
      map: "changsha",
      roam: true,
      hoverAnimation: true,
      label: {
        show: true,
        color: "white",
      },
      itemStyle: {
        normal: {
          areaColor: "#02215E",
          borderColor: "#24D2EE",
          borderWidth: 1 // 高亮时边框宽度
        },
      },
      emphasis: {
        areaColor: "#FFD700", // 高亮时区域颜色
        borderColor: "#FF0000", // 高亮时边框颜色
        borderWidth: 4 // 高亮时边框宽度
      },
      data: [],

    }
  ],
})
const ProblemTypeRateChart = ref({
  series: [
    {
      type: "pie",
      radius: ["40%", "70%"],
      label: {
        color: "#fff",
      },
      data: [],
    },
  ],
  tooltip: {
    trigger: "item",
  },
});  // 问题类型占比
// endregion


// region 所有函数
const getMapJSON = async (departId) => {
  const res = await getSubOneStreetMap(departId);
  currentMapData.value = res;
  echarts.registerMap("changsha", res);
  subOneVideoInspMapChart.value.chart.setOption(option.value);
}

const getSubOneVideoSuperviseProblemRankData = async (departId, timeValue) => {
  const res = await getSubOneVideoSuperviseProblemRank(departId, timeValue);
  fxsjRankList.value = res.policeVideoSuperviseProblemRankList
  jsdwRankList.value = res.teamVideoSuperviseProblemRankList
}
const getSubOneAllVideoSuperviseCountData = async (departId, timeValue) => {
  const res = await getSubOneAllVideoSuperviseCount(departId, timeValue);
  overview.value = res.overview;
}


const getSubOneVideoSuperviseMapData = async (departId, timeValue) => {
  const res = await getSubOneVideoSuperviseMap(departId, timeValue);
  console.log(res.videoSuperviseMapIconVoList)
  console.log("地图数据来了");
  const mappedData = res.videoSuperviseMapIconVoList.map(item => {
    return {
      ...item,
      value: item.discoverProblem,
    };
  });
  const total = mappedData.reduce((sum, item) => sum + Number(item.value), 0);
  const avg = total / mappedData.length; // 计算平均值
  const range30Percent = avg * 0.3   // 不用取整，小数也可以
  mapIconList.value = mappedData
  option.value.series[0].data = mapIconList
  option.value.visualMap.pieces = [
    {gte: 0, lte: avg - range30Percent, label: "低于平均问题30%", color: "#4987F6"},
    {gte: avg - range30Percent, lte: avg + range30Percent + 0.1, label: "平均问题上下浮动30%内", color: "#F6A149"},
    {gte: avg + range30Percent, label: "高于平均问题30%", color: "#D34343"},
  ];
}

const getSubOneVideoSuperviseProblemTypeRateData = async (departId, timeValue) => {
  const res = await getSubOneVideoSuperviseProblemTypeRate(departId, timeValue);
  ProblemTypeRateChart.value.series[0].data = res.subOneVideoSuperviseProblemTypeRate
}


const getSubOneVideoSuperviseTrendData = async (departId, year) => {
  const res = await getSubOneVideoSuperviseTrend(departId, year);
  const temp = res.videoSuperviseTrendList;
  const categories = temp.map(item => item.name);
  const values = temp.map(item => item.value);
  proTrend.value.xAxis.data = categories;
  proTrend.value.series[0].data = values;
}
const getData = async () => {
  getMapJSON(currentDepartId)
  getSubOneVideoSuperviseProblemRankData(currentDepartId, time.value);
  getSubOneAllVideoSuperviseCountData(currentDepartId, time.value);
  getSubOneVideoSuperviseMapData(currentDepartId, time.value)
  getSubOneVideoSuperviseTrendData(currentDepartId, selectedYear.value)
  getSubOneVideoSuperviseProblemTypeRateData(currentDepartId, time.value)
}


// 卡片动画
const subOneProCardAnimation = () => {
  subOneProRankTab.value = (parseInt(subOneProRankTab.value) % 2 + 1).toString();
  setTimeout(subOneProCardAnimation, 3000);
};

// 地图动画
const subOneVideoMapAnimation = () => {
  const mySubOneVideoInspMapChart = subOneVideoInspMapChart?.value?.chart;
  if (!mySubOneVideoInspMapChart) return;
  // 获取随机数，介于0到当前地图数据长度之间
  const tempNum =  currentMapData?.value?.geoJson?.features?.length
  const randomNum = Math.floor(Math.random() * tempNum);
  mySubOneVideoInspMapChart.dispatchAction({
    type: "downplay", //downplay 取消高亮
    seriesIndex: 0,
  });
  mySubOneVideoInspMapChart.dispatchAction({
    type: "highlight", //highLight 高亮指定的数据图形
    seriesIndex: 0, //系列index
    dataIndex: randomNum, //数据index
  });
  mySubOneVideoInspMapChart.dispatchAction({
    type: "showTip", //showTip 显示提示框
    seriesIndex: 0,
    dataIndex: randomNum,
  });
};
// 启动定时器，每隔 2 秒执行一次
subOneVideoMapIntervalId = setInterval(subOneVideoMapAnimation, 2000);



onMounted(() => {
  getData();
  subOneProCardAnimation();  // 启动卡片动画
  setupEventListeners();  // 设置地图监听
})
// endregion

// region 事件||监听
watch(time, () => {
  getData()
})
const handleCommand = (year) => {
  selectedYear.value = year; // 更新当前选中的年份
  getSubOneVideoSuperviseTrendData(currentDepartId, selectedYear.value)
};


// 鼠标经过地图事件
const setupEventListeners = () => {
  const mySubOneVideoInspMapChart = subOneVideoInspMapChart?.value?.chart;
  // 鼠标移入
  mySubOneVideoInspMapChart.on('mousemove', (e) => {
    clearInterval(subOneVideoMapIntervalId);
    mySubOneVideoInspMapChart.dispatchAction({type: "downplay", seriesIndex: 0,});
    mySubOneVideoInspMapChart.dispatchAction({type: "highlight", seriesIndex: 0, dataIndex: e.dataIndex,});
    mySubOneVideoInspMapChart.dispatchAction({type: "showTip", seriesIndex: 0, dataIndex: e.dataIndex,});
  });
  // 鼠标移出
  mySubOneVideoInspMapChart.on('mouseout', () => {
    clearInterval(subOneVideoMapIntervalId); // 确保没有多个定时器同时运行
    subOneVideoMapIntervalId = setInterval(subOneVideoMapAnimation, 2000);
  });
};

// endregion

</script>


<style lang="scss" scoped>
@import "@/style/datav.scss";

img {
  width: 100%;
  display: block;
  border: 1px solid transparent;

  &.active {
    border-color: #1cd9ff;
  }
}

.message {
  padding: 10px;
  margin-bottom: 10px;
  background: linear-gradient(
          180deg,
          rgba(145, 145, 145, 0) 0%,
          rgba(164, 164, 164, 0.26) 98%
  );
  border: 1px solid;
  border-image: linear-gradient(
          180deg,
          rgba(255, 255, 255, 0.28),
          rgba(255, 255, 255, 0.26)
  ) 1 1;

  &.message-error {
    background: linear-gradient(
            180deg,
            rgba(208, 18, 18, 0) 0%,
            rgba(255, 0, 0, 0.26) 100%
    );
    border: 1px solid;
    border-image: linear-gradient(
            180deg,
            rgba(255, 71, 71, 0.59),
            rgba(251, 95, 95, 1)
    ) 1 1;

    .message-title {
      color: #ff0017;
    }
  }

  &.message-info {
    background: linear-gradient(
            180deg,
            rgba(18, 104, 208, 0) 0%,
            rgba(0, 166, 255, 0.26) 100%
    );
    border: 1px solid;
    border-image: linear-gradient(
            180deg,
            rgba(71, 209, 255, 0.28),
            rgba(8, 177, 255, 1)
    ) 1 1;

    .message-title {
      color: #1cd9ff;
    }
  }

  .message-title {
    font-size: 23px;
    font-weight: 700;
    margin-bottom: 10px;
    color: #597ae9;
  }

  .message-footer {
    font-size: 14px;
    color: #597ae9;
    margin-top: 10px;
  }
}


:deep() {
  // 弹框整体
  .tooltip {
    position: relative;
    width: 169.88px;
    height: 178px;
    background: linear-gradient(180deg, rgba(1, 4, 87, 0.8) 0%, rgba(3, 21, 119, 0.8) 100%);
    border: 1px solid #4E8FFF;
    margin: -10px -10px -10px -10px;
  }

  //浏阳市局
  .tooltip-title {
    width: 169.88px;
    height: 43px;
    background: linear-gradient(180deg, rgba(1, 4, 87, 0.8) 0%, rgba(3, 21, 119, 0.8) 100%);
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    text-align: center; /* 水平居中 */
    font-weight: 400;
    font-size: 16px;
    color: #FFFFFF;
    line-height: 22px;
    border-bottom: 1px solid #253755; /* 设置下边框 */
  }


  .tooltip-content {
    width: 170px;
    height: 132px;
    //font-size: 11px;
    margin-top: -12px;
    background: linear-gradient(180deg, #010457 0%, #031577 100%);
  }

  .tooltip-content ul {
    list-style-type: none; /* 移除默认的小圆点 */
    padding: 0;

  }

  .tooltip-content ul li {
    margin-left: 5px;
    height: 25px;
    color: #597AE9;
    font-size: 13px;
  }


  // 数字的span
  .tooltip-ul span {
    float: right;
    width: 30px;
    text-align: right;
    margin-right: 15px;
    color: #fff;
    font-size: 13px;
  }


  /* 小尖角 */
  .tooltip::before {
    content: '';
    position: absolute;
    top: 90px; /* 调整尖角的垂直位置 */
    left: -10px; /* 调整尖角的水平位置 */
    width: 0;
    height: 0;
    //border-top: 10px solid red; /* 顶边颜色 */
    //border-bottom: 10px solid green; /* 底边颜色 */
    //border-right: 10px solid blue; /* 右边颜色，与背景颜色相同 */
  }


}


.gobal-dropdown-container {
  position: absolute;
  right: 20px;
  top: 15px;
}

.test {
  width: 95px;
  height: 25px;
  background: #1C3472;
}

.gobal-dropdown-container {
  position: absolute;
  right: 20px;
  top: 15px;
}

.my-gobal-yearselect {
  font-size: 14px;
  padding-top: 6px;
  padding-left: 20px;
  width: 90px;
  color: #fff;
}


</style>