<template>
  <div>
    <div class="cardBox">
      <div class="searchBox">
        <div class="row" style="width: 100%;">
          <span>统计时间：</span>
          <el-select v-model="time_type" style="width: 100px;margin-right: 5px;" @change="changeTimeType">
            <el-option v-for="item in timeTypeList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-date-picker
            v-if="time_type == 'week' || time_type == 'seven' || time_type == 'thirty'"
            v-model="dayValue"
            :clearable="false"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @change="changeDayTime">
          </el-date-picker>

          <el-date-picker
            v-else-if="time_type == 'month'"
            v-model="monthValue"
            type="month"
            :clearable="false"
            format="yyyy-MM"
            value-format="yyyy-MM"
            placeholder="选择月"
            @change="changeMonthTime">
          </el-date-picker>

          <el-date-picker
            v-else-if="time_type == 'custom'"
            v-model="customValue"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :clearable="false"
            style="width: 250px;"
            @change="changeCustomTime">
          </el-date-picker>

          <el-time-picker
            v-else-if="time_type == 'day'"
            is-range
            value-format="HH:mm:ss"
            style="width: 200px;"
            format="HH:mm:ss"
            v-model="dayTimeList"
            range-separator="至"
            :clearable="false"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            @change="changeTimePicker">
          </el-time-picker>
          
          <div class="time">
            <span>当前统计时间：</span>
            <span v-if="startTime == endTime">{{ startTime }}</span>
            <span v-else>{{ startTime }}~{{ endTime }}</span>
          </div>
        </div>
        <div class="row">
          <span>规格：</span>
          <el-select v-model="sku_id" filterable remote clearable reserve-keyword placeholder="请选择具体规格" :remote-method="remoteMethod"
            :loading="remoteLoading">
            <el-option v-for="it in skusList" :key="it.id" :label="it.title" :value="it.id"></el-option>
          </el-select>
        </div>
        <div class="row">
          <el-button type="primary" @click="handleSearch()" icon="el-icon-search">筛选</el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="opaBox">
        <el-button type="success" icon="el-icon-download" @click="handleExport" :loading="downloadLoading">导出</el-button>
      </div>
      <el-table v-loading="loading" border :data="saleList">
        <el-table-column label="类型名称" prop="type_name"></el-table-column>
        <el-table-column label="库存" prop="stock"></el-table-column>
        <el-table-column label="可售库存" prop="sale_stock"></el-table-column>

        <el-table-column label="已发货数" prop="shipping_num" v-if="time_type == 'day'"></el-table-column>
        <el-table-column label="未发货数" prop="unshipping_num" v-if="time_type == 'day'"></el-table-column>
        
        <el-table-column label="总销量" prop="goods_total"></el-table-column>
        <el-table-column label="总销售金额" prop="goods_total_amount"></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getSpuSalesCount } from "@/api/dataCenter.js"
import { getGoodsFilter } from "@/api/goods.js"
import dayjs from 'dayjs'

