<script lang="ts" setup>
import { IotStatApi } from '@/api/pms/stat'
import { CardStateItem, SummaryCardConfig, THEME } from '@/utils/kb'
import dayjs from 'dayjs'

type CardKey =
  | 'device'
  | 'maintain'
  | 'unfilledCount'
  | 'filledCount'
  | 'bytodo'
  | 'byfinished'
  | 'inspectttodo'
  | 'inspecttfinished'
  | 'zj'
  | 'xj'
  | 'utilizationRate'

type CardConfig = SummaryCardConfig<CardKey>

const cardConfigs: CardConfig[] = [
  {
    key: 'zj',
    title: '钻井总进尺(m)',
    icon: 'i-solar:ruler-bold',
    accent: THEME.color.green.strong,
    glow: THEME.color.green.glow
  },
  {
    key: 'xj',
    title: '修井总完成井数',
    icon: 'i-mdi:wrench-check-outline',
    accent: THEME.color.green.strong,
    glow: THEME.color.green.glow
  },
  {
    key: 'utilizationRate',
    title: '累计设备利用率(%)',
    icon: 'i-material-symbols:device-hub-rounded',
    accent: THEME.color.green.strong,
    glow: THEME.color.green.glow
  },
  {
    key: 'device',
    title: '设备数',
    icon: 'i-material-symbols:device-hub-rounded',
    accent: THEME.color.blue.strong,
    glow: THEME.color.blue.glow
  },
  {
    key: 'maintain',
    title: '维修工单',
    icon: 'i-material-symbols:home-repair-service',
    accent: THEME.color.orange.strong,
    glow: THEME.color.orange.glow
  },
  {
    key: 'unfilledCount',
    title: '运行未填写',
    icon: 'i-solar:clipboard-remove-linear',
    accent: THEME.color.orange.strong,
    glow: THEME.color.orange.glow
  },
  // {
  //   key: 'filledCount',
  //   title: '运行已填写',
  //   icon: 'i-solar:clipboard-check-linear',
  //   accent: THEME.color.green.strong,
  //   glow: THEME.color.green.glow
  // },
  {
    key: 'inspectttodo',
    title: '待巡检',
    icon: 'i-solar:map-point-search-linear',
    accent: THEME.color.orange.strong,
    glow: THEME.color.orange.glow
  },
  {
    key: 'bytodo',
    title: '待保养',
    icon: 'i-solar:shield-warning-linear',
    accent: THEME.color.orange.strong,
    glow: THEME.color.orange.glow
  }
  // {
  //   key: 'byfinished',
  //   title: '已保养',
  //   icon: 'i-solar:shield-check-linear',
  //   accent: THEME.color.green.strong,
  //   glow: THEME.color.green.glow
  // },
  // {
  //   key: 'inspecttfinished',
  //   title: '已巡检',
  //   icon: 'i-solar:check-circle-linear',
  //   accent: THEME.color.green.strong,
  //   glow: THEME.color.green.glow
  // },
]

function createDefaultCardState(): Record<CardKey, CardStateItem> {
  return {
    device: { value: 0, loading: true },
    maintain: { value: 0, loading: true },
    unfilledCount: { value: 0, loading: true },
    filledCount: { value: 0, loading: true },
    bytodo: { value: 0, loading: true },
    byfinished: { value: 0, loading: true },
    inspectttodo: { value: 0, loading: true },
    inspecttfinished: { value: 0, loading: true },
    zj: { value: 0, loading: true },
    xj: { value: 0, loading: true },
    utilizationRate: { value: 0, loading: true }
  }
}

const cardState = reactive<Record<CardKey, CardStateItem>>(createDefaultCardState())

const summaryCards = computed(() =>
  cardConfigs.map((card) => ({
    ...card,
    value: cardState[card.key].value,
    loading: cardState[card.key].loading
  }))
)

function toNumber(value: unknown) {
  const num = Number(value)
  return Number.isFinite(num) ? num : 0
}

function setCardValue(key: CardKey, value: unknown) {
  cardState[key].value = toNumber(value)
}

function setCardLoading(keys: CardKey[], loading: boolean) {
  keys.forEach((key) => {
    cardState[key].loading = loading
  })
}

function getCurrentYearCreateTime() {
  return [
    dayjs().startOf('year').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().endOf('year').format('YYYY-MM-DD HH:mm:ss')
  ]
}

async function loadDeviceCard() {
  const keys: CardKey[] = ['device']
  setCardLoading(keys, true)

  try {
    const res = await IotStatApi.getDeviceCount('ry')
    setCardValue('device', res?.total)
  } catch (error) {
    console.error('获取设备数失败:', error)
    setCardValue('device', 0)
  } finally {
    setCardLoading(keys, false)
  }
}

