<template>
  <div class="app-container" style="background-color: #F7F7F7;height: 100%;overflow: auto;">
    <div class="gw-statistic-row" style="height: 12vh;">
      <gw-statistic v-for="item in statisticData" :key="item.name" :name="item.name" :value="item.value"
                    :color="item.color">

      </gw-statistic>
    </div>
    <div class="gw-statistic-row" style="height: 30vh;">
      <gw-card style="width: 50%;">
        <template v-slot:title>
          <span>模型服务接口统计</span>
        </template>
        <gw-echart ref="top9Ref"></gw-echart>
      </gw-card>
      <!--      <gw-card style="width: 33%;">-->
      <!--        <template v-slot:title>-->
      <!--          <span>模型计算结果统计</span>-->
      <!--        </template>-->
      <!--        <gw-echart ref="top10Ref"></gw-echart>-->
      <!--      </gw-card>-->
      <gw-card style="width: 50%;">
        <template v-slot:title>
          <div style="display: flex;align-items: center;justify-content: space-between;">
            <div>
              <span>模型计算成功统计</span>
            </div>
            <el-segmented v-model="dateType" :options="dateTypeOptions" @change="initChartTop11"/>
          </div>
        </template>
        <gw-echart ref="top11Ref"></gw-echart>
      </gw-card>
    </div>
    <div class="gw-statistic-row" style="height: 30vh;">
      <gw-card style="width: 50%;">
        <template v-slot:title>
          <div style="display: flex;align-items: center;justify-content: space-between;">
            <div>模型调用次数</div>
            <el-segmented v-model="dateType" :options="dateTypeOptions" @change="initChartTop3"/>
          </div>
        </template>
        <gw-echart ref="top3Ref"></gw-echart>
      </gw-card>
      <gw-card style="width: 50%;">
        <template v-slot:title>
          <div style="display: flex;align-items: center;justify-content: space-between;">
            <div>
              <span>应用调用统计</span>
              <span style="color: #79bbff;">&nbsp;{{ todayModelCallCount }}&nbsp;</span>
              <span>次</span>
            </div>
            <el-segmented v-model="dateType" :options="dateTypeOptions" @change="initChartTop1"/>
          </div>
        </template>
        <gw-echart ref="top1Ref"></gw-echart>
      </gw-card>
      <!--      <gw-card style="width: 30%;">-->
      <!--        <template v-slot:title>-->
      <!--          <div style="display: flex;align-items: center;font-weight: bold;width: 100%;">-->
      <!--            <div style="">模型服务调用次数</div>-->
      <!--            <div style="width: 50%;margin-left: 20%;">-->
      <!--              <el-select v-model="userId" class="m-2" placeholder="选则用户" style="width: 100%;"-->
      <!--                         @change="initChartTop2">-->
      <!--                <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value"/>-->
      <!--              </el-select>-->
      <!--            </div>-->
      <!--          </div>-->
      <!--        </template>-->
      <!--        <gw-echart ref="top2Ref"></gw-echart>-->
      <!--      </gw-card>-->
    </div>
    <div class="gw-statistic-row" style="height: 30vh;">
      <gw-card style="width: 50%;">
        <template v-slot:title>
          <div style="display: flex;align-items: center;justify-content: space-between;">
            <div>
              <span>任务统计</span>
            </div>
            <el-segmented v-model="task" :options="taskOptions" @change="initChartTop5"/>
          </div>
        </template>
        <gw-echart ref="top5Ref"></gw-echart>
      </gw-card>
      <gw-card style="width: 50%;">
        <template v-slot:title>
          <div style="display:flex;align-items: center;">
            <span style="margin-right: 5px;">报警信息</span>
            <el-tag type="danger" effect="dark" size="small">{{ alarmTableData.length }}</el-tag>
          </div>
        </template>
        <el-table stripe :data="alarmTableData" size="small" height="100%">
          <el-table-column align="center" width="120" prop="tm" label="报警时间">
            <template #default="scope">
              {{ scope.row.alertTime ? scope.row.alertTime.substring(5, 16) : '' }}
            </template>
          </el-table-column>
          <el-table-column align="center" width="100" prop="alertType" label="报警类型">
            <template #default="scope">
              <el-tag size="small" v-if="scope.row.alertType == '1'" type="danger">
                {{ alertTypeConversion(scope.row.alertType) }}
              </el-tag>
              <el-tag size="small" v-else-if="scope.row.alertType == '2'" type="warning">
                {{ alertTypeConversion(scope.row.alertType) }}
              </el-tag>
              <el-tag size="small" v-else type="info">{{ alertTypeConversion(scope.row.alertType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" width="150" prop="modelName" label="模型名称"/>
          <el-table-column align="center" prop="alertContent" label="报警内容"/>
        </el-table>
      </gw-card>
    </div>
    <!--    <div class="gw-statistic-row" style="height: 30vh;">-->
    <!--      <gw-card>-->
    <!--        <template v-slot:title>-->
    <!--          <div style="width: 100%;display: flex;justify-content: flex-end;">-->
    <!--            <el-select-->
    <!--                v-model="dateType"-->
    <!--                class="m-2"-->
    <!--                style="width: 20%;"-->
    <!--                @change="initChartBottom1"-->
    <!--              <el-option-->
    <!--                  v-for="item in dateTypeOptions"-->
    <!--                  :key="item.value"-->
    <!--                  :label="item.label"-->
    <!--                  :value="item.value"-->
    <!--              />-->
    <!--            </el-select>-->
    <!--          </div>-->
    <!--        </template>-->
    <!--        <gw-echart ref="bt1Ref"></gw-echart>-->
    <!--      </gw-card>-->
    <!--    </div>-->
    <!--    <div class="gw-statistic-row" style="height: 40vh;">-->
    <!--      <div class="gw-statistic-body">-->
    <!--        <el-row :gutter="10" style="height: 100%;">-->
    <!--          <el-col :span="15" style="height: 100%;position: relative;">-->
    <!--            <div class="title">访问来源追溯</div>-->
    <!--            <div style="height: calc(100% - 20px)">-->
    <!--              <div id="visit_source_chart" class="chart_container"></div>-->
    <!--            </div>-->
    <!--          </el-col>-->
    <!--          <el-col :span="9" class="visit_number" style="height: 100%;">-->
    <!--            <div class="title">访问次数排行</div>-->
    <!--            <div style="height: calc(100% - 20px)">-->
    <!--              <div id="visit_number_chart" class="chart_container"></div>-->
    <!--            </div>-->
    <!--          </el-col>-->
    <!--        </el-row>-->
    <!--      </div>-->
    <!--    </div>-->
  </div>
</template>
<script setup>
import {onMounted} from 'vue';
import * as echarts from 'echarts';
import GwStatistic from "@/views/monitor/service/GwStatistic.vue";
import {
  getModelCallCount,
  getModelServiceCount,
  getModelServiceSuccessCount,
  getModelTypeCallCount,
  getStatisticData,
  getUserModelCallCount,
  getViewNumByCity
} from "@/api/monitor/server.js";
import {initEchartMap} from "@/utils/echarts/chinaMap.js";
import GwCard from "@/views/monitor/service/GwCard.vue";
import GwEchart from "@/components/chart/GwEchart.vue";
import {listUser} from "@/api/system/user.js";
import {parseTime} from "@/utils/ruoyi.js";
import {getAlarmList} from "@/api/service/alarm.js";

const statisticData = ref([
  {name: '当前服务总数', value: 0, color: '#477ACF'},
  {name: '服务在线比率', value: '0%', color: '#40B0D7'},
  {name: '模型服务支撑健康指数', value: '无', color: '#2DBEA2'},
  {name: '当月热点服务', value: '无', color: '#487ACF'},
  {name: '累计调用次数', value: '0', color: '#4BBA9B'},
])
const todayModelCallCount = ref(0)
const userId = ref(null)
const userOptions = ref([])
listUser().then(res => {
  userOptions.value = res.rows.map(item => {
    return {
      label: item.nickName,
      value: item.userId
    }
  })

})
const top1Ref = ref(null)
const top2Ref = ref(null)
const top3Ref = ref(null)
const top5Ref = ref(null)
const top9Ref = ref(null)
const top10Ref = ref(null)
const top11Ref = ref(null)
const modelTypeCallCount = ref(0)

const dateType = ref('5')
const dateTypeOptions = ref([
  {label: '今日', value: '1'},
  {label: '近三日', value: '2'},
  {label: '近一周', value: '3'},
  {label: '近一个月', value: '4'},
  {label: '全部', value: '5'},
])
const task = ref('1')
const taskOptions = ref([
  {label: '日执行量', value: '1'},
  {label: '月执行量', value: '2'},
])
const bt1Ref = ref(null)
const echartMapData = ref([])
const alarmTableData = ref([
  {tm: '09-12 11:12', type: '格式异常', modelName: '上海沿海风暴潮预报模型', content: '调用返回异常'},
  {tm: '09-11 11:12', type: '请求异常', modelName: '上海沿海风暴潮预报模型', content: '模型连接失败'},
  {tm: '09-10 11:12', type: '服务器未响应', modelName: '上海沿海风暴潮预报模型', content: '服务器报错'},
])

function getTimes(dateType) {
  let startTime = null, endTime = null
  const date = new Date()
  switch (dateType) {
    case '1':
      startTime = parseTime(new Date(), '{y}-{m}-{d}') + ' 00:00:00'
      date.setDate(date.getDate() + 1)
      endTime = parseTime(date, '{y}-{m}-{d}') + ' 00:00:00'
      break;
    case '2':
      endTime = parseTime(new Date())
      date.setDate(date.getDate() - 3)
      startTime = parseTime(date)
      break;
    case '3':
      endTime = parseTime(new Date())
      date.setDate(date.getDate() - 7)
      startTime = parseTime(date)
      break;
    case '4':
      endTime = parseTime(new Date())
      date.setDate(date.getDate() - 30)
      startTime = parseTime(date)
      break;
    default:
  }
  return {startTime, endTime}
}

function initChartTop1() {
  const params = {}
  const {startTime, endTime} = getTimes(dateType.value)
  params.startTime = startTime
  params.endTime = endTime
  getModelCallCount(params).then(res => {
    let chartData = res.data
    todayModelCallCount.value = chartData.map(item => item.TOTAL).reduce((acc, current) => acc + current, 0);
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '0%',
        top: '10%',
        containLabel: true
      },
      xAxis: {
        // splitLine: {show: false},
        axisLabel: {
          rotate: 10 // 设置标签旋转45度
        },
        data: chartData.map(item => item.APPNAME),
      },
      yAxis: {
        type: 'value',
        name: '次',
        // splitLine: {show: false}
      },
      series: [
        {
          data: chartData.map(item => item.TOTAL),
          type: 'bar',
          itemStyle: {
            normal: {
              // 这里就可以实现，配置柱状图的颜色
              color: function (params) {
                const colorList = ['#477ACF', '#40B0D7', '#2DBEA2', '#487ACF', '#4BBA9B', '#529b2e', '#95d475', '#b3e19d', '#d1edc4'];
                return colorList[params.dataIndex]
              },
            }
          },
          label: {
            show: true,   // 启用标签
            position: 'top' // 位置：顶部（可选 'inside'、'bottom' 等）
          }
        }
      ]
    };
    top1Ref.value.loadChart(option);
  })
}

function initChartTop2() {
  getUserModelCallCount(userId.value).then(res => {
    let chartData = res.data.map(item => {
      return {
        name: item.serviceName,
        value: item.TOTAL
      }
    })
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '90%',
        left: 'center'
      },
      series: [
        {
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'outside',
            formatter: '{c}',
          },
          labelLine: {
            show: true
          },
          color: ['#80D0F8', '#3384C2', '#14D3D4', '#69F3C0'],
          data: chartData
        }
      ]
    }
    top2Ref.value.loadChart(option)
  })
}

