<template>
  <view class="content">
    <view class="map-part" v-show="activeTab == 1">
      <view class="list-icon" @click="showList = !showList">
        <wd-icon name="bulletpoint" size="20px" color="#4783FA"></wd-icon>
      </view>
      <view class="event-list" v-show="showList">
        <view class="event-list-header">
          <view>
            <wd-picker :columns="eventLevel" v-model="queryParams.level" use-default-slot>
              <wd-input
                style="width: 110rpx; margin-right: 20rpx"
                readonly
                no-border
                :placeholder="
                  eventLevel.filter((item) => item.value == queryParams.level)[0]?.label ||
                  '事件等级'
                "
              >
              </wd-input>
            </wd-picker>

            <wd-input no-border v-model="queryParams.params.lx" placeholder="事件类型" />
            <wd-calendar
              type="daterange"
              :shortcuts="shortcuts"
              :on-shortcuts-click="onShortcutsClick"
              v-model="queryParams.dateRange"
              @confirm="calendarConfirm"
            >
              <view class="date-range">
                <wd-input
                  readonly
                  no-border
                  v-model="queryParams.params.beginCreateTime"
                  placeholder="开始时间"
                />
                ~
                <wd-input
                  readonly
                  no-border
                  v-model="queryParams.params.endCreateTime"
                  placeholder="结束时间"
                />
              </view>
            </wd-calendar>
          </view>
          <view class="addr-search">
            <wd-input
              no-border
              v-model="queryParams.params.key"
              suffix-icon="search"
              placeholder="输入地点关键字"
            />
            <view>
              <wd-button :round="false" size="small" @click="getList">查询</wd-button>
              <wd-button :round="false" size="small" @click="resetClick">重置</wd-button>
            </view>
          </view>
        </view>
        <view class="event-list-table">
          <wd-table :data="eventList" :show-header="false" :border="false">
            <wd-table-col prop="level" label="" :width="80">
              <template #value="{ row }">
                <view>{{ eventLevel.filter((item) => item.value == row.level)[0]?.label }}</view>
              </template>
            </wd-table-col>
            <wd-table-col prop="" :width="80" label="">
              <template #value="{ row }">
                <view>{{ row.ext2.lx }}</view>
              </template>
            </wd-table-col>
            <wd-table-col prop="addr" label=""></wd-table-col>
            <wd-table-col prop="createTimeFormat" label="" :width="100"></wd-table-col>
            <wd-table-col prop="status" label="" :width="60">
              <template #value="{ row }">
                <view v-if="row.status == 3" style="color: #5f86fd">已上报</view>
                <view v-else-if="row.status == 1" style="color: #26c768">已解决</view>
                <view v-else style="color: #ff6124">未解决</view>
              </template>
            </wd-table-col>
            <wd-table-col :width="60" prop="" label="">
              <template #value="{ row }">
                <wd-button
                  style="background: transparent; color: #507afc"
                  :round="false"
                  size="small"
                  @click="showDetails(row)"
                  >查看</wd-button
                >
              </template>
            </wd-table-col>
          </wd-table>
        </view>
        <view class="event-list-footer">
          <wd-pagination
            v-model="queryParams.pageNum"
            @change="pageChange"
            :page-size="queryParams.pageSize"
            :total="total"
          ></wd-pagination>
        </view>
      </view>
      <view class="map" id="map"></view>
    </view>
    <view class="data-part" v-show="activeTab == 2">
      <view class="data-panel">
        <view class="custom-title">
          <img src="/static/images/title.svg" />
          <text>本月</text>
        </view>
        <view class="custom-card">
          <view class="card-item">
            <text>{{ statData.monthCount }}</text>
            <text>所有数量</text>
          </view>
          <view class="card-item">
            <text>{{ statData.monthAlready }}</text>
            <text>已解决</text>
          </view>
          <view class="card-item">
            <text>{{ statData.monthNot }}</text>
            <text>未解决</text>
          </view>
          <view class="card-item">
            <text>{{ statData.monthReport }}</text>
            <text>已上报</text>
          </view>
        </view>
      </view>
      <view class="data-panel" style="margin-top: 40rpx">
        <view class="custom-title">
          <img src="/static/images/title.svg" />
          <text>本周</text>
        </view>
        <view class="custom-card week-card">
          <view class="card-item">
            <text>{{ statData.weekCount }}</text>
            <text>所有数量</text>
          </view>
          <view class="card-item">
            <text>{{ statData.weekAlready }}</text>
            <text>已解决</text>
          </view>
          <view class="card-item">
            <text>{{ statData.weekNot }}</text>
            <text>未解决</text>
          </view>
          <view class="card-item">
            <text>{{ statData.weekReport }}</text>
            <text>已上报</text>
          </view>
        </view>
      </view>
      <view class="data-panel" style="margin-top: 40rpx">
        <view class="custom-title">
          <img src="/static/images/title.svg" />
          <text>当天</text>
        </view>
        <view class="custom-card day-card">
          <view class="card-item">
            <text>{{ statData.dayCount }}</text>
            <text>所有数量</text>
          </view>
          <view class="card-item">
            <text>{{ statData.dayAlready }}</text>
            <text>已解决</text>
          </view>
          <view class="card-item">
            <text>{{ statData.dayNot }}</text>
            <text>未解决</text>
          </view>
          <view class="card-item">
            <text>{{ statData.dayReport }}</text>
            <text>已上报</text>
          </view>
        </view>
      </view>
      <view class="data-panel" style="margin-top: 40rpx">
        <view class="custom-title" style="border: none">
          <img src="/static/images/title.svg" />
          <text>统计分析</text>
        </view>
        <view class="pie-chart">
          <l-echart ref="pie"></l-echart>
        </view>
      </view>
    </view>
    <view class="fixed-footer">
      <view
        :class="{ 'tab-selected': activeTab == item.value }"
        v-for="item in tabList"
        :key="item.value"
        @click="tabClick(item)"
        >{{ item.name }}</view
      >
    </view>
  </view>
