<template>
  <div>
    <el-form :model="queryParams"
      inline>
      <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-select v-model="queryParams.typeList"
          @change="queryChangeFn"
          multiple
          clearable
          collapse-tags>
          <el-option v-for="str in typeList"
            :label="str"
            :value="str">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期选择">
        <el-date-picker v-model="queryParams.date"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="pickerOptions"
          @change="queryChangeFn('date')">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <div class="chart_wrap">
      <group-legend :legendData="chartData.legend"
        @click-item="legendChangeFn"></group-legend>
      <gradient-area :chartData="chartData"></gradient-area>
    </div>
  </div>
</template>

<script setup>
import GradientArea from './GradientArea.vue';
import { getSycmListAPI } from '@/api'
import { generatorDayList, parseTime, getBrandColor, resetObjValue } from '@/utils'
import { useDatePickerOptions } from '@/hooks/date'

// 静态数据
const dateList = [new Date().setDate((new Date().getDate() - 30)), new Date().setDate((new Date().getDate() - 1))] // 最近 30 日日期数组
const dataTypeList = ['支付买家数', '交易增速', '独立访客范围', '流量增速'] // 数据类型

// 本页数据
const typeList = ref(dataTypeList)
const { pickerOptions } = useDatePickerOptions()
const brandList = ref([]) // 店铺列表

const queryParams = reactive({ // 查询表单
  brandList: [],
  typeList: [typeList.value[0]],
  date: dateList,
})

const allChartData = reactive({ // 图表所有数据
  xAxis: [],
  legend: [],
  series: []
})
const chartData = reactive({ // 图表内要用的数据
  xAxis: [],
  legend: [],
  series: [],
})

// 获取数据
const getList = async () => {
  resetObjValue(allChartData)
  // 获取 x 轴时间
  allChartData.xAxis = generatorDayList(queryParams.date[0], queryParams.date[1])
  const { data } = await getSycmListAPI({
    startDate: parseTime(queryParams.date[0], '{y}-{m}-{d}'),
    endDate: parseTime(queryParams.date[1], '{y}-{m}-{d}'),
  })
  // 保存到数据源
  data.forEach(list => {
    // list: 每个店铺数据集合
    // 公共的配置
    let commonObj = {
      type: 'line',
      // stack: 'Total',
      smooth: true,
      // stackStrategy: 'all',
      lineStyle: {
        width: 0
      },
      showSymbol: false,
      emphasis: {
        focus: 'series'
      }
    }
    let jyzsObj = {
      ...commonObj,
      itemStyle: {
        color: getBrandColor(list[0]?.platformStore, 0)
      },
      areaStyle: {
        opacity: 0.8,
        color: getBrandColor(list[0]?.platformStore, 0)
      },
      name: list[0]?.platformStore + '-交易增速',
      data: []
    }
    let llzsObj = {
      ...commonObj,
      itemStyle: {
        color: getBrandColor(list[0]?.platformStore, 1)
      },
      areaStyle: {
        opacity: 0.8,
        color: getBrandColor(list[0]?.platformStore, 1)
      },
      name: list[0]?.platformStore + '-流量增速',
      data: [],
    }
    let uvObj = {
      ...commonObj,
      itemStyle: {
        color: getBrandColor(list[0]?.platformStore, 2)
      },
      areaStyle: {
        opacity: 0.8,
        color: getBrandColor(list[0]?.platformStore, 2)
      },
      name: list[0]?.platformStore + '-独立访客范围',
      data: []
    }
    let zfmjObj = {
      ...commonObj,
      itemStyle: {
        color: getBrandColor(list[0]?.platformStore, 3)
      },
      areaStyle: {
        opacity: 0.8,
        color: getBrandColor(list[0]?.platformStore, 3)
      },
      name: list[0]?.platformStore + '-支付买家数',
      data: []
    }
    // list: 循环每一天的数据
    // 按照日期添加数据
    allChartData.xAxis.forEach(date => {
      const findObj = list.find(o => o.date.includes(date))
      if (findObj) {
        jyzsObj.data.push((findObj.jyzsPeakTotal + findObj.jyzsUnderTotal) / 2)
        llzsObj.data.push((findObj.llzsPeakTotal + findObj.llzsUnderTotal) / 2)
        uvObj.data.push((findObj.uvPeakTotal + findObj.uvUnderTotal) / 2)
        zfmjObj.data.push((findObj.zfmjPeakTotal + findObj.zfmjUnderTotal) / 2)
      } else {
        jyzsObj.data.push(0)
        llzsObj.data.push(0)
        uvObj.data.push(0)
        zfmjObj.data.push(0)
      }
    })

    allChartData.legend.push({
      data: [{
        name: jyzsObj.name,
        type: 'circle',
        color: getBrandColor(list[0]?.platformStore, 0),
        effective: true,
        show: true,
      }, {
        name: llzsObj.name,
        type: 'circle',
        color: getBrandColor(list[0]?.platformStore, 1),
        effective: true,
        show: true
      }, {
        name: uvObj.name,
        type: 'circle',
        color: getBrandColor(list[0]?.platformStore, 2),
        effective: true,
        show: true
      }, {
        name: zfmjObj.name,
        type: 'circle',
        color: getBrandColor(list[0]?.platformStore, 3),
        effective: true,
        show: true
      }],
      orient: 'verticalAlign'
    })

    // allChartData.legend.push(zfmjObj.name, uvObj.name, llzsObj.name, jyzsObj.name)
    allChartData.series.push(jyzsObj, llzsObj, uvObj, zfmjObj)
  })
  return data
}

// 筛选数据
const filterData = () => {
  let legend = allChartData.legend
  let series = allChartData.series

  if (queryParams.brandList.length > 0) {
    // 选择了店铺，筛选
    series = series.filter(item => {
      return queryParams.brandList.find(o => o === item.name.split('-')[0])
    })
    legend = legend.filter(obj => {
      return queryParams.brandList.find(nameStr => obj.data.find(o => o.name.split('-')[0] === nameStr))
    })
  }

  // 选择了数据类型，筛选
  if (queryParams.typeList.length > 0) {
    series = series.filter(item => {
      return queryParams.typeList.find(o => o === item.name.split('-')[1])
    })
    // 图例组件数据源不变，只是显示/隐藏
    legend.filter(obj => {
      obj.data.forEach((o, index) => {
        const isHave = queryParams.typeList.includes(o.name.split('-')[1])
        // 设置图例组件显示/隐藏
        if (!isHave) o.show = false
        else o.show = true
      })
    })
  } else {
    // 数据类型都没选
    legend.forEach(obj => {
      obj.data.forEach(o => {
        o.show = true
      })
    })
  }
  // 据图例状态，筛选数据显示
  series = series.filter(sObj => {
    let nowSeries = true
    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() {
  const data = await getList()
  // 直播间列表
  brandList.value = data.map(list => list[0].platformStore)
  // 初始化筛选条件（默认请求第一个店铺的第一类型数据）
  queryParams.brandList = [data[0][0].platformStore]
  // 筛选图表数据
  filterData()
};
init()

const legendChangeFn = () => {
  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()
}

</script>

<style scoped></style>