async function loadMaintainCard() {
  const keys: CardKey[] = ['maintain']
  setCardLoading(keys, true)

  try {
    const res = await IotStatApi.getMaintainCount('ry')
    setCardValue('maintain', res?.total)
  } catch (error) {
    console.error('获取维修工单失败:', error)
    setCardValue('maintain', 0)
  } finally {
    setCardLoading(keys, false)
  }
}

async function loadFillCards() {
  const keys: CardKey[] = ['unfilledCount', 'filledCount']
  setCardLoading(keys, true)

  const params = {
    startTime: dayjs().subtract(7, 'day').startOf('day').valueOf(),
    endTime: dayjs().endOf('day').valueOf(),
    createTime: [],
    deptId: 158,
    status: null
  }

  try {
    const res = await IotStatApi.getDeptStatistics(params)
    const totalStats = res?.totalList?.[0] ?? {}

    setCardValue('unfilledCount', totalStats.unfilledCount)
    setCardValue('filledCount', totalStats.filledCount)
  } catch (error) {
    console.error('获取运行填写数据失败:', error)
    setCardValue('unfilledCount', 0)
    setCardValue('filledCount', 0)
  } finally {
    setCardLoading(keys, false)
  }
}

async function loadMaintainStatusCards() {
  const keys: CardKey[] = ['bytodo', 'byfinished']
  setCardLoading(keys, true)

  try {
    const res = await IotStatApi.getMaintenanceStatus('ry')
    setCardValue('bytodo', res?.todo)
    setCardValue('byfinished', res?.finished)
  } catch (error) {
    console.error('获取保养状态失败:', error)
    setCardValue('bytodo', 0)
    setCardValue('byfinished', 0)
  } finally {
    setCardLoading(keys, false)
  }
}

async function loadInspectCards() {
  const keys: CardKey[] = ['inspectttodo', 'inspecttfinished']
  setCardLoading(keys, true)

  const params = {
    startTime: dayjs().subtract(7, 'day').startOf('day').valueOf(),
    endTime: dayjs().endOf('day').valueOf(),
    deptId: '',
    status: null
  }

  try {
    const res = await IotStatApi.getInspectStatuss(params, 'ry')
    setCardValue('inspectttodo', res?.todo)
    setCardValue('inspecttfinished', res?.finished)
  } catch (error) {
    console.error('获取巡检状态失败:', error)
    setCardValue('inspectttodo', 0)
    setCardValue('inspecttfinished', 0)
  } finally {
    setCardLoading(keys, false)
  }
}

async function loadZjXj() {
  const keys: CardKey[] = ['zj', 'xj']
  setCardLoading(keys, true)

  const params = {
    createTime: getCurrentYearCreateTime()
  }

  try {
    const res = await IotStatApi.getInspectZjxjCount(params)
    setCardValue('zj', res?.zj)
    setCardValue('xj', res?.xj)
  } catch (error) {
    console.error('获取巡检状态失败:', error)
    setCardValue('zj', 0)
    setCardValue('xj', 0)
  } finally {
    setCardLoading(keys, false)
  }
}

async function loadRate() {
  const keys: CardKey[] = ['utilizationRate']
  setCardLoading(keys, true)

  const params = {
    createTime: getCurrentYearCreateTime()
  }

  try {
    const res = await IotStatApi.getInspectRate(params)
    setCardValue('utilizationRate', (res * 100).toFixed(2))
  } catch (error) {
    console.error('获取累计设备利用率失败:', error)
    setCardValue('utilizationRate', 0)
  } finally {
    setCardLoading(keys, false)
  }
}

function loadAllCards() {
  loadDeviceCard()
  loadMaintainCard()
  loadFillCards()
  loadMaintainStatusCards()
  loadInspectCards()
  loadZjXj()
  loadRate()
}

onMounted(() => {
  loadAllCards()
})
</script>

<template>
  <div class="panel summary-panel w-full flex flex-col">
    <div class="panel-title summary-panel__title">
      <div class="icon-decorator">
        <span></span>
        <span></span>
      </div>
      运行概况
    </div>

    <div class="summary-panel__grid grid grid-cols-8 flex-1">
      <article
        v-for="card in summaryCards"
        :key="card.key"
        class="summary-card relative flex h-full overflow-hidden rounded-md items-center"
        :style="{
          '--card-accent': card.accent,
          '--card-glow': card.glow
        }">
        <div class="summary-card__shine"></div>

        <div class="summary-card__icon">
          <div :class="card.icon" class="summary-card__icon-glyph"></div>
        </div>

        <div class="summary-card__body">
          <div class="summary-card__label">{{ card.title }}</div>
          <div class="summary-card__value">
            <CountTo
              v-if="!card.loading"
              style="color: #1f5bb8"
              :start-val="0"
              :end-val="card.value"
              :duration="1200" />
            <span v-else class="summary-card__placeholder">--</span>
          </div>
        </div>

        <div class="summary-card__corner"></div>
      </article>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import url('@/styles/kb.scss');
</style>