</template>

<script setup>
  import monitorIcon from '/static/images/monitor.svg'
  import * as echarts from 'echarts'
  import lEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue'
  import { dateFormat } from '@/utils/index'
  const { API_EVENT_LIST } = useRequest()
  const tabList = [
    { name: '地图', value: '1' },
    { name: '数据', value: '2' }
  ]
  const pie = shallowRef(null)
  const eventLevel = [
    {
      label: '内部掌握',
      value: '1'
    },
    {
      label: '建议上报',
      value: '2'
    }
  ]
  const eventStatus = [
    {
      label: '已解决',
      value: '1'
    },
    {
      label: '未解决',
      value: '2'
    },
    {
      label: '已上报',
      value: '3'
    }
  ]
  const shortcuts = ref([
    {
      text: '近7天',
      id: 7
    },
    {
      text: '近15天',
      id: 15
    },
    {
      text: '近30天',
      id: 30
    }
  ])
  const onShortcutsClick = ({ item }) => {
    const dayDiff = item.id
    const endDate = Date.now() - 24 * 60 * 60 * 1000
    const startDate = endDate - dayDiff * 24 * 60 * 60 * 1000

    return [startDate, endDate]
  }
  const calendarConfirm = ({ value }) => {
    if (value && value.length) {
      queryParams.value.params.beginCreateTime = dateFormat(new Date(value[0]), 'yyyy-MM-dd')
      queryParams.value.params.endCreateTime = dateFormat(new Date(value[1]), 'yyyy-MM-dd')
    }
  }
  const activeTab = ref('1')
  const showList = ref(false)
  const bdmap = ref(null)
  const marks = ref([
    {
      longitude: 118.84651017058795,
      latitude: 32.03286965957209
    },
    {
      longitude: 118.87381865809128,
      latitude: 32.050866853291296
    },
    {
      longitude: 118.88459832421101,
      latitude: 32.01094988629638
    }
  ])
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    level: undefined,
    dateRange: [],
    params: {
      lx: undefined,
      key: undefined,
      beginCreateTime: undefined,
      endCreateTime: undefined
    }
  })
  const statData = reactive({
    monthCount: 0,
    monthAlready: 0,
    monthNot: 0,
    monthReport: 0,
    weekCount: 0,
    weekAlready: 0,
    weekNot: 0,
    weekReport: 0,
    dayCount: 0,
    dayAlready: 0,
    dayNot: 0,
    dayReport: 0,
    already: 0,
    not: 0,
    report: 0
  })
  const total = ref(0)
  const eventList = ref([])
  const getPieOptions = () => {
    return {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'horizontal',
        left: 'center',
        itemWidth: 15,
        itemHeight: 8,
        itemGap: 10
      },
      series: [
        {
          type: 'pie',
          radius: ['40%', '80%'],
          center: ['50%', '60%'],
          data: [
            {
              value: statData.already,
              name: '已解决',
              itemStyle: {
                color: '#FAC858'
              }
            },
            {
              value: statData.not,
              name: '未解决',
              itemStyle: {
                color: '#93BEFF'
              }
            },
            {
              value: statData.report,
              name: '已上报',
              itemStyle: {
                color: '#507AFC'
              }
            }
          ],
          labelLine: {
            show: false
          },
          label: {
            show: false,
            position: 'center'
          }
        }
      ]
    }
  }
  const tabClick = (item) => {
    if (activeTab.value === item.value) return
    activeTab.value = item.value
    if (item.value === '2') {
      initPieChart()
    }
  }
  const showMarks = () => {
    bdmap.value.clearOverlays()
    marks.value.forEach((item) => {
      const pt = new BMapGL.Point(Number(item.longitude), Number(item.latitude))
      const icon = new BMapGL.Icon(monitorIcon, new BMapGL.Size(30, 30))
      const marker = new BMapGL.Marker(pt, { icon })
      bdmap.value.addOverlay(marker)
    })
  }
  const getList = async () => {
    const res = await API_EVENT_LIST(queryParams.value)
    eventList.value = res.rows.map((item) => ({
      ...item,
      status: item.status || '2',
      createTimeFormat: dateFormat(new Date(item.createTime), 'yyyy-MM-dd'),
      ext1: item.ext1 ? JSON.parse(item.ext1) : [],
      ext2: item.ext2 ? JSON.parse(item.ext2) : {}
    }))
    total.value = res.total
  }
  const getStat = async () => {
    const monthRange = getTimeRange('month')
    const monthRes = await API_EVENT_LIST({
      params: {
        beginCreateTime: monthRange.start,
        endCreateTime: monthRange.end
      }
    })
    statData.monthCount = monthRes.total
    statData.monthAlready = monthRes.rows.filter((item) => item.status === '1').length
    statData.monthNot = monthRes.rows.filter(
      (item) => item.status === '2' || item.status === null
    ).length
    statData.monthReport = monthRes.rows.filter((item) => item.status === '3').length
    const weekRange = getTimeRange('week', { firstDayOfWeek: 0 })
    const weekRes = await API_EVENT_LIST({
      params: {
        beginCreateTime: weekRange.start,
        endCreateTime: weekRange.end
      }
    })
    statData.weekCount = weekRes.total
    statData.weekAlready = weekRes.rows.filter((item) => item.status === '1').length
    statData.weekNot = weekRes.rows.filter(
      (item) => item.status === '2' || item.status === null
    ).length
    statData.weekReport = weekRes.rows.filter((item) => item.status === '3').length
    const todayRange = getTimeRange('day')
    const todayRes = await API_EVENT_LIST({
      params: {
        beginCreateTime: todayRange.start,
        endCreateTime: todayRange.end
      }
    })
    statData.dayCount = todayRes.total
    statData.dayAlready = todayRes.rows.filter((item) => item.status === '1').length
    statData.dayNot = todayRes.rows.filter(
      (item) => item.status === '2' || item.status === null
    ).length
    statData.dayReport = todayRes.rows.filter((item) => item.status === '3').length
    const res = await API_EVENT_LIST({})
    statData.already = res.rows.filter((item) => item.status === '1').length
    statData.not = res.rows.filter((item) => item.status === '2' || item.status === null).length
    statData.report = res.rows.filter((item) => item.status === '3').length
  }
  const pageChange = (e) => {
    queryParams.value.pageNum = e.value
    getList()
  }
  const getTimeRange = (unit = 'day', options = {}) => {
    const now = new Date()
    const { firstDayOfWeek = 1 } = options

    // 定义结果容器
    const result = {
      unit,
      startDate: null,
      endDate: null,
      start: '',
      end: '',
      description: '',
      duration: 0
    }

    // 内部工具函数：格式化日期时间为字符串
    const format = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }

    // 处理不同类型的时间范围
    switch (unit.toLowerCase()) {
      case 'day':
        // 当天范围 (00:00:00.000 - 23:59:59.999)
        const dayStart = new Date(now)
        dayStart.setHours(0, 0, 0, 0)

        const dayEnd = new Date(now)
        dayEnd.setHours(23, 59, 59, 999)

        result.startDate = dayStart
        result.endDate = dayEnd
        result.start = format(dayStart)
        result.end = format(dayEnd)
        result.description = `当天范围: ${result.start} 至 ${result.end}`
        result.duration = 1
        break

      case 'week':
        // 计算周起始日偏移
        const dayOfWeek = now.getDay()
        const diffToFirstDay = (dayOfWeek < firstDayOfWeek ? 7 : 0) + dayOfWeek - firstDayOfWeek

        // 本周开始 (周一 00:00:00.000)
        const weekStart = new Date(now)
        weekStart.setDate(now.getDate() - diffToFirstDay)
        weekStart.setHours(0, 0, 0, 0)

        // 本周结束 (周日 23:59:59.999)
        const weekEnd = new Date(weekStart)
        weekEnd.setDate(weekStart.getDate() + 6)
        weekEnd.setHours(23, 59, 59, 999)

        // 设置结果
        result.startDate = weekStart
        result.endDate = weekEnd
        result.start = format(weekStart)
        result.end = format(weekEnd)
        result.duration = 7

        // 生成描述信息
        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
        const startDayName = weekDays[firstDayOfWeek]
        const endDayName = weekDays[(firstDayOfWeek + 6) % 7]
        result.description = `本周范围 (${startDayName}至${endDayName}): ${result.start} 至 ${result.end}`
        break

      case 'month':
        // 本月第一天 (1号 00:00:00.000)
        const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
        monthStart.setHours(0, 0, 0, 0)

        // 本月最后一天 (月末日 23:59:59.999)
        const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0)
        monthEnd.setHours(23, 59, 59, 999)

        // 设置结果
        result.startDate = monthStart
        result.endDate = monthEnd
        result.start = format(monthStart)
        result.end = format(monthEnd)

        // 计算天数
        const dayDiff = Math.floor((monthEnd - monthStart) / (1000 * 60 * 60 * 24)) + 1
        result.duration = dayDiff

        // 获取月份名称
        const monthNames = [
          '一月',
          '二月',
          '三月',
          '四月',
          '五月',
          '六月',
          '七月',
          '八月',
          '九月',
          '十月',
          '十一月',
          '十二月'
        ]
        result.description = `${monthNames[now.getMonth()]}范围 (共${dayDiff}天): ${result.start} 至 ${result.end}`
        break

      default:
        throw new Error(`无效的时间单位: "${unit}". 请使用 'day', 'week' 或 'month'`)
    }

    return result
  }
  const resetClick = () => {
    queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      level: undefined,
      dateRange: [],
      params: {
        lx: undefined,
        key: undefined,
        beginCreateTime: undefined,
        endCreateTime: undefined
      }
    }
    getList()
  }
  const showDetails = (row) => {
    uni.navigateTo({
      url: `/pages/index/info?id=${row.id}`
    })
  }
  const initPieChart = () => {
    pie.value.init(echarts, (chart) => {
      chart.setOption(getPieOptions())
    })
  }
  onMounted(() => {
    const map = new BMapGL.Map('map') // 创建地图实例
    const point = new BMapGL.Point(118.879999, 32.016216) // 创建点坐标
    map.centerAndZoom(point, 14)
    map.enableScrollWheelZoom(true)
    bdmap.value = map
    map.addEventListener('click', function (e) {
      const { lng, lat } = e.latlng
      console.log(e.latlng)
    })
    showMarks()
    getList()
    getStat()
  })
