<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j component-commodity-trend-analysis">
    <!-- 标题 -->
    <view class="title">
      {{ $t('shangPinQuShiFenXi') }}
    </view>

    <!-- 选择时间 -->
    <view class="select-hang">
      <view
        class="select-item"
        @tap="openSelectDate"
      >
        <view
          v-if="dateData.dateRange.length"
          class="left-time"
        >
          <text class="left">
            {{ dateData.dateRange[0].split(' ')[0] }}
          </text>
          <text v-if="dateData.dateRange.length>1">
            -
          </text>
          <text
            v-if="dateData.dateRange.length>1"
            class="right"
          >
            {{ dateData.dateRange[1].split(' ')[0] }}
          </text>
        </view>
        <view class="right-time">
          {{ dateData.label }} <uni-icons
            class="ml-auto"
            type="arrowright"
            color="#999999"
            size="24rpx"
          />
        </view>
      </view>
    </view>

    <!-- 重选指标 -->
    <view
      class="reelect"
      @tap="reChoice"
    >
      {{ $t('zhongXuanZhiBiao') }}
    </view>

    <view
      v-if="chartData.series&&chartData.series.length"
      class="charts-box"
    >
      <qiun-data-charts
        type="area"
        :chart-data="chartData"
        :opts="chartsOpts"
        background="none"
        :ontouch="true"
        :tap-legend="false"
        :animation="true"
      />
    </view>
    <view
      v-else-if="isLoaded"
      class="chartsNoData"
    >
      {{ $t('zanWuShuJu') }}
    </view>

    <!-- 选择时间组件 -->
    <view class="zujian">
      <select-date
        v-if="showSelectDate"
        :value="dateData"
        :nature-day-show="true"
        @submit-data="submitData"
        @cancal="cancal"
        @handle-select-date="handleSelectDate"
      />
    </view>

    <!-- 重选指标组件 -->
    <view
      v-if="showIndicator"
      class="indicator"
    >
      <view
        class="mask"
        @tap="cancalIndicator"
      />
      <view class="content-box">
        <view class="title">
          <text>{{ $t('xuanZeZhanShiZhiBiao') }}</text>
          <view
            class="close"
            @tap="cancalIndicator"
          />
        </view>
        <view
          v-for="(item, index) in tabData"
          :key="index"
          class="tab-box"
        >
          <view class="title">
            {{ item[0].title }}
          </view>
          <view class="data">
            <view
              v-for="(itemTab, indexTab) in item"
              :key="indexTab"
              :class="['tab',itemTab.checked?'tab-checked':'']"
            >
              <view
                class="tabItem"
                @tap="choiceIndicator(itemTab)"
              >
                {{ itemTab.name }}
              </view>
            </view>
          </view>
        </view>
        <view class="footer">
          <view
            class="btn"
            @tap="submitData"
          >
            {{ $t('queDing') }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import dayjs from 'dayjs'
import { reactive } from 'vue'
import customParseFormat from 'dayjs/plugin/customParseFormat'
dayjs.extend(customParseFormat)

const isLoaded = ref(false) // 列表是否加载完毕
const showSelectDate = ref(false) // 时间组件的显隐
const showIndicator = ref(false) // 重选指标组件显隐

//  回显
const dateData = reactive({
  value: 1,
  dateRange: ['', ''],
  label: $t('jin_7Tian')
})

// echart 表格数据
const chartData = ref({
  categories: [],
  series: []
})
// echart暂存数据
const newchartData = {
  categories: [],
  series: [
  ]
}

let oldTabData = [] // 存放初始tabData数据
const tabData = reactive(
  [
    [
      {
        title: $t('shangPinGaiKuang'),
        name: $t('xinZengShangPinShu'),
        checked: false,
        data: []

      },
      {
        title: $t('shangPinGaiKuang-0'),
        name: $t('beiFangWenShangPin'),
        checked: false,
        data: []

      },
      {
        title: $t('shangPinGaiKuang-1'),
        name: $t('dongXiaoShangPinShu'),
        checked: false,
        data: []

      }
    ], // 商品概况
    [
      {
        title: $t('shangPinLiuLiang'),
        name: $t('fenXiangFangWenShu'),
        checked: true,
        data: []

      },
      {
        title: $t('shangPinLiuLiang-0'),
        name: $t('shangPinLiuLanLiang'),
        checked: true,
        data: []

      },
      {
        title: $t('shangPinLiuLiang-1'),
        name: $t('shangPinFangWenKeShu'),
        checked: true,
        data: []
      }
    ], // 商品流量
    [
      {
        title: $t('shangPinZhuanHua'),
        name: $t('jiaGouJianShu'),
        checked: false,
        data: []
      },
      {
        title: $t('shangPinZhuanHua-0'),
        name: $t('xiaDanJianShu'),
        checked: false,
        data: []
      },
      {
        title: $t('shangPinZhuanHua-1'),
        name: $t('zhiFuJianShu'),
        checked: false,
        data: []
      }
    ] // 商品转化
  ]
) // tab切换栏展示的数据

const chartsOpts = { // ucharts 配置
  dataPointShapeType: 'hollow', // 图例是否空心   'solid'实心,'hollow'空心
  color: ['#0065F3', '#0BB903', '#FD4171'], // 图例颜色
  enableScroll: true, // 开启滚动条，X轴配置里需要配置itemCount单屏幕数据点数量
  dataLabel: false, // 是否显示图表区域内数据点上方的数据文案
  xAxis: {
    boundaryGap: 'center', // 折线图、区域图起画点结束点方法，可选值：'center'两端留空,'justify'两端对齐
    dashLength: 10, // 纵向网格为虚线时，单段虚线长度
    gridEval: 10, // 纵向网格线显示间隔
    itemCount: 7, // 可视区域内显示的X轴数据点数量
    axisLine: false,
    axisLineColor: '#000000'
  },
  yAxis: {
    data: [{
      axisLineColor: '#fff' //  坐标轴轴线颜色
    }]
  },
  extra: {
    area: {
      type: 'curve' // 曲线
    }
  },
  legend: {
    position: 'top', // 数据名称顶部显示
    lineHeight: 50, // lineHeight
    itemHeight: 10,
    itemWidth: 10,
    icon: 'circle'
  },
  padding: [0, 0, 0, 0] // 图标边距
}

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

const init = () => {
  initDateData()
  oldTabData = tabData && JSON.parse(JSON.stringify(tabData))
}

/**
 * 获取获取商品趋势分析
 */
const getProdTrendAnalysis = () => {
  if (dateData.value === 4) {
    dateData.dateRange[0] = dayjs(dateData.dateRange[0], 'YYYY-MM').startOf('day').format('YYYY.MM.DD')
    dateData.dateRange[1] = dayjs(dateData.dateRange[0], 'YYYY-MM').endOf('month').format('YYYY.MM.DD')
  }
  // 请求参数
  const data = {
    dateType: dateData.value + 1,
    startTime: '',
    endTime: ''
  }
  if (dateData.value === 1 || dateData.value === 2) {
    data.startTime = dayjs(dateData.dateRange[0], 'YYYY.MM.DD').startOf('day').format('YYYY-MM-DD HH:mm:ss')
    data.endTime = dayjs(dateData.dateRange[1], 'YYYY.MM.DD').endOf('day').format('YYYY-MM-DD HH:mm:ss')
  }
  if (dateData.value === 4) {
    data.startTime = dayjs(dateData.dateRange[0], 'YYYY-MM').startOf('month').format('YYYY-MM-DD HH:mm:ss')
    data.endTime = dayjs(dateData.dateRange[0], 'YYYY-MM').endOf('month').format('YYYY-MM-DD HH:mm:ss')
    const d1 = dayjs(dateData.dateRange[0], 'YYYY-MM').format('YYYY-MM')
    const d2 = dayjs().format('YYYY-MM')
    if (d1 === d2) {
      data.endTime = dayjs(new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)).subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss')
    }
  }
  isLoaded.value = false
  const params = {
    url: '/multishop/prodAnalysis/getProdTrendAnalysis',
    method: 'GET',
    data
  }
  http.request(params).then(({ data: res }) => {
    isLoaded.value = true
    tabData.forEach(item => {
      item.forEach(vale => {
        vale.data = []
      })
    })
    res.map(item => {
      tabData[0][0].data.push(item.newProd)
      tabData[0][1].data.push(item.visitedProd)
      tabData[0][2].data.push(item.dynamicSale)
      tabData[1][0].data.push(item.shareVisit)
      tabData[1][1].data.push(item.browse)
      tabData[1][2].data.push(item.visitor)
      tabData[2][0].data.push(item.addCart)
      tabData[2][1].data.push(item.orderNum)
      tabData[2][2].data.push(item.payNum)
      return item
    })
    submitData()
  })
}
/**
 * 初始化数据
 */
