<template>
  <div class="application-monitor">
    <!-- 右侧主内容区 -->
    <div class="main-content">
      <!-- 应用统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card" v-for="(item, index) in getLimitedList()" :key="item.name">
          <div class="stat-icon approved">
            <el-icon>
              <CircleCheckFilled v-if="index == 0" style="color: orange" />
              <Clock v-else-if="index == 1" style="color: greenyellow" />
              <UploadFilled v-else-if="index == 2" style="color: yellow" />
              <DeleteFilled v-else style="color: cadetblue" />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">{{ item.name }}</div>
            <div class="stat-number"><NumberScroll :value="item.value" :duration="2000" /> 个</div>
          </div>
        </div>
        <!-- <div class="stat-card">
          <div class="stat-icon approved">
            <el-icon><CircleCheckFilled /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">已审批应用</div>
            <div class="stat-number">490个</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon pending">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">待上架应用</div>
            <div class="stat-number">168个</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon online">
            <el-icon><UploadFilled /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">已上架应用</div>
            <div class="stat-number">43个</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon offline">
            <el-icon><DeleteFilled /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">已下架应用</div>
            <div class="stat-number">20个</div>
          </div>
        </div> -->
      </div>

      <!-- 内容模块 -->
      <div class="content-modules">
        <!-- 应用状态分布 -->
        <div class="module">
          <div class="module-header">
            <h3 class="module-title">应用状态分布</h3>
          </div>
          <div class="module-content">
            <div ref="statusChart" class="chart-container"></div>
          </div>
        </div>

        <!-- 快捷应用 -->
        <div class="module">
          <div class="module-header">
            <h3 class="module-title">应用趋势图</h3>
            <el-select
              v-model="selectedAppRange"
              size="small"
              style="width: 120px"
              @change="handleAppChange"
            >
              <el-option
                v-for="item in selectAapplications"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
            <div>
              <el-date-picker
                size="small"
                :clearable="false"
                v-model="datetimeValue"
                type="daterange"
                @change="handleDateChange"
                :shortcuts="shortcuts"
                format="YYYY-MM-DD"
                range-separator="到"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </div>
            <!-- <a href="#" class="module-more">更多</a> -->
          </div>
          <div class="module-content">
            <div ref="lineChartRes" class="chart-container"></div>
            <!-- <div class="quick-app" v-for="(app, index) in quickApps" :key="index">
              <div class="app-item">
                <span class="app-icon" :style="{ backgroundColor: getAppColor(app.type) }"
                  ><el-icon><Promotion /></el-icon
                ></span>
                <span class="app-name">{{ app.name }}</span>
              </div>
            </div> -->
          </div>
        </div>

        <!-- 应用上新 -->
        <div class="module">
          <div class="module-header">
            <h3 class="module-title">应用上新</h3>
            <!-- <a href="#" class="module-more">更多</a> -->
          </div>
          <div class="module-content">
            <div class="new-app" v-for="(app, index) in newApplications" :key="index">
              <div class="app-info">
                <span class="app-name">{{ app.title }} </span>
                <span class="app-date">{{ app.createTime }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 应用热度排行TOP5 -->
        <div class="module">
          <div class="module-header">
            <h3 class="module-title">应用热度排行TOP5</h3>
            <!-- <a href="#" class="module-more">更多</a> -->
          </div>
          <div class="module-content">
            <div class="hot-app" v-for="(app, index) in hotApps" :key="index">
              <div class="app-rank">
                <span class="rank-number">{{ index + 1 }}</span>
                <span class="app-name">{{ app.name }}</span>
              </div>
              <div class="app-stats">
                <!-- <div class="stat-bar" :style="{ width: app.percentage + '%' }"></div> -->
                <div style="width: 100%">
                  <el-progress :percentage="app.percentage" />
                </div>
                <span class="stat-count">{{ app.count }}次</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import appCenter from "@/api/appCenter";
import { topApp, countAppInfo, getAppList } from "@/api/count";
import moment from "moment";
import NumberScroll from "@/components/AppVue/numberScroll.vue";
export default {
  name: "ApplicationMonitor",
  components: {
    NumberScroll,
  },
  data() {
    return {
      statusChart: null,
      lineChart: null,
      itemApplications: [],
      applications: [],
      newApplications: [],
      statusOptions: [],
      buffOptions: [],
      typeArrs: [],
      selectAapplications: [],
      selectedAppRange: "",
      datetimeValue: [
        new Date(new Date(new Date().setMonth(new Date().getMonth() - 1))).setDate(
          new Date().getDate() + 1
        ),
        new Date(),
      ], // 默认显示最近一个月
      shortcuts: [
        {
          text: "当天",
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setDate(start.getDate());
            return [start, end];
          },
        },
        {
          text: "最近一周",
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setDate(start.getDate() - 7);
            start.setDate(start.getDate() + 1);
            return [start, end];
          },
        },
        {
          text: "最近1月",
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setMonth(start.getMonth() - 1);
            start.setDate(start.getDate() + 1);
            return [start, end];
          },
        },
        {
          text: "最近1年",
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setFullYear(start.getFullYear() - 1);
            start.setDate(start.getDate() + 1);
            return [start, end];
          },
        },
        // {
        //   text: 'Last 3 months',
        //   value: () => {
        //     const end = new Date()
        //     const start = new Date()
        //     start.setMonth(start.getMonth() - 3)
        //     return [start, end]
        //   },
        // },
      ],
      // 快捷应用数据
      quickApps: [
        { name: "农产品安全管控示范应用场", type: "green" },
        { name: "崇明区乡村振兴一张图", type: "yellow" },
        { name: "数字孪生黄浦", type: "blue" },
      ],

      // 应用热度排行数据
      hotApps: [],
    };
  },
  mounted() {
    this.initData();
    window.addEventListener("resize", this.handleResize);
  },
  beforeUnmount() {
    window.removeEventListener("resize", this.handleResize);
    this.destroyCharts();
  },
  methods: {
    initData() {
      this.getDmsCNameAType("applevel");
      this.getDmsCNameAType("appstatus");
      this.getDmsDataList();
      let param = {
        num: 6,
        start: "2000-01-01",
        end: moment().format("YYYY-MM-DD"),
      };
      this.getAppCount(param);
    },
    // 获取应用统计数据
    getAppCount(param) {
      let that = this;
      that.hotApps = [];
      topApp(param.num, param.start, param.end).then((res) => {
        let maxv = 100;
        res.forEach((item, index) => {
          if (index < 5) {
            if (index === 0) {
              maxv = item.count;
            }
            item.percentage = ((item.count / maxv) * 100).toFixed(1);
            let str = {
              name: item.name.trim() == "" ? "其他" : item.name,
              count: item.count,
              percentage: item.percentage,
            };
            that.hotApps.push(str);
          }
        });
        //  console.log(that.hotApps);
      });
    },
    handleAppChange() {
      // console.log(this.selectedAppRange);
      this.getCountAppInfo();
    },
    handleDateChange() {
      // console.log(this.datetimeValue);
      this.getCountAppInfo();
    },
    //获取应用统计Charts图表
    getCountAppInfo() {
      let start = moment(this.datetimeValue[0]).format("YYYY-MM-DD 00:00:00");
      let end = moment(this.datetimeValue[1]).format("YYYY-MM-DD 23:59:59");
      countAppInfo(start, end, this.selectedAppRange).then((res) => {
        // console.log(res);
        this.drawLineChart(res);
      });
    },
    drawLineChart(data) {
      let that = this;
      let times = [];
      let values = [];
      data.forEach((item, index) => {
        times.push(moment(item.time).format("YYYY-MM-DD"));
        values.push(item.count);
      });
      // 基于准备好的dom，初始化echarts实例
      let lineChart = echarts.init(this.$refs.lineChartRes);
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          backgroundColor: "rgba(0, 25, 50, 0.8)",
          borderColor: "#1E90FF",
          textStyle: {
            color: "#fff",
          },
          formatter: function (params) {
            let str = "";
            params.forEach((item) => {
              str += `${item.name} <br/> ${item.seriesName}: ${item.value}次<br/>`;
            });
            return str;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: times,
          axisLabel: {
            color: "#a3b6c7",
          },
          axisLine: {
            lineStyle: {
              color: "#1E90FF",
            },
          },
        },
        yAxis: {
          type: "value",
          axisLabel: {
            color: "#a3b6c7",
          },
          axisLine: {
            lineStyle: {
              color: "#1E90FF",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(30, 144, 255, 0.2)",
            },
          },
        },
        series: [
          {
            name: "调用次数",
            type: "line",
            data: values,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#1E90FF" },
                { offset: 1, color: "#00BFFF" },
              ]),
            },
          },
        ],
      };
      // 绘制图表
      lineChart.setOption(option);
      that.lineChart = lineChart;
    },
    handleResize() {
      if (this.statusChart) this.statusChart.resize();
      if (this.lineChart) this.lineChart.resize();
    },
    destroyCharts() {
      if (this.statusChart) {
        this.statusChart.dispose();
        this.statusChart = null;
      }
      if (this.lineChart) {
        this.lineChart.dispose();
        this.lineChart = null;
      }
    },
    getLimitedList() {
      return this.typeArrs.slice(0, 4); // 获取前四个元素
    },
    getDmsCNameAType(param) {
      if (param === "applevel") {
        this.buffOptions = [];
        let obj = this.$getDmsTypes("applevel");
        for (let key in obj) {
          this.buffOptions.push({
            label: key,
            value: obj[key],
          });
        }
      } else if (param === "appstatus") {
        this.statusOptions = [];
        let obj = this.$getDmsTypes("appstatus");
        for (let key in obj) {
          this.statusOptions.push({
            label: key,
            value: obj[key],
          });
        }
      }
      // let requestParams = {
      //   cName: param,
      //   type: 0,
      // };
      // appCenter.getDmsCNameAType(requestParams).then((res) => {
      //   if (res.code === 200 && res.content) {
      //     let option = res.content.map((item) => ({
      //       label: item.index,
      //       value: item.name,
      //     }));
      //     if (param === "applevel") {
      //       this.buffOptions = option;
      //     } else if (param === "appstatus") {
      //       this.statusOptions = option;
      //     }
      //   }
      // });
    },
    getDmsDataList() {

      let param = {
        start: "2000-01-01",
        end: moment().format("YYYY-MM-DD"),
      };
      getAppList(param.start, param.end).then((res) => {
        // console.log("=======getAppList======"+res);
        this.selectAapplications = res;
        this.selectAapplications.forEach((item) => {
          if(item.name.includes("华新镇")){
              this.selectedAppRange = item.name;
              return;
          }
        });

        let requestParams = {
          columnId: systemConfig.columnIds[1], // 应用中心栏目id
          states: 0,
          orderBy: JSON.stringify([{ field: "create_time", orderByType: 2 }]),
          pageSize: 9999,
          page: 0,
        };
        appCenter.getDmsDataList(requestParams).then((res) => {
          if (res.code === 200) {
            this.itemApplications = res.content.data.map((item) => ({
              ...item,
              status:
                item.status === 0
                  ? "待审核"
                  : item.status === 1
                    ? "待发布"
                    : item.status === 2
                      ? "未完成"
                      : "已完成",
              buffName:
                this.buffOptions.find((info) => info.label == item.appbuff.trim())?.value || "",
              appstautName:
                this.statusOptions.find((info) => info.label == item.appstauts.trim())?.value || "",
              createTime: moment(item.create_time).format("YYYY-MM-DD HH:mm:ss"),
            }));
            this.applications = this.itemApplications;
            // this.selectAapplications = this.applications.filter((item) => item.yylx == "0"); //yylx 0:内部 1:外部
            this.newApplications = this.applications.slice(0, 10); // 获取前十个元素
            // this.selectedAppRange = this.applications[0].title;
            this.getTypeArrs();
            this.getCountAppInfo();
          } else {
            this.applications = [];
            this.selectAapplications = [];
            this.selectedAppRange = "";
          }
        });
      });
    },
    getTypeArrs() {
      let that = this;
      that.statusOptions.forEach((item) => {
        let arr = this.applications.filter((info) => info.appstauts == item.label);
        let name = item.value,
          length = arr.length;
        let str = { name: name, value: length };
        that.typeArrs.push(str);
      });
      this.initStatusChart();
    },
    initStatusChart() {
      let colors = ["#52C41A", "#FAAD14", "#F5222D", "#1E90FF"];
      let seriesData = this.typeArrs.map((item, index) => ({
        // value: item.value, name: item.name, itemStyle: { color: colors[index] }  //自定义颜色
        value: item.value,
        name: item.name, // 随机颜色
      }));
      seriesData = seriesData.filter((item) => item.value > 0); // 过滤掉值为0的项
      this.statusChart = echarts.init(this.$refs.statusChart);
      const option = {
        tooltip: {
          trigger: "item",
          backgroundColor: "rgba(0, 25, 50, 0.8)",
          borderColor: "#1E90FF",
          textStyle: {
            color: "#fff",
          },
        },
        legend: {
          orient: "horizontal",
          bottom: 0,
          textStyle: {
            color: "#a3b6c7",
          },
        },
        series: [
          {
            name: "应用状态分布",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#0A192F",
              borderWidth: 2,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 20,
                fontWeight: "bold",
                color: "#fff",
              },
            },
            labelLine: {
              show: false,
            },
            data: seriesData,
          },
        ],
      };
      this.statusChart.setOption(option);
    },
    // 获取应用图标的背景颜色
    getAppColor(type) {
      const colorMap = {
        green: "rgba(103, 194, 58, 0.2)",
        yellow: "rgba(230, 162, 60, 0.2)",
        blue: "rgba(64, 158, 255, 0.2)",
      };
      return colorMap[type] || "rgba(64, 158, 255, 0.2)";
    },
  },
};
</script>

