<script setup>
import dayjs from 'dayjs'
import { getElevatorDetailStatisticsApi } from '@/api/elevator'
import uCharts from '@/uni_modules/qiun-data-charts/js_sdk/u-charts/config-ucharts.js'

const list = ref(['日', '周', '月'])
const date = ref(dayjs().format('YYYY-MM-DD'))
const currSub = ref(0)
const currDate = ref([dayjs().format('YYYY-MM-DD')])
const subsectionChange = (index) => {
  console.log(index)
  currSub.value = index
  changeChartDate()
}

const changeChartDate = () => {
  switch (currSub.value) {
    case 0:
      changeChartDay()
      break
    case 1:
      changeChartWeek()
      break
    case 2:
      changeChartMonth()
      break
  }
}
const changeChartDay = async () => {
  date.value = dayjs().format('YYYY-MM-DD')
  currDate.value = [dayjs().format('YYYY-MM-DD')]
  opts.value.xAxis.formatter = (val) => {
    if (val % 3 === 0) {
      return `${val}点`
    } else {
      return ''
    }
  }
  await getAllStatistics()
  // const { timeLineList } = allData.value
  // runningData.value.categories = splitCurrentHour(timeLineList)
}
const changeChartWeek = () => {
  // 生成当前周的开始和结束日期
  const weekStart = dayjs().startOf('week').format('YYYY-MM-DD')
  const weekEnd = dayjs().endOf('week').format('YYYY-MM-DD')
  date.value = `${weekStart} / ${weekEnd}`
  currDate.value = [weekStart, weekEnd]

  opts.value.xAxis.formatter = (val) => {
    return `星期${val}`
  }
  runningData.value.categories = [1, 2, 3, 4, 5, 6, 7]
  getAllStatistics()
}
const changeChartMonth = () => {
  // 生成当前月的开始和结束日期
  const monthStart = dayjs().startOf('month').format('YYYY-MM-DD')
  const monthEnd = dayjs().endOf('month').format('YYYY-MM-DD')
  date.value = `${monthStart} / ${monthEnd}`
  currDate.value = [monthStart, monthEnd]

  opts.value.xAxis.formatter = (val) => {
    if (val % 4 === 1) {
      return `${val}号`
    } else {
      return ''
    }
  }
  // 根据今天多少号 生成 1～x 号数组
  const today = dayjs().date()
  const categories = []
  for (let i = 1; i <= today; i++) {
    categories.push(i)
  }
  runningData.value.categories = categories
  getAllStatistics()
}
const changeDate = (flag) => {
  const [start, end] = currDate.value
  if (flag) {
    switch (currSub.value) {
      case 0: {
        // 上一天 start的前一天
        const d = dayjs(start).subtract(1, 'day').format('YYYY-MM-DD')
        date.value = d
        currDate.value = [d]
        break
      }
      case 1: {
        // start的7天前 end的7天前
        const s = dayjs(start).subtract(7, 'day').format('YYYY-MM-DD')
        const e = dayjs(end).subtract(7, 'day').format('YYYY-MM-DD')
        date.value = `${s} / ${e}`
        currDate.value = [s, e]
        break
      }
      case 2: {
        // start的上个月 end的上个月
        const sm = dayjs(start).subtract(1, 'month').format('YYYY-MM-DD')
        const em = dayjs(end).subtract(1, 'month').format('YYYY-MM-DD')
        date.value = `${sm} / ${em}`
        currDate.value = [sm, em]
        break
      }
    }
  } else {
    switch (currSub.value) {
      case 0: {
        // 下一天 start的后一天
        const d = dayjs(start).add(1, 'day').format('YYYY-MM-DD')
        date.value = d
        currDate.value = [d]
        break
      }
      case 1: {
        // start的7天后 end的7天后
        const s = dayjs(start).add(7, 'day').format('YYYY-MM-DD')
        const e = dayjs(end).add(7, 'day').format('YYYY-MM-DD')
        date.value = `${s} / ${e}`
        currDate.value = [s, e]
        break
      }
      case 2: {
        // start 所在时间的下一个月 开始日期和结束日期
        // 先获取start 的月份 然后+1 得到下个月的月份的日期
        const d = dayjs(start).add(1, 'month').format('YYYY-MM-DD')
        const sm = dayjs(d).startOf('month').format('YYYY-MM-DD')
        const em = dayjs(d).endOf('month').format('YYYY-MM-DD')
        date.value = `${sm} / ${em}`
        currDate.value = [sm, em]
        break
      }
    }
  }

  getAllStatistics()
}

