<template>
    <div class="app-container">
      <el-card>
        <div slot="header" class="clearfix">
          <span>设备绑定统计</span>
        </div>

        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="按天统计" name="daily">
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item label="日期">
                <el-date-picker
                  v-model="dailyDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                  @change="handleDailyDateChange"
                ></el-date-picker>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="searchDaily">查询</el-button>
                <el-button @click="resetDaily">重置</el-button>
                <el-button type="success" @click="exportDaily">导出</el-button>
              </el-form-item>
            </el-form>

            <el-table
              v-loading="dailyLoading"
              border
              :data="companyList"
              style="width: 100%"
            >
              <el-table-column prop="date" label="日期" width="180" />
              <el-table-column prop="companyName" label="公司名称" />
              <el-table-column prop="bindCount" label="绑定台数" />
            </el-table>

            <div class="chart-container" style="margin-top: 20px; height: 400px">
              <div ref="dailyChart" style="height: 100%; width: 100%"></div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="按月统计" name="monthly">
            <el-form :inline="true" class="demo-form-inline">
              <el-form-item label="月份">
                <el-date-picker
                  v-model="monthlyDate"
                  type="month"
                  placeholder="选择月份"
                  value-format="yyyy-MM"
                  @change="handleMonthlyDateChange"
                ></el-date-picker>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="searchMonthly">查询</el-button>
                <el-button @click="resetMonthly">重置</el-button>
                <el-button type="success" @click="exportMonthly">导出</el-button>
              </el-form-item>
            </el-form>

            <el-table
              v-loading="monthlyLoading"
              border
              :data="companyList"
              style="width: 100%"
            >
              <el-table-column prop="date" label="月份" width="180" />
              <el-table-column prop="companyName" label="公司名称" />
              <el-table-column prop="bindCount" label="绑定台数" />
            </el-table>

            <div class="chart-container" style="margin-top: 20px; height: 400px">
              <div ref="monthlyChart" style="height: 100%; width: 100%"></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </template>

  <script>
  import { ipadStaticTotal,exportIpadStaticByTime} from "@/api/company/statistics";

  export default {
    name: 'ipadStatic',
    data() {
      const today = this.parseTime(new Date(), '{y}-{m}-{d}')
      const yesterday = this.parseTime(new Date(new Date().getTime() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
      return {
        // 激活的标签页
        activeTab: 'daily',
        // 按天统计数据
        dailyLoading: false,
        dailyDate: yesterday, // 默认当天
        // 按月统计数据
        monthlyLoading: false,
        monthlyDate: this.parseTime(new Date(), '{y}-{m}'), // 默认当月
        companyList: [],
      }
    },
    created() {
      // 获取当天数据
      this.getList()
    },
    methods: {
      // 标签页切换
      handleTabClick(tab) {
        if (tab.name === 'daily') {
          this.getList()
        } else if (tab.name === 'monthly') {
          this.getMonthlyList()
        }
      },

      // 按天统计相关方法
      handleDailyDateChange(val) {
        if (val) {
          this.dailyDate = val
        }
      },
      searchDaily() {
        this.getList()
      },
      resetDaily() {
        const today = this.parseTime(new Date(), '{y}-{m}-{d}')
        const yesterday = this.parseTime(new Date(new Date().getTime() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
        this.dailyDate = yesterday
        this.getList()
      },

      // 导出
      exportDaily() {
        this.$confirm("是否确认导出数据项?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(() => {
            this.exportLoading = true;
            return exportIpadStaticByTime(this.dailyDate);
            })
            .then((response) => {
            this.download(response.msg);
            this.exportLoading = false;
            })
            .catch(() => { });
      },
      getList() {
        this.dailyLoading = true
        ipadStaticTotal(this.dailyDate).then(response => {
          // 处理返回数据，添加日期字段用于表格和图表显示
          this.companyList = response.list;
          this.dailyLoading = false;
        }).catch(() => {
          this.dailyLoading = false;
        });
      },

      // 按月统计相关方法
      handleMonthlyDateChange(val) {
        if (val) {
          this.monthlyDate = val
        }
      },
      searchMonthly() {
        this.getMonthlyList()
      },
      resetMonthly() {
        this.monthlyDate = this.parseTime(new Date(), '{y}-{m}')
        this.getMonthlyList()
      },
      exportMonthly() {
        this.$confirm("是否确认导出数据项?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(() => {
            this.exportLoading = true;
            return exportIpadStaticByTime(this.monthlyDate);
            })
            .then((response) => {
            this.download(response.msg);
            this.exportLoading = false;
            })
            .catch(() => { });
      },
      getMonthlyList() {
        this.monthlyLoading = true
        ipadStaticTotal(this.monthlyDate).then(response => {
          // 处理返回数据，添加月份字段用于表格和图表显示
          this.companyList = response.list;
          this.monthlyLoading = false;
        }).catch(() => {
          this.monthlyLoading = false;
          this.monthlyTotal = 0;
        });
      },

      // 日期格式化
      parseTime(time, pattern) {
        let date;
        if (arguments.length === 0 || !time) {
          return null
        }
        const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'

        if (typeof time === 'object') {
          date = time
        } else {
          if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
          } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/')
          }
          if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
          }
          date = new Date(time)
        }
        const formatObj = {
          y: date.getFullYear(),
          m: date.getMonth() + 1,
          d: date.getDate(),
          h: date.getHours(),
          i: date.getMinutes(),
          s: date.getSeconds(),
          a: date.getDay()
        }
        const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
          let value = formatObj[key]
          // Note: getDay() returns 0 on Sunday
          if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
          if (result.length > 0 && value < 10) {
            value = '0' + value
          }
          return value || 0
        })
        return time_str
      }
    }
  }
  </script>

  <style scoped>
  .chart-container {
    position: relative;
    padding: 20px 0;
  }
  </style>