</script>

<style lang="scss" scoped>
  .content {
    height: 100%;
    background: #fff;
    display: flex;
    flex-direction: column;

    :deep(.anchorBL) {
      display: none;
    }
  }

  .map-part {
    width: 100%;
    height: 100%;
    flex: 1;
    overflow-y: auto;

    .map {
      width: 100%;
      height: 100%;
    }
  }

  .list-icon {
    position: absolute;
    right: 30rpx;
    top: 30rpx;
    width: 70rpx;
    height: 66rpx;
    border-radius: 6rpx;
    background: #ffffff;
    box-shadow: 0 4rpx 10rpx 0 #0000004d;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10;
  }

  .event-list {
    position: absolute;
    background: #ffffff;
    left: 0;
    right: 0;
    top: 150rpx;
    bottom: 120rpx;
    z-index: 12;
    display: flex;
    flex-direction: column;

    &-header {
      background: #f8f8f8;
      padding: 20rpx;

      :deep(.wd-input__placeholder) {
        color: #262626;
      }

      :deep(.wd-input) {
        padding: 0 10rpx;
        background-color: #f8f8f8;
        border: 1px solid #d6d6d7;
        border-radius: 4rpx;
      }

      > view:first-of-type {
        display: flex;
        align-items: center;

        > .wd-input {
          margin-right: 20rpx;
          width: 110rpx;
          flex-shrink: 0;
        }

        .date-range {
          flex: 1;
          display: flex;
          align-items: center;
        }
      }

      .addr-search {
        margin-top: 10rpx;
        display: flex;
        align-items: center;

        .wd-input {
          width: 345rpx;
        }

        > view:last-child {
          margin-left: 20rpx;
          display: flex;
          align-items: center;

          .wd-button {
            height: 48rpx;
            margin-right: 10rpx;

            &:first-of-type {
              background: #1890ff;
            }

            &:last-of-type {
              background: #ffffff;
              color: #000000d9;
              border: 1px solid #cbcbcb;
            }
          }
        }
      }
    }

    &-table {
      flex: 1;
      overflow-y: auto;
    }

    &-footer {
      height: 100rpx;
    }
  }

  .data-part {
    width: 100%;
    flex: 1;
    padding-bottom: 50rpx;
    overflow-y: auto;

    .data-panel {
      .custom-title {
        display: flex;
        align-items: center;
        color: #000000;
        font-size: 32rpx;
        padding: 30rpx;
        border-bottom: 2rpx solid #e9e9e9;

        img {
          height: 35rpx;
          margin-right: 10rpx;
        }
      }

      .custom-card {
        display: flex;
        justify-content: space-between;
        height: 100%;
        padding: 0 50rpx;
        margin-top: 40rpx;

        .card-item {
          display: flex;
          width: 22.5%;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          height: 100%;
          background: #e3eefe;
          color: #2d5794;
          border-radius: 10rpx;

          text:first-child {
            flex: 1;
            font-size: 44rpx;
            margin-top: 20rpx;
            display: flex;
            align-items: center;
          }

          text:last-child {
            width: 80%;
            text-align: center;
            height: 52rpx;
            line-height: 52rpx;
            border-top: 1rpx solid #d0dff4;
            font-size: 20rpx;
          }
        }
      }

      .week-card {
        .card-item {
          background: #fef4e3;

          text:first-child {
            color: #7c5b22;
          }

          text:last-child {
            border-color: #eddbbc;
            color: #8c692e;
          }
        }
      }

      .day-card {
        .card-item {
          background: #e3fef0;

          text:first-child {
            color: #248647;
          }

          text:last-child {
            border-color: #ade7cd;
            color: #238546;
          }
        }
      }

      .pie-chart {
        height: 400rpx;
        width: 100%;
      }
    }
  }

  .fixed-footer {
    height: 120rpx;
    width: 100%;
    display: flex;
    background: #e1edff;
    line-height: 120rpx;
    color: #313131;
    font-size: 34rpx;

    .tab-selected {
      background: #507afc;
      color: #fff;
    }

    > view {
      flex: 1;
      text-align: center;
    }
  }
</style>