const allData = ref({})
const baseData = ref([
  { label: '繁忙时间段(个)', value: 10 },
  { label: '适中时间段(个)', value: 20 },
  { label: '较闲时间段(个)', value: 30 }
])

const opts = ref({
  extra: {
    tooltip: {
      borderRadius: 5
    }
  },
  xAxis: {
    calibration: true,
    formatter: (val) => {
      if (val % 3 === 0) {
        return `${val}点`
      } else {
        return ''
      }
    }
  }
})
const runningData = ref({
  categories: [],
  series: [
    {
      name: '上行次数',
      formatter: () => '',
      data: []
    },
    {
      name: '下行次数',
      formatter: () => '',
      data: []
    },
    {
      name: '关门次数',
      formatter: () => '',
      data: []
    },
    {
      name: '停梯次数',
      formatter: () => '',
      data: []
    },
    {
      name: '运行距离(km)',
      formatter: () => '',
      data: []
    }
  ]
})

const floorDataOpts = ref({
  enableScroll: false,
  xAxis: {
    scrollShow: false,
    itemCount: 4,
    disableGrid: true,
    formatter: (val) => {
      return `${val}层`
    }
  }
})
const floorData = ref({
  categories: [],
  series: [
    {
      name: '停梯次数',
      formatter: () => '',
      data: []
    }
  ]
})
const showMyTooltip = (e) => {
  console.log('获取点击索引事件', e)
  //拿到canvasId后即e.id，可以通过uCharts.instance[e.id]代表当前的图表实例（除APP端，APP不可在组件外调用uCharts的实例）
  console.log('获取uCharts实例', uCharts.instance[e.id])
  //uCharts.option[e.id]代表当前的图表的opts（除APP端，APP不可在组件外调用uCharts的实例）
  console.log('uCharts的option', uCharts.option[e.id])
  //从option（opts）中获取数据
  const categories = uCharts.option[e.id].categories
  const series = uCharts.option[e.id].series
  //e.currentIndex是点击的的点位索引值
  const index = e.currentIndex.index //注意v2.1.2版本后，e.currentIndex是对象，而e.currentIndex.index是索引值，如果是时间轴图表，index在多个series的情况下会是数组
  //自行通过uCharts的实例调用showToolTip方法（APP端不能实现，无法通过renderjs获取到uCharts实例）
  // #ifndef APP-PLUS
  //如果需要tooltip换行显示，也可以参照本示例，关闭组件本身的tooltip功能，即:tooltipShow="false"，然后在@getIndex事件中，通过uCharts.instance[e.id].showToolTip()方法来自定义。
  let text = ''
  if (currSub.value === 0) {
    text = `${categories[index]}点数据`
  } else if (currSub.value === 1) {
    text = `星期${categories[index]}数据`
  } else if (currSub.value === 2) {
    text = `${categories[index]}号数据`
  }
  const textList = [{ text, color: null }]
  for (let i = 0; i < series.length; i++) {
    textList.push({
      text: `${series[i].name}：${series[i].data[index]}`,
      color: series[i].color
    })
  }
  //changedTouches是点击的坐标值
  uCharts.instance[e.id].showToolTip(
    { changedTouches: [e.event] },
    {
      index: index,
      textList: textList
    }
  )
  // #endif
}