const initDateData = () => {
  const startDay = -7
  const endDay = -1
  const startTime = dayjs()
    .add(startDay, 'days')
    .startOf('days')
    .format('YYYY.MM.DD')
  // 结束时间
  const endTime = dayjs()
    .add(endDay, 'days')
    .endOf('days')
    .format('YYYY.MM.DD')
  dateData.dateRange = [startTime, endTime]
  handleSelectDate(dateData)
}

const addDate = (dd, dadd) => {
  let a = new Date(dd)
  a = a.valueOf()
  a = a + dadd * 24 * 60 * 60 * 1000
  a = new Date(a)
  return a
}

const getNearlyDataSum = (data) => {
  let now = new Date()
  let dataSum = []
  for (let i = 0; i < data; i++) {
    // var month = (now.getMonth() + 1)
    now = addDate(now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate(), -1)
    dataSum[i] = ((now.getMonth() + 1) + '-' + now.getDate())
  }
  dataSum = dataSum.reverse()
  newchartData.categories = JSON.parse(JSON.stringify(dataSum))
}

const getChartMonth = (year, month) => {
  const dataTimes = []
  const d = new Date(year, month, 0)
  let n = +d.getDate()

  const d1 = dayjs(dateData.dateRange[0], 'YYYY-MM').format('YYYY-MM')
  const d2 = dayjs().format('YYYY-MM')
  const n2 = Number(dayjs().format('DD')) - 1

  n = (d1 === d2) ? n2 : n
  for (let i = 1; i < n + 1; i++) {
    dataTimes.push(month + '-' + i)
  }
  newchartData.categories = JSON.parse(JSON.stringify(dataTimes))
}

