<template>
  <a-drawer
    :open="props.open"
    class="config-drawer"
    root-class-name="config-drawer-root"
    :title="props.title"
    :width="props.width"
    placement="right"
    @close="close"
  >
    <template #extra>
      <a-radio-group v-model:value="tableType" button-style="solid" size="small">
        <a-radio-button value="fall">跌倒统计</a-radio-button>
        <a-radio-button value="alarm">告警统计</a-radio-button>
        <a-radio-button value="online">上下线记录</a-radio-button>
        <a-radio-button value="inout">历史进出记录</a-radio-button>
      </a-radio-group>
    </template>

    <div class="searchBar">
      <a-form layout="inline" @keydown.enter="searchHandler">
        <a-form-item label="创建时间">
          <range-picker
            v-model:start="searchState.createTimeStart"
            v-model:end="searchState.createTimeEnd"
            @change="searchHandler"
          />
        </a-form-item>

        <a-form-item v-if="tableType === 'alarm'" label="告警类型">
          <a-select
            v-model:value="searchState.eventType"
            placeholder="请选择"
            style="width: 150px"
            :options="alarmEventTypeOptions"
            @change="searchHandler"
          />
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" @click="searchHandler"> 搜索 </a-button>
            <a-button @click="resetHandler"> 重置 </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <div class="tableCard">
      <a-table :columns="columns" :data-source="tableList" :loading="loading" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'eventType'">
            {{ record.eventTypeName }}
          </template>
          <template v-if="column.key === 'info'">
            <div class="eventInfo">
              <div v-if="record.info?.start_time">开始时间：{{ record.info?.start_time }}</div>
              <div v-if="record.info?.end_time">结束时间：{{ record.info?.end_time }}</div>
              <div v-if="record.info?.stay_time"
                >停留时长：{{ formatSeconds(record.info?.stay_time) }}</div
              >
              <div v-if="record.info?.count">次数：{{ record.info?.count }}</div>
              <a-collapse ghost accordion v-if="record.info?.event_list && !initPanel">
                <template #expandIcon="{ isActive }">
                  <caret-right-outlined :rotate="isActive ? 90 : 0" />
                </template>
                <a-collapse-panel :header="`事件列表 (${record.info?.event_list?.length ?? 0}条)`">
                  <ScrollContainer style="max-height: 110px">
                    <div
                      v-for="(event, index) in record.info?.event_list"
                      :key="index"
                      class="eventInfo-list"
                    >
                      <div v-if="event.start_time">开始时间：{{ event.start_time }}</div>
                      <div v-if="event.end_time">结束时间：{{ event.end_time }}</div>
                      <div v-if="event.stay_time"
                        >停留时长：{{ formatSeconds(event.stay_time) }}</div
                      >
                      <div v-if="event.absence_time"
                        >消失时长：{{ formatSeconds(event.absence_time) }}</div
                      >
                      <span class="showIndex">{{ index + 1 }}</span>
                    </div>
                  </ScrollContainer>
                </a-collapse-panel>
              </a-collapse>
            </div>
          </template>

          <template v-if="column.key === 'onlineType'">
            <a-tag v-if="record.type === 'on'" :bordered="false" color="green">上线</a-tag>
            <a-tag v-if="record.type === 'off'" :bordered="false" color="red">离线</a-tag>
          </template>
        </template>
      </a-table>

      <base-pagination
        v-if="tableTotal > 0"
        v-model:current="current"
        v-model:pageSize="pageSize"
        :total="tableTotal"
        @change="paginationChange"
        @showSizeChange="paginationSizeChange"
      ></base-pagination>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useSearch } from '@/hooks/useSearch'
import { fallColumns, alarmColumns, onlineColumns, inoutColumns } from './const'
import * as statsApi from '@/api/stats'
import type {
  StatsFallQueryDataRow,
  StatsAlarmQueryDataRow,
  StatsDeviceOnlineQueryDataRow,
  StatsInoutHistoryQueryDataRow,
} from '@/api/stats/types'
import { useDict, type DictItem } from '@/hooks/useDict'
import { useDictName } from '@/hooks/useDictName'
import * as alarmApi from '@/api/alarm'
import { CaretRightOutlined } from '@ant-design/icons-vue'
import { formatSeconds } from '@/utils/index'

defineOptions({
  name: 'DeviceStatsDrawer',
})

type Props = {
  open: boolean
  devId: string
  clientId: string
  title?: string
  width?: number
  type?: 'fall' | 'alarm' | 'online' | 'inout'
}

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'success', value: void): void
}>()
const props = withDefaults(defineProps<Props>(), {
  open: false,
  devId: '',
  clientId: '',
  title: '设备历史统计',
  width: 900,
  type: 'fall',
})