function initChartTop3() {
  const params = {}
  const {startTime, endTime} = getTimes(dateType.value)
  params.startTime = startTime
  params.endTime = endTime
  getModelTypeCallCount(params).then(res => {
    modelTypeCallCount.value = res.data.map(item => item.TOTAL).reduce((acc, current) => acc + current, 0);
    let chartData = res.data.map(item => {
      return {
        name: item.NAME,
        value: item.TOTAL
      }
    })
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '0%',
        top: '10%',
        containLabel: true
      },
      legend: {
        type: "scroll",
        top: '90%',
        left: 'center'
      },
      series: [
        {
          name: '调用次数',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'outside',
            formatter: '{b} : {c} ({d}%)',
          },
          labelLine: {
            show: true
          },
          // color: ['#529b2e', '#95d475', '#b3e19d', '#d1edc4'],
          data: chartData
        }
      ]
    };
    top3Ref.value.loadChart(option)
  })
}

function initChartTop9() {
  getModelServiceCount().then(res => {
    modelTypeCallCount.value = res.data.map(item => item.TOTAL).reduce((acc, current) => acc + current, 0);
    let chartData = res.data.map(item => {
      return {
        name: item.NAME,
        value: item.TOTAL
      }
    })
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '0%',
        top: '10%',
        containLabel: true
      },
      legend: {
        type: "scroll",
        top: '90%',
        left: 'center'
      },
      series: [
        {
          name: '接口个数',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'outside',
            formatter: '{b} : {c} ({d}%)',
          },
          labelLine: {
            show: true
          },
          // color: ['#529b2e', '#95d475', '#b3e19d', '#d1edc4'],
          data: chartData
        }
      ]
    };
    top9Ref.value.loadChart(option)
  })
}

