<template>
  <div class="chart_wrap">
    <el-form :model="queryParams"
      inline
      size="default">
      <el-form-item label="直播间">
        <el-select v-model="queryParams.brandList"
          @change="queryChangeFn"
          multiple
          clearable
          collapse-tags
          collapse-tags-tooltip>
          <el-option v-for="str in brandList"
            :label="str"
            :value="str">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期选择">
        <el-date-picker v-model="queryParams.date"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="queryChangeFn('date')">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="数据类型">
        <el-checkbox-group v-model="queryParams.typeList"
          @change="queryChangeFn">
          <el-checkbox label="销售额"></el-checkbox>
          <el-checkbox label="观看人次"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <div class="chart_wrap">
      <group-legend :legendData="chartData.legend"
        @click-item="legendChangeFn"></group-legend>
      <line-charts :chartData="chartData"></line-charts>
    </div>
    <levitated-sphere>
      <el-button type="danger"
        @click="reset">重置本页</el-button>
    </levitated-sphere>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import LineCharts from './LineAndBar.vue'
import { getCmmListAPI } from '@/api'
import { generatorDayList, parseTime, getBrandColor } from '@/utils'

const queryParams = reactive({ // 查询表单
  brandList: [],
  date: [new Date().setDate((new Date().getDate() - 30)), new Date().setDate((new Date().getDate() - 1))],
  typeList: ['销售额', '观看人次']
})
const pickerOptions = reactive({// 日期选项配置
  shortcuts: [{
    text: '最近一周',
    onClick(picker) {
      const end = new Date().setDate((new Date().getDate() - 1));
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      picker.$emit('pick', [start, end]);
    }
  }, {
    text: '最近一个月',
    onClick(picker) {
      const end = new Date().setDate((new Date().getDate() - 1));
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      picker.$emit('pick', [start, end]);
    }
  }]
})
const brandList = ref([])// 直播间列表
const allChartData = reactive({ // 图表所有数据
  series: [],
  xAxis: [],
  legend: []
})
const chartData = reactive({ // 图表内要用的数据
  series: [],
  xAxis: [],
  legend: []
})

// 获取数据
const getList = async () => {
  allChartData.series = []
  allChartData.legend = []
  const { data } = await getCmmListAPI({
    startDate: parseTime(queryParams.date[0], '{y}-{m}-{d}'),
    endDate: parseTime(queryParams.date[1], '{y}-{m}-{d}')
  })
  data.map((list, index) => {
    // list：每个直播间
    let color = getBrandColor(list[0]?.name)
    const saleObj = {
      name: list[0]?.name + '-销售额',
      type: 'bar',
      data: [],
      itemStyle: {
        color
      }
    }
    const gkrcObj = {
      name: list[0]?.name + '-观看人次',
      type: 'line',
      data: [],
      showSymbol: false,
      lineStyle: {
        width: 2, // 设置折线的宽度
        type: 'solid', // 设置折线的类型
        color
      },
      yAxisIndex: 1,
    }
    // 按照日期添加数据
    allChartData.xAxis.forEach(date => {
      const findObj = list.find(o => o.date.includes(date))
      if (findObj) {
        saleObj.data.push(findObj.saleSumTotal)
        gkrcObj.data.push(findObj.gkrcNumTotal)
      } else {
        saleObj.data.push(0)
        gkrcObj.data.push(0)
      }
    })
    // legendData 名字
    allChartData.legend.push({
      data: [{
        name: saleObj.name,
        type: 'bar',
        color: color,
        effective: true,
        show: true
      }, {
        name: gkrcObj.name,
        type: 'line',
        color: color,
        effective: true,
        show: true
      }],
      orient: 'verticalAlign'
    })
    // allChartData.legend.push(saleObj.name)
    // allChartData.legend.push(gkrcObj.name)
    allChartData.series.push(saleObj)
    allChartData.series.push(gkrcObj)
  })
  return data
}

// 筛选数据
const filterData = () => {
  let series = allChartData.series
  let legend = allChartData.legend
  // 直播间筛选
  if (queryParams.brandList.length > 0) {
    series = series.filter(obj => {
      return queryParams.brandList.find(nameStr => obj.name.split('-')[0] === nameStr)
    })
    legend = legend.filter(obj => {
      return queryParams.brandList.find(nameStr => obj.data.find(o => o.name.split('-')[0] === nameStr))
    })
  }
  // 查看数据类型必须走
  series = series.filter(obj => {
    return queryParams.typeList.find(str => obj.name.split('-')[1] === str)
  })
  legend = legend.filter(obj => {
    // TODO：会不会有丢失响应式的
    const list = [...obj.data]
    list.forEach((o, index) => {
      const isHave = queryParams.typeList.includes(o.name.split('-')[1])
      if (!isHave) o.show = false
      else o.show = true
    })
    obj.data = list
    return true
  })
  // 根据图例状态筛选数据是否显示
  series = series.filter(sObj => {
    let nowSeries = true
    chartData.legend.forEach(obj => {
      const now = obj.data.find(o => {
        return o.name === sObj.name
      })
      // now 图例对象无效，则当前 sObj 对象无效
      if (now?.effective === false) {
        nowSeries = false
      }
    })
    return nowSeries
  })
  // 最后赋予给要展示的部分
  chartData.legend = legend
  chartData.series = series
  chartData.xAxis = allChartData.xAxis
}

// 默认打开页面请求一次所有数据，并保存在数据源
(async function init() {
  // 生成 x 轴时间
  allChartData.xAxis = generatorDayList(queryParams.date[0], queryParams.date[1])
  // 请求数据
  const data = await getList()
  // 初始化直播间列表
  brandList.value = data.map(list => list[0].name)
  // 筛选图表数据
  filterData()
})();


// 筛选条件改变了
const queryChangeFn = async (arg) => {
  if (arg === 'date' && !queryParams.date) return
  if (arg === 'date' && queryParams.date) {
    // 时间变化，并且有值，需要重新请求
    allChartData.xAxis = generatorDayList(queryParams.date[0], queryParams.date[1])
    await getList()
  }
  filterData()
}

// 图例点击改变了
const legendChangeFn = (o) => {
  filterData()
}
// 重置
const reset = async () => {
  // 重置查询参数
  queryParams.brandList = []
  queryParams.date = [new Date().setDate((new Date().getDate() - 30)), new Date().setDate((new Date().getDate() - 1))]
  queryParams.typeList = ['销售额', '观看人次']
  allChartData.xAxis = generatorDayList(queryParams.date[0], queryParams.date[1])
  // 重新获取
  await getList()
  // 筛选图表数据
  filterData()
}
</script>

<style scoped
  lang="scss"></style>