<template>
  <div class="app-container">
    <el-form :model="queryParams">
      <el-row>
        <el-col :span="10">
          <el-form-item label="日期范围">
            <el-date-picker
              v-if="showIndexTwo"
              disabled
              v-model="queryParams.value"
              type="daterange"
              value-format="yyyy-MM"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
            <el-date-picker
              disabled
              v-if="showIndexOne"
              v-model="queryParams.valueDay"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-input
            style="margin-left: -240px;"
            placeholder="请输入ICCID"
            v-model="queryParams.iccid"
            clearable>
          </el-input>
        </el-col>
        <el-button style="width: 7%;margin-left: -228px;" size="medium" :loading="loading" type="primary" round
                   @click="selCardUsage">
          统计
        </el-button>
        <el-button style="width: 7%;" size="medium" @click="resetQuery" round>重置</el-button>
      </el-row>
      <el-form-item label="上游规则：" v-if="showIndexOne">
        <p style="margin-top: 1px;
    margin-left: 73px;">仅支持查询近 <p style="color: rgb(255,0,0);margin-left: 170px;
    margin-top: -50px;">7天中某一天的数据</p>
          <p style="margin-left: 290px;margin-top: -50px;">，截止前一天</p></p>
      </el-form-item>
      <el-form-item label="上游规则：" v-if="showIndexTwo">
        <p style="margin-top: 1px;
    margin-left: 73px;">仅支持查询最近 6
          个月中某月的使用量，其中 <p style="color: rgb(255,0,0);margin-left: 365px;
    margin-top: -50px;">本月数据截止为前一天（每月 1 日不支持查询本月）</p></p>
      </el-form-item>
    </el-form>
    <br/>
    <div style="margin-top: -40px;">
      <el-tabs type="border-card" @tab-click="showIndex">
        <el-tab-pane label="按月统计">
          <div class="chart" ref="mychart" id="mychart" style="width: 1500px; height: 400px"></div>
        </el-tab-pane>
        <el-tab-pane label="按日统计">
          <div class="chart" ref="myDay" id="myDay" style="width: 1500px; height: 400px"></div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <br/>
    <div>
    </div>
  </div>
</template>
<script>
import {cardMonthUsage, listUsage} from "@/api/yunze/flowcard/usage";
import service from "@/utils/request";