export default {
  data() {
    return {
      loading: false,
      time_type: 'day',
      timeTypeList: [
        { label: '今日', value: 'day' },
        { label: '自然周', value: 'week' },
        { label: '自然月', value: 'month' },
        { label: '近7天', value: 'seven' },
        { label: '近30天', value: 'thirty' },
        { label: '自定义', value: 'custom' }
      ],
      TIMETYPE: {
        'day': '今日',
        'week': '自然周',
        'month': '自然月',
        'seven': '近7天',
        'thirty': '近30天',
        'custom': '自定义'
      },
      dayValue: '',
      monthValue: '',
      customValue: [],
      startTime: '',
      endTime: '',
      saleList: [],
      downloadLoading: false,
      autoWidth: true,
      bookType: 'xlsx',
      dayTimeList: [],
      sku_id: '',
      skusList: [],
      remoteLoading: false
    }
  },
  mounted() {
    this.getInitList()
  },
  methods: {
    getInitList() {
      let time = this.getDayTime()
      this.startTime = time + ' 00:00:00'
      this.endTime = time + ' 23:59:59'
      this.dayTimeList = ['00:00:00', '23:59:59']
      this.fetchData()
    },
    changeTimeType() {
      if(this.time_type == 'day') {
        let time = this.getDayTime()
        this.startTime = time + ' 00:00:00'
        this.endTime = time + ' 23:59:59'
        this.dayTimeList = ['00:00:00', '23:59:59']
      } else if(this.time_type == 'week') {
        this.dayValue = this.endTime = dayjs().format('YYYY-MM-DD')
        this.startTime = dayjs(this.getFirstDay(this.dayValue)).format('YYYY-MM-DD')
      } else if(this.time_type == 'month') {
        this.monthValue = dayjs().format('YYYY-MM')
        this.startTime = this.monthValue + '-01'
        this.endTime = this.monthValue + '-' + this.getDaysInMonth(this.monthValue)
      } else if(this.time_type == 'seven') {
        this.dayValue = this.endTime = dayjs().format('YYYY-MM-DD')
        this.startTime = dayjs().subtract(7, 'day').format('YYYY-MM-DD')
      } else if(this.time_type == 'thirty') {
        this.dayValue = this.endTime = dayjs().format('YYYY-MM-DD')
        this.startTime = dayjs().subtract(30, 'day').format('YYYY-MM-DD')
      } else if(this.time_type == 'custom') {
        this.startTime = this.endTime = dayjs().format('YYYY-MM-DD')
        this.customValue = [this.startTime, this.startTime]
      }
      this.fetchData()
    },
    fetchData() {
      this.loading = true
      let params = {
        type: this.time_type == 'day' ? 1 : 2,
        sku_id: this.sku_id
      }
      if(params.type == 1) {
        params.start_time = this.startTime
        params.end_time = this.endTime
      } else {
        params.start_day = this.startTime
        params.end_day =  this.endTime
      }
      getSpuSalesCount(params).then((res) => {
        this.saleList = res.data.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取当前日期
    getDayTime() {
      let time = dayjs().format('YYYY-MM-DD')
      return time
    },
    // 获取所在周的周一
    getFirstDay(date) {
      let day = new Date(date).getDay() || 7
      return new Date(new Date(date).getFullYear(), new Date(date).getMonth(), new Date(date).getDate() + 1 - day)
    },
    getDaysInMonth(date) {
      let year = date.split('-')[0] * 1
      let month = date.split('-')[1] * 1
      const startOfMonth = dayjs(new Date(year, month - 1, 1))
      const endOfMonth = startOfMonth.endOf('month')
      return endOfMonth.date()
    },
    changeDayTime() {
      if(this.time_type == 'day') {
        let time = this.getDayTime()
        this.startTime = time + ' 00:00:00'
        this.endTime = time + ' 23:59:59'
        this.dayTimeList = ['00:00:00', '23:59:59']
      } else if(this.time_type == 'week') {
        this.endTime = this.dayValue
        this.startTime = dayjs(this.getFirstDay(this.dayValue)).format('YYYY-MM-DD')
      } else if(this.time_type == 'seven') {
        this.endTime = this.dayValue
        this.startTime = dayjs(this.dayValue).subtract(7, 'day').format('YYYY-MM-DD')
      } else if(this.time_type == 'thirty') {
        this.endTime = this.dayValue
        this.startTime = dayjs(this.dayValue).subtract(30, 'day').format('YYYY-MM-DD')
      }
      this.fetchData()
    },
    changeMonthTime() {
      this.startTime = this.monthValue + '-01'
      this.endTime = this.monthValue + '-' + this.getDaysInMonth(this.monthValue)
      this.fetchData()
    },
    changeCustomTime() {
      this.startTime = this.customValue[0]
      this.endTime = this.customValue[1]
      this.fetchData()
    },
    changeTimePicker() {
      let time = this.getDayTime()
      this.startTime = time + ' ' + this.dayTimeList[0]
      this.endTime = time + ' ' + this.dayTimeList[1]
      this.fetchData()
    },
    handleSearch() {
      this.fetchData()
    },
    handleExport() {
      if(!this.saleList.length) {
        this.$message({
          message: '暂无数据',
          type: 'error'
        })
        return
      }
      this.downloadLoading = true
      import('@/util/Export2Excel').then(excel => {
        const tHeader = ['类型名称', '库存', '可售库存', '总销量', '总销售金额']
        const filterVal = ['type_name', 'stock', 'sale_stock', 'goods_total', 'goods_total_amount']
        
        if(this.time_type == 'day') {
          tHeader.splice(3, 0, '已发货数', '未发货数')
          filterVal.splice(3, 0, 'shipping_num', 'unshipping_num')
        }
        const list = this.saleList
        let date = this.startTime == this.endTime ? this.startTime : this.startTime + '-' + this.endTime
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'sku销售统计数据【' + this.TIMETYPE[this.time_type] + date + '】',
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      }).catch(() => {
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    remoteMethod(query) {
      if(query) {
        this.remoteLoading = true
        getGoodsFilter(query).then((res) => {
          this.skusList = res.data.data
          this.remoteLoading = false
        })
      } else {
        this.skusList = []
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .searchBox{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    white-space: nowrap;
    .row{
      font-size: 14px;
      margin-bottom: 20px;
      margin-right: 15px;
      display: flex;
      align-items: center;
    }
    .time{
      margin-left: 20px;
      color: #999;
      font-size: 12px;
    }
  }
  .opaBox{
    margin-bottom: 15px;
  }
</style>
  