// 根据当前时间的 hour 分割数据，截断
const splitCurrentHour = (arr) => {
  if (currSub.value === 0) {
    return arr.slice(0, dayjs().hour() + 1)
  } else {
    return arr
  }
}

const getAllStatistics = async () => {
  const [start, end] = currDate.value
  const { error, data } = await getElevatorDetailStatisticsApi({
    // startTime: `${dayjs(start).format('YYYY-MM-DD')} 00:00:00`,
    // endTime: `${dayjs(start || end).format('YYYY-MM-DD')} 23:59:59`,
    startTime: `${start} 00:00:00`,
    endTime: `${end || start} 23:59:59`,
    statisticsType: currDate.value.length,
    ...options.value
  })
  if (error) {
    return
  }
  allData.value = data
  const { busyNum, moderateNum, idleNum } = data

  baseData.value = [
    { label: '繁忙时间段(个)', value: busyNum },
    { label: '适中时间段(个)', value: moderateNum },
    { label: '较闲时间段(个)', value: idleNum }
  ]
  const {
    timeLineList,
    upNumList,
    downNumList,
    openCloseNumList,
    stopStationNumList,
    runMileageList,
    floorList,
    floorStopStationNumList
  } = data
  if (currSub.value === 0) {
    runningData.value.categories = splitCurrentHour(timeLineList)
  }
  runningData.value.series[0].data = splitCurrentHour(upNumList)
  runningData.value.series[1].data = splitCurrentHour(downNumList)
  runningData.value.series[2].data = splitCurrentHour(openCloseNumList)
  runningData.value.series[3].data = splitCurrentHour(stopStationNumList)
  runningData.value.series[4].data = splitCurrentHour(runMileageList)

  if (floorList.length > 4) {
    floorDataOpts.value.enableScroll = true
    floorDataOpts.value.xAxis.scrollShow = true
  }
  floorData.value.categories = floorList
  floorData.value.series[0].data = floorStopStationNumList
  return data
}

const options = ref({})
onLoad((e) => {
  options.value = e
  getAllStatistics()
})
</script>

<template>
  <view px-28>
    <up-subsection :list="list" :current="currSub" @change="subsectionChange" />

    <!-- 日期 -->
    <view w-full flex justify-between mt-24>
      <view bg="#F0F7FC" w-50 h-50 rounded-full f-c-c @tap="changeDate(true)">
        <up-icon name="arrow-left" :color="`${'#4395D5'}`" />
      </view>
      <view color="#4395D5">{{ date }}</view>
      <view bg="#F0F7FC" w-50 h-50 rounded-full f-c-c @tap="changeDate(false)">
        <up-icon name="arrow-right" :color="`${'#4395D5'}`" />
      </view>
    </view>

    <!-- 每日数据 -->
    <view v-if="currSub === 0" mt-28>
      <up-row justify="space-between" gutter="10">
        <up-col v-for="(item, index) in baseData" :key="index" span="4">
          <view color="#4395D5">{{ item.label }}</view>
          <view color="#4395D5" text-center text-32 font-500 mt-4>
            {{ item.value }}
          </view>
        </up-col>
      </up-row>
    </view>

    <!-- 折线图 - 运行数据 -->
    <view mt-28>
      <qiun-data-charts
        :tooltip-show="false"
        type="line"
        :opts="opts"
        :chart-data="runningData"
        @getIndex="showMyTooltip"
      />
    </view>

    <!-- 折线图 - 停梯次数 -->
    <view mt-28>
      <view color="#4395D5" text-center mb-28>当前选择时间：{{ date }}</view>
      <qiun-data-charts
        :tooltip-show="false"
        :ontouch="true"
        :canvas2d="true"
        type="line"
        :opts="floorDataOpts"
        :chart-data="floorData"
        @getIndex="showMyTooltip"
      />
    </view>
  </view>
</template>