// 表格统计类型展示 跌倒、一般滞留、异常滞留
const tableType = ref<'fall' | 'alarm' | 'online' | 'inout'>('fall')

const columns = computed(() => {
  if (tableType.value === 'alarm') {
    return alarmColumns
  } else if (tableType.value === 'online') {
    return onlineColumns
  } else if (tableType.value === 'inout') {
    return inoutColumns
  } else {
    return fallColumns
  }
})

interface SearchData {
  createTimeStart: string // 创建时间开始
  createTimeEnd: string // 创建时间结束
  type?: ID // 事件类型 一般滞留
  eventType?: ID // 事件类型 异常滞留
}
// 默认搜索条件
const defaultSearch: SearchData = {
  createTimeStart: '',
  createTimeEnd: '',
  type: null,
  eventType: null,
}

const afterResetHandler = () => {
  if (props.open) {
    current.value = 1
    pageSize.value = 10
    fetchList()
  }
}

const [searchState, resetHandler] = useSearch(defaultSearch, {
  afterReset: afterResetHandler,
})

const close = async () => {
  await emit('update:open', false)
  tableList.value = []
  current.value = 1
  pageSize.value = 10
  resetHandler()
}

// 获取字典数据
const { dictList: personPoseList, fetchDict: fetchPersonPose } = useDict('person_pose') // 姿势字典
fetchPersonPose()

const alarmEventTypeList = ref<DictItem[]>([])
const { dictNameMap: personPoseName } = useDictName(personPoseList)
const { dictNameMap: alarmEventTypeName } = useDictName(alarmEventTypeList)

const fetchEventTypeList = async () => {
  try {
    const res = await alarmApi.getAlarmEventTypeList()
    console.log('获取事件类型下拉列表成功✅', res)
    const data = res.data
    alarmEventTypeList.value =
      (Array.isArray(data) &&
        data.map((item) => ({
          label: item.eventDesc,
          value: item.eventVal,
        }))) ||
      []
  } catch (err) {
    console.log('获取事件类型下拉列表失败❌', err)
  }
}
fetchEventTypeList()

// 异常滞留 事件类型
const alarmEventTypeOptions = computed(() => [
  {
    label: '全部',
    value: null,
  },
  ...alarmEventTypeList.value.map((item) => ({
    label: item.label,
    value: item.value,
  })),
])

type TableList =
  | StatsFallQueryDataRow
  | StatsAlarmQueryDataRow
  | StatsDeviceOnlineQueryDataRow
  | StatsInoutHistoryQueryDataRow
const tableList = ref<TableList[]>([])
const tableTotal = ref<number>(0)
const current = ref<number>(1)
const pageSize = ref<number>(10)

const fallList = ref<StatsFallQueryDataRow[]>([])
const alarmList = ref<StatsAlarmQueryDataRow[]>([])
const onlineList = ref<StatsDeviceOnlineQueryDataRow[]>([])
const inoutList = ref<StatsInoutHistoryQueryDataRow[]>([])

// 搜索
const searchHandler = async () => {
  console.log('searchState', searchState)
  current.value = 1
  await fetchList()
}

// 分页变化
const paginationChange = (current: number, pageSize: number) => {
  console.log('change', current, pageSize)
  fetchList()
}
// 分页大小变化
const paginationSizeChange = (current: number, pageSize: number) => {
  console.log('showSizeChange', current, pageSize)
}

const loading = ref(false)
// 获取跌倒统计数据
const fetchFallList = async () => {
  console.log('🚀🚀🚀fetchFallList')
  try {
    loading.value = true
    const res = await statsApi.statsFallQuery({
      pageNo: current.value,
      pageSize: pageSize.value,
      devId: props.devId,
      createTimeStart: searchState.createTimeStart,
      createTimeEnd: searchState.createTimeEnd,
    })
    console.log('✅ 获取跌倒统计数据成功', res)
    const { rows, total } = res.data
    fallList.value = rows as StatsFallQueryDataRow[]
    fallList.value.forEach((item) => {
      item.poseName = item.pose !== null ? personPoseName(String(item.pose)) : ''
    })
    tableList.value = fallList.value
    tableTotal.value = Number(total)
    loading.value = false
  } catch (error) {
    console.error('❌ 获取跌倒统计数据失败', error)
    loading.value = false
  }
}