<style lang="less" scoped>
.application-monitor {
  width: 100%;
  background-color: #00002a;
  color: #ffffff;
}

/* 右侧主内容区 */
.main-content {
  flex: 1;
  // padding: 20px 30px;
  padding: 20px 30px 100px 20px;
  overflow-y: auto;
}

/* 统计卡片 */
.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 200px;
  height: 100px;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  transition: all 0.3s ease;

  &:hover {
    background-color: rgba(255, 255, 255, 0.08);
  }
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;

  &.approved {
    background-color: rgba(64, 158, 255, 0.2);
    color: #409eff;
  }

  &.pending {
    background-color: rgba(230, 162, 60, 0.2);
    color: #e6a23c;
  }

  &.online {
    background-color: rgba(103, 194, 58, 0.2);
    color: #67c23a;
  }

  &.offline {
    background-color: rgba(245, 108, 108, 0.2);
    color: #f56c6c;
  }
}

.stat-content {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.stat-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.6);
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #ffffff;
}

/* 内容模块 */
.content-modules {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 20px;
}

/* 模块通用样式 */
.module {
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  overflow: hidden;
}

.module-header {
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.module-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0;
  color: #ffffff;
}

.module-more {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  text-decoration: none;

  &:hover {
    color: #409eff;
  }
}

.module-content {
  padding: 20px;
  height: 320px;
  overflow: auto;
}

/* 应用状态分布图 */
.chart-container {
  width: 100%;
  height: 300px;
}

/* 快捷应用 */
.quick-app {
  margin-bottom: 15px;
}

.app-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  transition: all 0.3s ease;

  &:hover {
    background-color: rgba(255, 255, 255, 0.08);
  }
}

.app-icon {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 14px;
}

.app-name {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 应用上新 */
.new-app {
  // margin-bottom: 15px;
  // padding-bottom: 15px;
  padding: 6px 0px 6px 0px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);

  &:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
  }
}

.app-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.app-date {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

/* 使用热度排行 */
.hot-app {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.app-rank {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rank-number {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.app-stats {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stat-bar {
  flex: 1;
  height: 6px;
  background-color: #409eff;
  border-radius: 3px;
}

.stat-count {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  min-width: 100px;
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content-modules {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(4, auto);
  }

  .stats-cards {
    flex-direction: column;
  }

  .stat-card {
    min-width: auto;
  }
}
</style>
