<template>
  <div class="course-label-statistics-container">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-radio-group v-model="timeType" size="small" @change="handleTimeTypeChange">
          <el-radio-button label="year">按年份</el-radio-button>
          <el-radio-button label="month">按月份</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-show="timeType === 'year'"
          v-model="currentDate"
          type="year"
          format="yyyy"
          placeholder="选择年份"
          popper-append-to-body
          @change="getDataList"
          size="small"
        />
        <el-date-picker
          v-show="timeType === 'month'"
          v-model="currentDate"
          type="month"
          format="yyyy-MM"
          placeholder="选择月份"
          popper-append-to-body
          @change="getDataList"
          size="small"
        />
      </el-form-item>
      <el-form-item>
        <el-button 
          type="primary"
          size="small"
          @click="handleRefresh"
        >刷新</el-button>
      </el-form-item>
      <el-form-item>
        <el-button 
          type="success"
          size="small"
          @click="exportData"
        >下载报表</el-button>
      </el-form-item>
    </el-form>
    
    <div class="table-container" ref="tableContainer">
      <el-table
        ref="dataTable"
        :data="dataList"
        border
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        :max-height="tableHeight"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="courseLabel" label="分类" min-width="150" />
        <el-table-column
          prop="courseCount"
          label="总销售门数"
          sortable="custom"
          min-width="120"
        />
        <el-table-column
          prop="sales"
          label="总销量"
          sortable="custom"
          min-width="100"
        />
        <el-table-column 
          :label="timeType === 'year' ? '年销售额（微信+支付宝+银行+天医币）' : '月销售额（微信+支付宝+银行+天医币）'" 
          prop="salesFee"
          sortable="custom"
          min-width="280"
        >
          <template slot-scope="scope">
            {{ scope.row.salesFee }}
          </template>
        </el-table-column>
        <el-table-column 
          :label="timeType === 'year' ? '年销售额（微信+支付宝+银行）' : '月销售额（微信+支付宝+银行）'" 
          prop="cashFee"
          sortable="custom"
          min-width="250"
        >
          <template slot-scope="scope">
            {{ scope.row.cashFee }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import http from '@/utils/httpRequest'

export default {
  data() {
    return {
      timeType: 'year',
      currentDate: new Date(),
      dataForm: {
        sortKey: '',
        sortValue: ''
      },
      dataList: [],
      tableHeight: null
    }
  },
  activated() {
    const now = new Date()
    if (this.timeType === 'year') {
      this.currentDate = new Date(now.getFullYear(), 0, 1)
    } else {
      this.currentDate = now
    }
    this.getDataList()
    this.$nextTick(() => {
      this.calculateTableHeight()
    })
  },
  mounted() {
    window.addEventListener('resize', this.handleResize)
    this.$nextTick(() => {
      this.calculateTableHeight()
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      this.calculateTableHeight()
    },
    calculateTableHeight() {
      if (this.$refs.tableContainer) {
        this.tableHeight = this.$refs.tableContainer.offsetHeight || 500
      } else {
        this.tableHeight = 500
      }
    },
    handleTimeTypeChange() {
      if (this.timeType === 'year') {
        const now = new Date()
        this.currentDate = new Date(now.getFullYear(), 0, 1)
      } else {
        this.currentDate = new Date()
      }
      this.getDataList()
    },
    handleSortChange({ prop, order }) {
      this.dataForm.sortKey = prop
      this.dataForm.sortValue = order
      this.getDataList()
    },
    handleRefresh() {
      this.dataForm.sortKey = ''
      this.dataForm.sortValue = ''
      this.$nextTick(() => {
        this.$refs.dataTable.clearSort()
      })
      this.getDataList()
    },
    getDataList() {
      const dateStr = this.timeType === 'year' 
        ? this.currentDate.getFullYear().toString() 
        : `${this.currentDate.getFullYear()}-${String(this.currentDate.getMonth() + 1).padStart(2, '0')}`
      http({
        url: http.adornUrl('/master/statisticsBusiness/getCourseSaleInfoByCourseLabel'),
        method: 'post',
        data: http.adornData({
          date: dateStr,
          sortKey: this.dataForm.sortKey,
          sortValue: this.dataForm.sortValue
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.courseSaleInfo || []
        }
      })
    },
    exportData() {
      const dateStr = this.timeType === 'year' 
        ? this.currentDate.getFullYear().toString() 
        : `${this.currentDate.getFullYear()}-${String(this.currentDate.getMonth() + 1).padStart(2, '0')}`
      http({
        url: http.adornUrl('/master/statisticsBusiness/exportCourseSaleInfoByCourseLabel'),
        method: 'post',
        data: http.adornData({
          date: dateStr
        }),
        responseType: 'blob'
      }).then((response) => {
        const blob = new Blob([response.data])
        const fileName = `按分类统计报表_${dateStr}.xlsx`
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = fileName
        link.click()
        URL.revokeObjectURL(link.href)
      })
    }
  }
}
</script>

<style scoped lang="less">
@import '../styles/statistics-common.less';

.course-label-statistics-container {
  .sb-page-height-with-table();
}

.sb-form-item-ten();
</style>
