<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="echartBox" id="myEchart"></div>
    </el-card>
  </div>
</template>

<script>
import { getLossStatistics } from "@/api/dataCenter.js"
import { getGoodsFilter } from "@/api/goods.js"
import dayjs from 'dayjs'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      loading: false,
      time_type: 'thirty',
      timeTypeList: [
        { label: '自然周', value: 'week' },
        { label: '自然月', value: 'month' },
        { label: '近7天', value: 'seven' },
        { label: '近30天', value: 'thirty' },
        { label: '自定义', value: 'custom' }
      ],
      dayValue: '',
      monthValue: '',
      customValue: [],
      startTime: '',
      endTime: '',
      dateList: [],
      totalNum: [],
      totalAmount: [],
      myChart: null,
      dayTimeList: [],
      sku_id: '',
      skusList: [],
      remoteLoading: false
    }
  },
  mounted() {
    this.getInitList()
    window.onresize = () => {
      if(this.myChart) {
        this.myChart.resize()
      }
    }
  },
  methods: {
    getInitList() {
      this.dayValue = this.endTime = dayjs().format('YYYY-MM-DD')
      this.startTime = dayjs().subtract(30, 'day').format('YYYY-MM-DD')
      this.fetchData()
    },
    changeTimeType() {
      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 = {
        start_time: this.startTime + ' 00:00:00',
        end_time: this.endTime + ' 23:59:59',
        sku_id: this.sku_id || 0
      }
      getLossStatistics(params).then((res) => {
        this.dateList = []
        this.totalNum = []
        this.totalAmount = []
        res.data.data.forEach((it) => {
          this.dateList.push(it.date)
          this.totalNum.push(it.total_num)
          this.totalAmount.push(it.total_loss_amount)
        })
        this.renderChart()
      }).catch(() => {
        this.loading = false
      })
    },
    renderChart() {
      this.myChart = echarts.init(document.getElementById('myEchart'))
      this.myChart.setOption({
        grid: {
          left: '1%',
          bottom: '2%',
          containLabel: true
        },
        color: ['#3cd08f', '#f89f34'],
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          icon: 'rect',
          left: 30,
          data: ['报损数', '报损金额']
        },
        xAxis: {
          type: 'category',
          data: this.dateList
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '报损数',
            type: 'line',
            smooth: true,
            data: this.totalNum,
          },
          {
            name: '报损金额',
            type: 'line',
            smooth: true,
            data: this.totalAmount
          }
        ]
      })
      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') {
        this.startTime = this.endTime = this.dayValue
      } 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()
    },
    remoteMethod(query) {
      if(query) {
        this.remoteLoading = true
        getGoodsFilter(query).then((res) => {
          this.skusList = res.data.data
          this.remoteLoading = false
        })
      } else {
        this.skusList = []
      }
    }
  },
  beforeDestroy() {
    if (!this.myChart) {
      return
    }
    this.myChart.dispose()
    this.myChart = null
  }
}
</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;
    }
  }
  .echartBox{
    width: 100%;
    height: 480px;
  }
</style>
