<template>
  <div>
    <el-row type="flex">
      <el-tabs v-model="queryParams.groupBy" style="width: 100%">
        <el-tab-pane label="月报表" name="create_month">
          <range-picker v-model="queryParams.year" @change="onChangeYear" suffix="年"/>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <single-line-chart v-loading="loading" :labels="labels" :chart-data="chartData" name="收入" />
  </div>
</template>

<script>
import SingleLineChart from "@/components/SingleLineChart/index.vue";
import RangePicker from "@/components/RangePicker/index.vue";
import {countBill, listBill} from "@/api/system/recharge";

export default {
  name: 'storeRechargeReport',
  components: {RangePicker, SingleLineChart},
  props: {
    // 店铺id
    storeId: {
      type: String,
      default: null,
    }
  },
  data() {
    return {
      labels: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'], // x轴
      chartData: [],  // 报表数据
      queryParams: {
        type: 1,
        year: new Date().getFullYear(),
        status: "2",
        groupBy: "create_month",
        storeId: this.storeId,
      },
      loading: false,
    }
  },
  watch: {
    storeId(nv, ov) {
      this.getReportData(nv);
    }
  },
  methods: {
    // 当年份发生变化
    onChangeYear(year) {
      console.log(year);
      this.queryParams.year = year;
      this.getReportData(this.storeId);
    },
    // 获取到账人的报表
    getReportData(storeId) {
      this.loading = true;
      this.queryParams.storeId = storeId | this.storeId;
      countBill(this.queryParams).then(response => {
        let data = response.data;
        // 按月统计数据
        let list = [];
        if (data != null) {
          for (let i = 1; i <= this.getReportMonth(); i ++) {
            let monthData = data.find(item => item.createMonth === i);
            list[i - 1] = monthData == null ? 0 : monthData.recharge;
          }
        }
        this.chartData = list;
      }).finally(() => {
        this.loading = false;
      })
    },
    // 获取报表显示的月份
    getReportMonth() {
      let now = new Date();
      let nowYear = new Date().getFullYear()
      let paramYear = this.queryParams.year;
      if (paramYear < nowYear) {
        return 12;
      }
      if (paramYear === nowYear) {
        return now.getMonth() + 1;
      }
      return 0;
    },
    // 获取字符串时间的月份
    getMonth(str) {
      if (str == null) {
        return null;
      }
      return new Date(str).getMonth() + 1;
    }

  }
}
</script>

<style scoped>
.title {
  line-height: 36px;
}
</style>