// 选中的时间
const openSelectDate = () => {
  showSelectDate.value = true
}

// 商品趋势分析选择时间
const handleSelectDate = (data) => {
  dateData.dateRange = dateData.dateRange.map(element => {
    if (element.indexOf(' ') !== -1) {
      return element.substring(0, element.indexOf(' '))
    }
    return element
  })
  dateData.label = data.label
  dateData.value = data.value
  dateData.dateRange = data.dateRange
  // console.log(data, 'datadata', dateData.dateRange)
  // dateData.dateRange =
  showSelectDate.value = false

  // echart时间选择 1.近七天 2.近三十天 4.自然月
  switch (data.value) {
    case 1:
      getNearlyDataSum(7)
      break
    case 2:
      getNearlyDataSum(30)
      break
    default:
      {
        let year
        let month
        if (data.dateRange[0].indexOf('-') !== -1) {
          year = data.dateRange[0].split('-')[0]
          month = data.dateRange[0].split('-')[1]
        } else {
          year = data.dateRange[0].split('.')[0]
          month = data.dateRange[0].split('.')[1]
        }
        month = month.split('')
        if (month[0] === '0') {
          month = month[1]
        } else {
          month = month.join('')
        }
        getChartMonth(year, month)
      }
      break
  }
  getProdTrendAnalysis()
}
const cancal = () => {
  showSelectDate.value = false
}
// 选中的时间 end

// 重选指标
const choiceIndicator = (itemTab) => {
  let checkedNum = 0
  tabData.forEach(element => {
    element.forEach(item => {
      if (item.checked === true) checkedNum += 1
    })
  })
  if (checkedNum === 3 && !itemTab.checked) {
    uni.showToast({
      title: $t('zuiDuoXuanZe_3Xiang'),
      icon: 'none',
      duration: 2000
    })
  } else {
    itemTab.checked = !itemTab.checked
  }
}

const submitData = () => {
  showIndicator.value = false
  const series = []
  tabData.forEach(el => {
    el.forEach(it => {
      if (it.checked) {
        series.push({
          name: it.name,
          data: it.data,
          legendShape: 'circle'
        })
      }
    })
  })
  newchartData.series = JSON.parse(JSON.stringify(series))
  chartData.value = JSON.parse(JSON.stringify(newchartData))
  oldTabData = tabData && JSON.parse(JSON.stringify(tabData))
}

const cancalIndicator = () => {
  showIndicator.value = false
  Object.assign(tabData, oldTabData ? JSON.parse(JSON.stringify(oldTabData)) : {})
}
// 重选指标 end

// 请求商品整体概况
const reChoice = () => {
  showIndicator.value = true
}

</script>

<style lang="scss" scoped>
@use './commodity-trend-analysis.scss';
</style>