// 获取告警统计数据
const fetchAlarmList = async () => {
  console.log('🚀🚀🚀fetchAlarmList')
  try {
    loading.value = true
    const res = await statsApi.statsAlarmQuery({
      pageNo: current.value,
      pageSize: pageSize.value,
      clientId: props.clientId,
      createTimeStart: searchState.createTimeStart,
      createTimeEnd: searchState.createTimeEnd,
      eventType: searchState.eventType as ID,
    })
    console.log('✅ 获取告警统计数据成功', res)
    const { rows, total } = res.data
    alarmList.value = rows as StatsAlarmQueryDataRow[]
    alarmList.value.forEach((item) => {
      item.eventTypeName = alarmEventTypeName(item.eventType)
      try {
        item.info = item.info && JSON.parse(item.info)
      } catch (error) {
        item.info = ''
        console.log('❌ 解析info失败', error)
      }
    })
    tableList.value = alarmList.value
    tableTotal.value = Number(total)
    loading.value = false
  } catch (error) {
    console.error('❌ 获取告警统计数据失败', error)
    loading.value = false
  }
}

// 获取上下线统计数据
const fetchOnlineList = async () => {
  console.log('🚀🚀🚀fetchOnlineList')
  try {
    loading.value = true
    const res = await statsApi.statsDeviceOnlineQuery({
      pageNo: current.value,
      pageSize: pageSize.value,
      devId: props.devId,
      createTimeStart: searchState.createTimeStart,
      createTimeEnd: searchState.createTimeEnd,
    })
    console.log('✅ 获取上下线统计数据成功', res)
    const { rows, total } = res.data
    onlineList.value = rows as StatsDeviceOnlineQueryDataRow[]
    tableList.value = onlineList.value
    tableTotal.value = Number(total)
    loading.value = false
  } catch (error) {
    console.error('❌ 获取上下线统计数据失败', error)
    loading.value = false
  }
}

// 获取历史进出记录
const fetchInOutList = async () => {
  console.log('🚀🚀🚀fetchInOutList')
  try {
    loading.value = true
    const res = await statsApi.statsInoutHistoryQuery({
      pageNo: current.value,
      pageSize: pageSize.value,
      devId: props.devId,
      createTimeStart: searchState.createTimeStart,
      createTimeEnd: searchState.createTimeEnd,
    })
    console.log('✅ 获取历史进出记录数据成功', res)
    const { rows, total } = res.data
    inoutList.value = rows as StatsInoutHistoryQueryDataRow[]
    tableList.value = inoutList.value
    tableTotal.value = Number(total)
    loading.value = false
  } catch (error) {
    console.error('❌ 获取历史进出记录数据失败', error)
    loading.value = false
  }
}

const fetchList = () => {
  if (tableType.value === 'fall') {
    fetchFallList()
  }
  if (tableType.value === 'alarm') {
    fetchAlarmList()
  }
  if (tableType.value === 'online') {
    fetchOnlineList()
  }
  if (tableType.value === 'inout') {
    fetchInOutList()
  }
}

watch(
  () => tableType.value,
  () => {
    fetchList()
  },
  { immediate: true }
)

watch(
  () => props.open,
  (newVal) => {
    if (newVal) {
      console.log('🌸🌸 DeviceStatsDrawer PROPS 🌸🌸', props)
      tableType.value = props.type || 'fall'
      fetchList()
    }
  },
  {
    immediate: true,
  }
)

const initPanel = ref<boolean>(false)
</script>

<style scoped lang="less">
.searchBar {
  padding: 20px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  .ant-form {
    flex-grow: 1;
  }
  :deep(.ant-form-inline .ant-form-item) {
    margin-bottom: 16px !important;
  }
}

.tableCard {
  background-color: #fff;

  &-header {
    display: flex;
    justify-content: space-between;
    padding: 20px;
    &-title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .eventInfo {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 10px;
    border-radius: 4px;
    &-list {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      background-color: #eee;
      padding: 12px;
      border-radius: 5px;
      margin-bottom: 8px;
      position: relative;

      .showIndex {
        position: absolute;
        right: 0;
        bottom: 0;
        font-size: 12px;
        color: #fff;
        padding: 0 5px;
        border-radius: 5px 0 5px 0;
        background-color: #ccc;
      }
    }
  }
}

:deep(.ant-collapse > .ant-collapse-item > .ant-collapse-header) {
  padding: 0 !important;
}
:deep(.ant-collapse > .ant-collapse-item > .ant-collapse-header > .ant-collapse-header-text) {
  flex: none;
}
:deep(.ant-collapse .ant-collapse-content > .ant-collapse-content-box) {
  padding: 0 !important;
}
</style>
