<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="alarmRetention">异常滞留</a-radio-button>
        <a-radio-button value="generalRetention">一般滞留</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 === 'alarmRetention'" label="告警类型">
          <a-select
            v-model:value="searchState.eventType"
            placeholder="请选择"
            style="width: 120px"
            :options="alarmEventTypeOptions"
            @change="searchHandler"
          />
        </a-form-item>

        <a-form-item v-if="tableType === 'generalRetention'" label="滞留类型">
          <a-select
            v-model:value="searchState.type"
            placeholder="请选择"
            style="width: 120px"
            :options="stayEventTypeOptions"
            @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 === 'pose'">
            {{ record.poseName }}
          </template>
          <!-- 跌倒、异常统计 是否处理  -->
          <template v-if="column.key === 'isHandle'">
            <a-tag v-if="record.isHandle === 0" :bordered="false" color="red">未处理</a-tag>
            <a-tag v-if="record.isHandle === 1" :bordered="false" color="green">已处理</a-tag>
          </template>
          <!-- 异常滞留 告警类型 -->
          <template v-if="column.key === 'eventType'">
            {{ record.eventTypeName }}
          </template>
          <!-- 一般滞留 滞留类型 -->
          <template v-if="column.key === 'type'">
            {{ record.typeName }}
          </template>
          <!-- 一般滞留 停留时间 -->
          <template v-if="column.key === 'stayTime'">
            {{ formatSeconds(record.stayTime) }}
          </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, generalRetentionColumns, alarmRetentionColumns } from './const'
import * as statsApi from '@/api/stats'
import type {
  StatsFallQueryDataRow,
  StatsAlarmRetentionQueryDataRow,
  StatsGeneralRetentionQueryDataRows,
} from '@/api/stats/types'
import { useDict } from '@/hooks/useDict'
import { useDictName } from '@/hooks/useDictName'
import { formatSeconds } from '@/utils'

defineOptions({
  name: 'DeviceStatsDrawer',
})

type Props = {
  open: boolean
  devId: string
  title?: string
  width?: number
}

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

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

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

const columns = computed(() => {
  if (tableType.value === 'generalRetention') {
    return generalRetentionColumns
  } else if (tableType.value === 'alarmRetention') {
    return alarmRetentionColumns
  } 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') // 姿势字典
const { dictList: alarmEventTypeList, fetchDict: fetchAlarmEventType } = useDict('alarm_event_type') // 异常告警字典
const { dictList: stayEventTypeList, fetchDict: fetchStayEventType } = useDict('stay_event_type') // 停留类型字典
fetchPersonPose()
fetchAlarmEventType()
fetchStayEventType()

const { dictNameMap: personPoseName } = useDictName(personPoseList)
const { dictNameMap: alarmEventTypeName } = useDictName(alarmEventTypeList)
const { dictNameMap: stayEventTypeName } = useDictName(stayEventTypeList)

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

const tableList = ref<
  (StatsFallQueryDataRow | StatsGeneralRetentionQueryDataRows | StatsAlarmRetentionQueryDataRow)[]
>([])
const tableTotal = ref<number>(0)
const current = ref<number>(1)
const pageSize = ref<number>(10)

const fallList = ref<StatsFallQueryDataRow[]>([])
const generalRetentionList = ref<StatsGeneralRetentionQueryDataRows[]>([])
const alarmRetentionList = ref<StatsAlarmRetentionQueryDataRow[]>([])

// 搜索
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 = personPoseName(String(item.pose))
    })
    tableList.value = fallList.value
    tableTotal.value = Number(total)
    loading.value = false
  } catch (error) {
    console.error('❌ 获取跌倒统计数据失败', error)
    loading.value = false
  }
}

// 获取一般滞留数据
const fetchGeneralRetentionList = async () => {
  console.log('🚀🚀🚀fetchGeneralRetentionList')
  try {
    loading.value = true
    const res = await statsApi.statsGeneralRetentionQuery({
      pageNo: current.value,
      pageSize: pageSize.value,
      devId: props.devId,
      createTimeStart: searchState.createTimeStart,
      createTimeEnd: searchState.createTimeEnd,
      type: searchState.type as ID,
    })
    console.log('✅ 获取一般滞留统计数据成功', res)
    const { rows, total } = res.data
    generalRetentionList.value = rows as StatsGeneralRetentionQueryDataRows[]
    generalRetentionList.value.forEach((item) => {
      console.log('item.pose', item)
      item.typeName = stayEventTypeName(String(item.type))
    })
    tableList.value = generalRetentionList.value
    tableTotal.value = Number(total)
    loading.value = false
  } catch (error) {
    console.error('❌ 获取一般滞留统计数据失败', error)
    loading.value = false
  }
}

// 获取异常滞留数据
const fetchAlarmRetentionList = async () => {
  console.log('🚀🚀🚀fetchAlarmRetentionList')
  try {
    loading.value = true
    const res = await statsApi.statsAlarmRetentionQuery({
      pageNo: current.value,
      pageSize: pageSize.value,
      devId: props.devId,
      createTimeStart: searchState.createTimeStart,
      createTimeEnd: searchState.createTimeEnd,
      eventType: searchState.eventType as ID,
    })
    console.log('✅ 获取异常滞留统计数据成功', res)
    const { rows, total } = res.data
    alarmRetentionList.value = rows as StatsAlarmRetentionQueryDataRow[]
    alarmRetentionList.value.forEach((item) => {
      console.log('item.pose', item)
      item.poseName = personPoseName(String(item.pose))
      item.eventTypeName = alarmEventTypeName(String(item.eventType))
    })
    tableList.value = alarmRetentionList.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 === 'generalRetention') {
    fetchGeneralRetentionList()
  }
  if (tableType.value === 'alarmRetention') {
    fetchAlarmRetentionList()
  }
}

watch(
  () => tableType.value,
  () => {
    fetchList()
  },
  { immediate: true }
)
</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;
    }
  }
}
</style>