function initChartTop11() {
  const params = {}
  const {startTime, endTime} = getTimes(dateType.value)
  params.startTime = startTime
  params.endTime = endTime
  getModelServiceSuccessCount(params).then(res => {
    let rawData = [
      res.data.map(item => item.SUCCESS),
      res.data.map(item => item.FAIL)
    ]
    const totalData = [];
    for (let i = 0; i < rawData[0].length; ++i) {
      let sum = 0;
      for (let j = 0; j < rawData.length; ++j) {
        sum += rawData[j][i];
      }
      totalData.push(sum);
    }
    const series = ['成功', '失败'].map((name, sid) => {
      return {
        name,
        type: 'bar',
        stack: 'total',
        barWidth: '60%',
        label: {
          show: true,
          formatter: (params) => Math.round(params.value * 1000) / 10 + '%'
        },
        data: rawData[sid].map((d, did) =>
            totalData[did] <= 0 ? 0 : d / totalData[did]
        )
      };
    });
    const option = {
      legend: {
        selectedMode: false
      },
      tooltip: {
        trigger: 'item'
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '0%',
        top: '20%',
        containLabel: true
      },
      yAxis: {
        type: 'value'
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          interval: 0,
          rotate: 10 // 设置标签旋转45度
        },
        data: res.data.map(item => item.NAME)
      },
      series
    };
    top11Ref.value.loadChart(option)
  })
}

