<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
          :clearable="false"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="pickerOptions"
          @change="queryChangeFn('date')">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <div class="chart_wrap"
      v-loading="loading">
      <template v-if="queryParams.brandList.length > 0 && queryParams.typeList.length > 0">
        <template v-if="showType === 'charts'">
          <group-legend :legendData="chartData.legend"
            @click-item="legendChangeFn"></group-legend>
          <gradient-area :chartData="chartData"></gradient-area>
        </template>
        <template v-else-if="showType === 'table'">
          <table-list :column="queryParams" :data="useTableList"></table-list>
        </template>
      </template>
      <no-data v-else></no-data>
    </div>
    <levitated-sphere>
      <el-button type="danger"
        @click="reset">重置本页</el-button>
    </levitated-sphere>
  </div>
</template>

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

// 静态数据
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 loading = ref(true)
// const showType = ref('charts') // 展示类型（'charts' / 'table')
const showType = ref('table') // 展示类型（'charts' / 'table')

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

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

const allTableList = ref([])
const useTableList = ref([])

// 获取数据
const getList = async () => {
  loading.value = true
  resetObjValue(allChartData)
  // 获取 x 轴时间
  allChartData.xAxis = generatorDayList(queryParams.date[0], queryParams.date[1])
  const { data } = await getSycmStoreListAPI({
    startDate: parseTime(queryParams.date[0], '{y}-{m}-{d}'),
    endDate: parseTime(queryParams.date[1], '{y}-{m}-{d}'),
    platformStore: '沃隆旗舰店,三只松鼠旗舰店'
  })
  // 表格数据
  allTableList.value = data.flat()
  // 图表数据
  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)
  })
  loading.value = false
  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))
    })
    // 表格数据筛选
    useTableList.value = allTableList.value.filter(item => {
      return queryParams.brandList.find(o => o === item.platformStore)
    })
  } else {
    // 店铺都没选
    legend.forEach(obj => {
      obj.data.forEach(o => {
        o.show = true
      })
    })
  }

  // 选择了数据类型，筛选
  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()
};

onMounted(() => {
  init()
})


const legendChangeFn = () => {
  filterData()
}

// 查询条件改变
const queryChangeFn = async (arg) => {
  await getList()
  // 数据筛选
  filterData()
}

// 重置
const reset = async () => {
  // 重置查询参数
  queryParams.brandList = []
  queryParams.date = dateList
  queryParams.typeList = [dataTypeList[0]]
  init()
}

</script>

<style scoped></style>