<script setup>
import dayjs from 'dayjs'
import { getElevatorExaminationInfoApi } from '@/api/elevator'

import { useUniApi } from '@/composables/use-uni-api'
import uCharts from '@/uni_modules/qiun-data-charts/js_sdk/u-charts/config-ucharts.js'
const subsection = ref({
  list: ['日', '周', '月'],
  current: 0
})
const subsectionChange = (index) => {
  subsection.value.current = index
  changeChartDate()
}
const changeChartDate = () => {
  switch (subsection.value.current) {
    case 0: {
      opts.value.xAxis.formatter = (val) => {
        if (val % 3 === 0) {
          return `${val}点`
        } else {
          return ''
        }
      }
      runningData.value.categories = [
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
        20, 21, 22, 23
      ]
      break
    }
    case 1: {
      opts.value.xAxis.formatter = (val) => {
        return `星期${val}`
      }
      runningData.value.categories = [1, 2, 3, 4, 5, 6, 7]
      break
    }
    case 2: {
      opts.value.xAxis.formatter = (val) => {
        if (val % 4 === 1) {
          return `${val}号`
        } else {
          return ''
        }
      }
      // 根据上个月有多少天 生成 1～x 号数组
      const lastMonthDays = dayjs().subtract(1, 'month').daysInMonth()
      const categories = []
      for (let i = 1; i <= lastMonthDays; i++) {
        categories.push(i)
      }
      runningData.value.categories = categories
      break
    }
  }
  renderCharts()
}

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 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 (subsection.value.current === 0) {
    text = `${categories[index]}点数据`
  } else if (subsection.value.current === 1) {
    text = `星期${categories[index]}数据`
  } else if (subsection.value.current === 2) {
    text = `${categories[index]}号数据`
  }
  const textList = [{ text: `${categories[index]}点数据`, 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
}

// 获取电梯详情
const elevatorInfo = ref({})
// 体检日/周/月统计数据
const statisticsDayData = ref({})
const statisticsWeekData = ref({})
const statisticsMonthData = ref({})
// 高峰时段数据
const peakHourArr = ref([])
const peakHourData = ref([])
const peakDateStr = ref('')
// 上个月
const lastMonthStart = ref(null)
const lastMonthEnd = ref(null)
const lastMonthStr = ref(0)
const getElevatorInfo = async () => {
  const { elevatorNum } = options.value
  // 获取上个月
  const lastMonth = dayjs().subtract(1, 'month')
  const startTime = lastMonth.startOf('month').format('YYYY-MM-DD 00:00:00')
  const endTime = lastMonth.endOf('month').format('YYYY-MM-DD 23:59:59')
  lastMonthStart.value = startTime
  lastMonthEnd.value = endTime
  lastMonthStr.value = lastMonth.format('MM')
  const { error, data } = await getElevatorExaminationInfoApi({
    elevatorNum,
    startTime,
    endTime
  })
  if (error) {
    return
  }
  elevatorInfo.value = data || {}
  statisticsDayData.value = JSON.parse(data.statisticsDayData)
  statisticsWeekData.value = JSON.parse(data.statisticsWeekData)
  statisticsMonthData.value = JSON.parse(data.statisticsMonthData)
  const hourList = JSON.parse(data.peakHourData || '[]')
  peakHourData.value = hourList.map((item) => {
    const [[hours, times]] = Object.entries(item)
    return { hours, times }
  })
  peakHourArr.value = hourList.map((item) => {
    const [keys] = Object.keys(item)
    return keys
  })
  // dayjs 将时间转换为 `MM月DD日` 格式
  peakDateStr.value = dayjs(data.peakDate).format('MM月DD日')
  // 电梯安全指数
  computedElevatorSafetyIndex()
  // 电梯维保指数
  computedElevatorMaintenanceIndex()
  changeChartDate()
}

const safetyStr = ref('')
const computedElevatorSafetyIndex = () => {
  const { safetyIndex: n } = elevatorInfo.value
  if (n >= 0 && n < 1) {
    safetyStr.value = '好'
  } else if (n >= 1 && n < 2.5) {
    safetyStr.value = '较好'
  } else if (n >= 2.5 && n < 4) {
    safetyStr.value = '一般'
  } else if (n >= 4 && n < 5.5) {
    safetyStr.value = '不好'
  } else {
    safetyStr.value = '未知'
  }
}
const maintenanceStr = ref('')
const computedElevatorMaintenanceIndex = () => {
  const { maintenanceIndex: n } = elevatorInfo.value
  if (n >= 0 && n < 1) {
    maintenanceStr.value = '不需'
  } else if (n >= 1 && n < 2) {
    maintenanceStr.value = '注意'
  } else if (n >= 2 && n < 3) {
    maintenanceStr.value = '该保'
  } else if (n >= 3 && n < 4) {
    maintenanceStr.value = '必保'
  } else if (n >= 4) {
    maintenanceStr.value = '滞保'
  } else {
    maintenanceStr.value = '未知'
  }
}

// 根据 日/周/月 画 echarts
const renderCharts = () => {
  const { current } = subsection.value
  if (current === 0) {
    const {
      upNumList,
      downNumList,
      openCloseNumList,
      runMileageList,
      stopStationNumList
    } = statisticsDayData.value
    runningData.value.series[0].data = upNumList
    runningData.value.series[1].data = downNumList
    runningData.value.series[2].data = openCloseNumList
    runningData.value.series[3].data = stopStationNumList
    runningData.value.series[4].data = runMileageList
  } else if (current === 1) {
    const {
      weekUpNumList,
      weekDownNumList,
      weekOpenCloseNumList,
      weekStopStationNumList,
      weekRunMileageList
    } = statisticsWeekData.value
    runningData.value.series[0].data = weekUpNumList
    runningData.value.series[1].data = weekDownNumList
    runningData.value.series[2].data = weekOpenCloseNumList
    runningData.value.series[3].data = weekStopStationNumList
    runningData.value.series[4].data = weekRunMileageList
  } else if (current === 2) {
    const {
      monthUpNumList,
      monthDownNumList,
      monthOpenCloseNumList,
      monthRunMileageList,
      monthStopStationNumList
    } = statisticsMonthData.value
    runningData.value.series[0].data = monthUpNumList
    runningData.value.series[1].data = monthDownNumList
    runningData.value.series[2].data = monthOpenCloseNumList
    runningData.value.series[3].data = monthStopStationNumList
    runningData.value.series[4].data = monthRunMileageList
  }
}

const { navigateTo } = useUniApi()
const toDetail = () => {
  const { id, elevatorNum } = options.value
  navigateTo(
    `/pages/views/elevator-examine/detail?id=${id}&elevatorNum=${elevatorNum}`
  )
}

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

<template>
  <view bg="#F2F2F2" class="hold-table" min-h-100vh>
    <!-- 顶部 -->
    <view w-full bg-white py-12 px-24 position="fixed" z-2 top-0>
      <view f-s-c>
        <view flex items-end>
          <view text-36>电梯体检报告</view>
          <view text-28 color="#A1A1A1">({{ lastMonthStr }}月份)</view>
        </view>
        <view ml-auto>
          <up-icon
            name="file-text-fill"
            :size="`${32}`"
            :color="`${'#5EB1F8'}`"
            @click="toDetail"
          />
        </view>
      </view>
      <view color="#9A9A9A" text-26 mt-16>
        <text>编号：{{ elevatorInfo.examinationNum }}</text>
        <text ml-20>
          检测周期：{{ dayjs(lastMonthStart).format('MM/DD') }}-{{
            dayjs(lastMonthEnd).format('MM/DD')
          }}
        </text>
      </view>
    </view>

    <!-- 电梯安全指数 -->
    <view m-x-auto mt-188 w-710 bg-white px-24 rounded-18>
      <up-card
        title="电梯安全指数"
        margin="0"
        :border="false"
        :foot-border-top="false"
        :foot-style="{ padding: 0 }"
      >
        <template #body>
          <view f-c-c>
            <view relative>
              <text text-60 color-black>
                {{ elevatorInfo.safetyIndex || 0 }}
              </text>
              <view absolute right--70 top-0>
                <up-tag :text="safetyStr" type="success" size="mini" />
              </view>
            </view>
          </view>
        </template>
        <template #foot>
          <view f-s-c color="#999999" text-24 py-12>
            <up-icon name="question-circle" size="28" />
            <text ml-6>0-1好</text>
            <up-line direction="col" length="20rpx" margin="0 6rpx" />
            <text>1-2.5较好</text>
            <up-line direction="col" length="20rpx" margin="0 6rpx" />
            <text>2.5-4一般</text>
            <up-line direction="col" length="20rpx" margin="0 6rpx" />
            <text>4-5.5不好</text>
            <up-line direction="col" length="20rpx" margin="0 6rpx" />
            <text>5.5差</text>
          </view>
        </template>
      </up-card>
    </view>

    <!-- 电梯维保指数 -->
    <view m-x-auto mt-24 w-710 bg-white px-24 rounded-18>
      <up-card
        title="电梯维保指数"
        margin="0"
        :border="false"
        :foot-border-top="false"
        :foot-style="{ padding: 0 }"
      >
        <template #body>
          <view f-c-c>
            <view relative>
              <text text-60 color-black>
                {{ elevatorInfo.maintenanceIndex || 0 }}
              </text>
              <view absolute right--100 top-0>
                <up-tag :text="maintenanceStr" type="success" size="mini" />
              </view>
            </view>
          </view>
        </template>
        <template #foot>
          <view f-s-c color="#999999" text-24 py-12>
            <up-icon name="question-circle" size="28" />
            <text ml-6>0-1不需</text>
            <up-line direction="col" length="20rpx" margin="0 6rpx" />
            <text>1-2注意</text>
            <up-line direction="col" length="20rpx" margin="0 6rpx" />
            <text>2-3该保</text>
            <up-line direction="col" length="20rpx" margin="0 6rpx" />
            <text>3-4必保</text>
            <up-line direction="col" length="20rpx" margin="0 6rpx" />
            <text>>4滞保</text>
          </view>
        </template>
      </up-card>
    </view>

    <!-- 管理建议 -->
    <view m-x-auto mt-24 w-710 bg-white px-24 rounded-18>
      <up-card
        title="管理建议"
        sub-title="可按需调整电梯停站模式"
        :border="false"
        :foot-border-top="false"
        margin="0"
        :body-style="{ padding: 0 }"
      >
        <template #body>
          <view p-24>
            <view>
              1、电梯运行高峰为：
              <template v-if="peakHourArr.length">
                <text v-for="(item, index) in peakHourArr" :key="index">
                  {{ item }}
                  <text v-if="index < peakHourArr.length - 1">、</text>
                </text>
              </template>
              <template v-else>暂无</template>
            </view>
            <view>
              2、电梯停站较多的楼层为{{
                elevatorInfo.busyFloor
              }}层,可按需调整电梯停站模式
            </view>
          </view>
        </template>
      </up-card>
    </view>

    <!-- 运行数据 -->
    <view m-x-auto mt-24 w-710 bg-white px-24 rounded-18>
      <up-card
        title="运行数据"
        :border="false"
        :foot-border-top="false"
        margin="0"
        :body-style="{ padding: 0 }"
      >
        <template #body>
          <view p-24>
            <!-- 高峰日期/高峰日运行次数 -->
            <up-row>
              <up-col span="4">
                <view text-32 color-gray>高峰日期</view>
                <view text-40 color="#5EB1F8">{{ peakDateStr }}</view>
              </up-col>
              <up-col span="5" offset="2">
                <view text-32 color-gray>高峰日运行次数</view>
                <view text-40 color="#5EB1F8">
                  {{ elevatorInfo.peakRunNum }}次
                </view>
              </up-col>
            </up-row>
            <up-divider text="" />

            <!-- 高峰日期/高峰日运行次数 -->
            <up-row>
              <up-col span="12">
                <view text-32 color-gray>高峰时段</view>
                <template v-if="peakHourData.length">
                  <view
                    v-for="(item, index) in peakHourData"
                    :key="index"
                    f-s-c
                    text-40
                    color="#5EB1F8"
                  >
                    <text>{{ item.hours }}</text>
                    <text ml-20>{{ item.times }}</text>
                    <text text-32>(次/半小时)</text>
                  </view>
                </template>
                <view v-else text-40 color="#5EB1F8">暂无</view>
              </up-col>
            </up-row>
            <up-divider text="" />

            <!-- 高峰日期/高峰日运行次数 -->
            <up-row>
              <up-col span="4">
                <view text-32 color-gray>每日繁忙楼层</view>
                <view text-40 color="#5EB1F8">
                  {{ elevatorInfo.busyFloor }}层
                </view>
              </up-col>
              <up-col span="5" offset="2">
                <view text-32 color-gray>停梯</view>
                <view text-40 color="#5EB1F8">
                  {{ elevatorInfo.busyFloorNum }}次
                </view>
              </up-col>
            </up-row>
          </view>
        </template>
      </up-card>
    </view>

    <!-- 数据曲线 -->
    <view m-x-auto mt-24 w-710 bg-white px-24 rounded-18>
      <up-card
        title="数据曲线"
        margin="0"
        :border="false"
        :foot-border-top="false"
        :body-style="{ padding: 0 }"
      />
      <up-subsection
        :list="subsection.list"
        :current="subsection.current"
        mode="subsection"
        @change="subsectionChange"
      />
      <view mt-24>
        <qiun-data-charts
          :tooltip-show="false"
          :ontouch="true"
          :canvas2d="true"
          type="line"
          :opts="opts"
          :chart-data="runningData"
          @getIndex="showMyTooltip"
        />
      </view>
    </view>

    <view h-30 mt-24 />
  </view>
</template>