function initChartBottom1() {
  const params = {}
  const {startTime, endTime} = getTimes(dateType.value)
  params.startTime = startTime
  params.endTime = endTime

  getModelCallCount(params).then(res => {
    const chartData = res.data
    const option = {
      tooltip: {},
      grid: {
        left: '5%',
        right: '5%',
        bottom: '10%',
        top: '18%',
        containLabel: true
      },
      xAxis: {
        data: chartData.map(item => item.name),
      },
      yAxis: {
        type: 'value',
        name: '次',
        // splitLine: {show: false}
      },
      series: [
        {
          name: 'Access From',
          data: chartData.map(item => item.TOTAL),
          type: 'bar',
          label: {
            show: true,   // 启用标签
            position: 'top' // 位置：顶部（可选 'inside'、'bottom' 等）
          }
        }
      ]
    };
    bt1Ref.value.loadChart(option)
  })
}

function initChartBottom2() {
  var chartDom = document.getElementById('bt2');
  var myChart = echarts.init(chartDom);
  var option;

  option = {
    radar: {
      // shape: 'circle',
      indicator: [
        {name: 'Sales', max: 6500},
        {name: 'Administration', max: 16000},
        {name: 'Information Technology', max: 30000},
        {name: 'Customer Support', max: 38000},
        {name: 'Development', max: 52000},
        {name: 'Marketing', max: 25000}
      ]
    },
    series: [
      {
        name: 'Budget vs spending',
        type: 'radar',
        data: [
          {
            value: [4200, 3000, 20000, 35000, 50000, 18000],
            name: 'Allocated Budget'
          },
          {
            value: [5000, 14000, 28000, 26000, 42000, 21000],
            name: 'Actual Spending'
          }
        ]
      }
    ]
  };

  option && myChart.setOption(option);
}