export default {
  name: "index",
  data() {
    return {
      value: [],
      resDay: {},
      loading: false,
      msisdn: "",
      tableData: [],
      charts: null,
      value1: "",
      queryParams: {value: [], valueDay: []},
      showIndexOne: false,
      showIndexTwo: true
    }
  },
  created() {
  },
  mounted() {
    this.initDateRange();
    this.initDayTange();
    this.showDayChart();
    this.showIndexChart();
  },
  methods: {
    //统计按钮
    selCardUsage() {
      if (this.queryParams.iccid == undefined || this.queryParams.iccid == "") {
        this.$message.error("参数不能为空 ！")
        return;
      }
      if (this.showIndexOne == true) {
        let query = {
          dateTime: this.queryParams.valueDay,
          iccid: this.queryParams.iccid
        }
        this.loading = true;
        listUsage(query).then(res => {
          if (res.code == 200) {
            this.resDay = res.data;
            this.$message.success("操作成功 ！")
            this.showDayChart()
            this.loading = false;
          }
        },error => {
          this.loading = false;
        })
      }
      if (this.showIndexOne == false) {
        this.loading = true;
        let query = {
          dateTime: this.queryParams.value,
          iccid: this.queryParams.iccid
        }
        cardMonthUsage(query).then(res=>{
          if (res.code == 200) {
            this.resDay = res.data;
            this.loading = false;
            this.$message.success("操作成功 ！")
            this.showIndexChart();
          }
        },error => {
          this.loading = false;
        })
      }
    },
    //重置
    resetQuery() {
      this.queryParams.iccid = "";
    },

    //本周取值范围
    initDayTange() {
      var dateTime = new Date();
      dateTime = dateTime.setDate(dateTime.getDate() - 1);
      const end = new Date(dateTime); // 当前日期
      const start = new Date(new Date().getTime() - 3600 * 1000 * 24 * 7); // 七天前的日期
      // // 设置为当天的开始时间（可选，但通常对于范围选择很有用）
      // start.setHours(0, 0, 0, 0);
      // // 设置为当天的结束时间（对于范围选择通常是可选的，但这里我们保持它）
      // end.setHours(23, 59, 59, 999);
      var begin = this.formatDate(start);
      var ends = this.formatDate(end);
      this.queryParams.valueDay = [begin, ends];
    },
    formatDate(date) {
      function padZero(num) {
        return num < 10 ? '0' + num : num;
      }

      var year = date.getFullYear();
      var month = padZero(date.getMonth() + 1); // 月份是从0开始的
      var day = padZero(date.getDate());
      return year + '-' + month + '-' + day;
    },
    formatMonthDate(date) {
      function padZero(num) {
        return num < 10 ? '0' + num : num;
      }

      var year = date.getFullYear();
      var month = padZero(date.getMonth() + 1); // 月份是从0开始的
      return year + '-' + month;
    },
    //月取值范围
    initDateRange() {
      const today = new Date();
      const endMonth = today.getMonth(); // 当前月份
      const endYear = today.getFullYear(); // 当前年份

      // 计算开始月份和年份
      let startMonth = endMonth - 6;
      let startYear = endYear;
      // 如果开始月份小于0，则调整年份
      if (startMonth < 0) {
        startMonth;
        startYear--;
      }
      // 获取开始月份的最后一天
      const startDate = new Date(startYear, startMonth);
      // 获取当前月份的最后一天（或者你可以根据需要设置为今天）
      const endDate = new Date(endYear, endMonth);
      // 格式化日期为 yyyy-MM-dd 字符串（Element UI 需要的格式）
      // const startDateStr = `${startDate.getFullYear()}-${(startDate.getMonth() + 1).toString().padStart(2, '0')}`;
      // const endDateStr = `${endDate.getFullYear()}-${(endDate.getMonth() + 1).toString().padStart(2, '0')}`;
      // 将日期字符串转换为日期对象数组，并赋值给 value
      var start = this.formatMonthDate(startDate);
      var end = this.formatMonthDate(endDate);
      this.queryParams.value = [start, end];
    },
    showIndex(tab) {
      if (tab.index == 1) {
        this.showIndexOne = true;
        this.showIndexTwo = false;
      } else {
        this.showIndexOne = false;
        this.showIndexTwo = true;
      }
    },
    showIndexChart() {
      const chart = this.$echarts.init(this.$refs.mychart);
      const option = {
        title: {
          text: '月用量(MB)'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['usage']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.resDay.day == undefined ? ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] : this.resDay.day,
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '用量',
            type: 'line',
            stack: 'Total',
            data: this.resDay.usage == undefined ? [820, 932, 901, 934, 1290, 1330, 900] : this.resDay.usage,
            lineStyle: {
                      color: '#556FFD'
                    },
                    areaStyle: {
                      color: '#556FFD', // 区域颜色
                      opacity: 0.5 // 区域透明度
                    },
          }
        ]
      };
      chart.setOption(option);
    },
    showDayChart() {
      // const dom = document.querySelector("mychart");
      const day = this.$echarts.init(this.$refs.myDay);
      const options = {
        title: {
          text: '日用量(MB)'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['usage']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.resDay.day == undefined ? ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] : this.resDay.day,
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '用量',
            type: 'line',
            stack: 'Total',
            data: this.resDay.usage == undefined ? [820, 932, 901, 934, 1290, 1330, 900] : this.resDay.usage,
            lineStyle: {
              color: '#556FFD'
            },
            areaStyle: {
              color: '#556FFD', // 区域颜色
              opacity: 0.5 // 区域透明度
            },
          }
        ]
      };
      day.setOption(options);
    }
  }
}
</script>
<style scoped>

</style>