function initChartTop5() {
  const option = {
    legend: {},
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      showContent: false
    },
    dataset: {
      source: [
        ['模型', '09-07', '09-08', '09-09', '09-10', '09-11', '09-12'],
        ['上海沿海风暴潮预报模型', 56.5, 82.1, 88.7, 70.1, 53.4, 85.1],
        ['马斯京根法', 51.1, 51.4, 55.1, 53.3, 73.8, 68.7],
        ['三水源新安江产流模型', 40.1, 62.2, 69.5, 36.4, 45.2, 32.5],
        ['上海市中心城区排水系统模型', 25.2, 37.1, 41.2, 18, 33.9, 49.1]
      ]
    },
    xAxis: {type: 'category'},
    yAxis: {gridIndex: 0},
    series: [
      {
        type: 'line',
        smooth: true,
        seriesLayoutBy: 'row',
        emphasis: {focus: 'series'}
      },
      {
        type: 'line',
        smooth: true,
        seriesLayoutBy: 'row',
        emphasis: {focus: 'series'}
      },
      {
        type: 'line',
        smooth: true,
        seriesLayoutBy: 'row',
        emphasis: {focus: 'series'}
      },
      {
        type: 'line',
        smooth: true,
        seriesLayoutBy: 'row',
        emphasis: {focus: 'series'}
      }
    ]
  };
  top5Ref.value.loadChart(option);
}

function initVisitNumberChart(name, data) {
  data.sort((a, b) => b.value - a.value)
  let d = data.slice(0, 9)
  let yAxisData = []
  let seriesData = []
  for (let i in d) {
    yAxisData.push(d[i].name)
    seriesData.push(d[i].value)
  }

  // 初始化echarts实例
  let chart = echarts.init(document.getElementById(name))
  // 绘制图表
  let option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01],
    },
    yAxis: {
      type: 'category',
      data: yAxisData,
    },
    series: [
      {
        name: '访问次数',
        type: 'bar',
        data: seriesData,
      },
    ],
  }
  chart.setOption(option)
}

/** 获取统计数据 */
function initStatisticData() {
  getStatisticData().then((r) => {
    statisticData.value = r.data
  })
}

/** 访问来源追溯 */
function initViewNumByCity() {
  getViewNumByCity().then((r) => {
    echartMapData.value = r.data
    // 初始化地图
    initEchartMap('visit_source_chart', echartMapData.value)
    initVisitNumberChart('visit_number_chart', echartMapData.value)
  })
}

/** 获取模型服务调用次数 */
function getAlarmData() {
  getAlarmList().then(res => {
    alarmTableData.value = res.data
  })
}

function alertTypeConversion(alertType) {
  switch (alertType) {
    case '1':
      return '服务器异常'
    case '2':
      return '接口异常'
    case '3':
      return '返回信息异常'
    default:
      return ''
  }
}

onMounted(() => {
  initStatisticData()

  initChartTop1()
  // initChartTop2()
  initChartTop3()
  initChartTop5()
  initChartTop9()
  initChartTop11()
  // initChartBottom1()
  // initChartBottom2()
  // initViewNumByCity()

  getAlarmData()
});
</script>
<style scoped lang="scss">
.boxShadow {
  box-shadow: -8px 0 15px -10px rgba(0, 0, 0, 0.1), /* 左侧阴影 */
  8px 0 15px -10px rgba(0, 0, 0, 0.1); /* 右侧阴影 */
  transition: box-shadow 0.3s ease;

}

.gw-statistic-row {
  display: flex;
  align-content: center;
  gap: 10px;
  margin-bottom: 10px;

  .gw-statistic-body {
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
    width: 100%;
    height: 100%;
    border-radius: 8px;
    background: #fff;
    padding: 15px 20px;

    .title {
      font-weight: bold;
      margin: 0;
    }


  }

}

.chart_container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>