<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { useDebounceFn } from '@vueuse/core'
import MiniBarChart from '@/components/WorkOrderCompletionBar/index.vue'
import CountTo from '@/components/count-to1.vue'
import { IotReportApi } from '@/api/pms/report'
import { rangeShortcuts } from '@/utils/formatTime'
import download from '@/utils/download'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'

// 定义时间类型
type TimeType = 'year' | 'month' | 'day'

interface Query {
  deptId?: number
  createTime?: [string, string]
  type?: string
  pageNo: number
  pageSize: number
}

interface ChartDataItem {
  label: string
  num: number
}

interface StatItem {
  key: string
  title: string
  type: string
  icon: string
  total: number
  charts: ChartDataItem[]
  tb: number
  hb: number
}

// 选项配置数组
const timeOptions: { label: string; value: TimeType }[] = [
  { label: '年', value: 'year' },
  { label: '月', value: 'month' },
  { label: '日', value: 'day' }
]

const activeTimeType = ref<TimeType | undefined>('year')
const query = ref<Query>({
  pageNo: 1,
  pageSize: 10
})

const defaultStats: StatItem[] = [
  {
    key: 'yx',
    title: '运行记录',
    type: '运行记录',
    icon: 'i-material-symbols:list-alt-outline',
    total: 0,
    charts: [],
    tb: 0,
    hb: 0
  },
  {
    key: 'rb',
    title: '生产日报',
    type: '日报',
    icon: 'i-material-symbols:calendar-today-outline',
    total: 0,
    charts: [],
    tb: 0,
    hb: 0
  },
  {
    key: 'wx',
    title: '维修工单',
    type: '维修工单',
    icon: 'i-material-symbols:home-repair-service-outline',
    total: 0,
    charts: [],
    tb: 0,
    hb: 0
  },
  {
    key: 'by',
    title: '保养工单',
    type: '保养工单',
    icon: 'i-material-symbols:construction-rounded',
    total: 0,
    charts: [],
    tb: 0,
    hb: 0
  },
  {
    key: 'xj',
    title: '巡检工单',
    type: '巡检工单',
    icon: 'i-material-symbols:warning-outline',
    total: 0,
    charts: [],
    tb: 0,
    hb: 0
  }
]

const statList = ref<StatItem[]>(JSON.parse(JSON.stringify(defaultStats)))
const dataLoading = ref(false)
const list = ref<any[]>([])
const loading = ref(false)
const total = ref(0)

const handleTimeChange = (type: TimeType, init = false) => {
  activeTimeType.value = type

  const formatStr = 'YYYY-MM-DD HH:mm:ss'
  const endTime = dayjs().endOf('day').format(formatStr)
  let startTime = ''

  switch (type) {
    case 'year':
      startTime = dayjs().startOf('year').format(formatStr)
      break
    case 'month':
      startTime = dayjs().startOf('month').format(formatStr)
      break
    case 'day':
      startTime = dayjs().startOf('day').format(formatStr)
      break
  }

  query.value.createTime = [startTime, endTime]

  console.log(`切换为[${type}]:`, query.value.createTime)

  if (!init) loadData()
}

const labelMap = {
  wxoareject: '审批不通过',
  wxoa: '审批中',
  wxclose: '关闭',
  wxfinished: '完成',
  wxtx: '待填写',
  xjtodo: '待执行',
  xjignore: '忽略',
  xjfinished: '已执行',
  yx0: '待填写',
  yx1: '已完成',
  yx2: '填写中',
  yx3: '忽略',
  by1: '未保养',
  by2: '已保养',
  rb0: '未完成',
  rb1: '已完成'
}

// 模拟数据加载
const loadData = useDebounceFn(async function () {
  dataLoading.value = true

  const { pageNo, pageSize, type, ...other } = query.value

  const res = await IotReportApi.getOrderNumber({ ...other, timeType: activeTimeType.value })

  statList.value.forEach((item) => {
    const data = res[item.key] ?? {}

    item.total = data.total?.total ?? 0
    item.tb = data.total?.tb ?? 0
    item.hb = data.total?.hb ?? 0
    item.charts = data.status
      .filter((d) => d.num !== 0)
      .map((d) => ({
        label: labelMap[item.key + d.status],
        num: d.num
      }))
  })

  dataLoading.value = false
}, 500)

const loadList = useDebounceFn(async function () {
  loading.value = true

  const res = await IotReportApi.getOrderPage(query.value)

  // console.log('res :>> ', res)

  // const mockTableData = Array.from({ length: query.value.pageSize }).map((_, index) => {
  //   const types = ['维修工单', '保养工单', '巡检工单', '运行记录', '生产日报']
  //   const companies = ['第一工程公司', '第二工程公司', '总包单位']
  //   const statuses = ['已完成', '未完成', '处理中']

  //   return {
  //     id: index + 1,
  //     orderType: types[Math.floor(Math.random() * types.length)],
  //     createTime: dayjs()
  //       .subtract(Math.floor(Math.random() * 10), 'day')
  //       .format('YYYY-MM-DD HH:mm:ss'),
  //     companyName: companies[Math.floor(Math.random() * companies.length)],
  //     projectDept: `项目部-${Math.floor(Math.random() * 10) + 1}`,
  //     teamName: `作业队-${String.fromCharCode(65 + Math.floor(Math.random() * 5))}`,
  //     status: statuses[Math.floor(Math.random() * statuses.length)],
  //     deviceName: `设备-${Math.floor(Math.random() * 1000)}`
  //   }
  // })

  list.value = res.list
  total.value = res.total
  loading.value = false
}, 500)

function handleSizeChange(val: number) {
  query.value.pageSize = val
  query.value.pageNo = 1
  loadList()
}

function handleCurrentChange(val: number) {
  query.value.pageNo = val
  loadList()
}

function handleQuery(setPage = true) {
  if (setPage) {
    query.value.pageNo = 1
  }
  loadList()
  loadData()
}

onMounted(() => {
  handleTimeChange('year', true)
})

watch(
  [() => query.value.createTime, () => query.value.deptId],
  () => {
    handleQuery()
  },
  { immediate: true }
)

function selectType(type: string | undefined) {
  query.value.type = type
  query.value.pageNo = 1
  loadList()
}

function handleReset() {
  handleTimeChange('year')
  selectType(undefined)
}

const handleClear = () => {
  handleTimeChange('year')
}

const handleChange = () => {
  activeTimeType.value = undefined
}

const message = useMessage()

const exportLoading = ref(false)
const { ZmTable, ZmTableColumn } = useTableComponents<any>()

async function handleExport() {
  try {
    await message.exportConfirm()

    exportLoading.value = true
    const res = await IotReportApi.exportOrderPage(query.value)

    download.excel(res, '工单完成情况.xlsx')
  } finally {
    exportLoading.value = false
  }
}
</script>

<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[208px_1fr] gap-4 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]"
  >
    <DeptTreeSelect
      :top-id="156"
      :deptId="156"
      v-model="query.deptId"
      :init-select="false"
      :show-title="false"
      class="row-span-2"
    />
    <!-- <div class="p-4 bg-white dark:bg-[#1d1e1f] shadow rounded-lg row-span-2"> </div> -->
    <div class="flex flex-col gap-4 h-full">
      <div
        class="grid grid-cols-1 md:grid-cols-3 xl:grid-cols-5 gap-4 flex-1"
        v-loading="dataLoading"
      >
        <section
          v-for="item in statList"
          :key="item.key"
          class="bg-white dark:bg-[#1d1e1f] rounded-xl shadow flex justify-between items-stretch min-h-[140px] border border-gray-200 dark:border-gray-700/50 relative overflow-hidden group transition-colors duration-300 transition-transform hover:scale-105 duration-500"
          :class="{ 'scale-105': item.type === query.type }"
          @click="selectType(item.type)"
        >
          <div class="flex flex-col justify-between z-10 p-4 pb-2 pr-0 gap-1">
            <div class="text-gray-500 dark:text-gray-400 text-sm font-medium">
              {{ item.title }}
            </div>
            <div class="text-3xl font-bold tracking-tight text-gray-900! dark:text-white! mt-2">
              <count-to :start-val="0" :end-val="item.total" :duration="100">
                <span class="text-xs leading-9 text-[var(--el-text-color-regular)]">
                  暂无数据
                </span>
              </count-to>
            </div>
            <div class="flex flex-col gap-2 w-24">
              <div v-show="item.tb !== 0" class="flex items-center gap-1">
                <div
                  class="px-2 py-0.5 rounded text-xs font-bold flex items-center space-x-1"
                  :class="
                    item.tb >= 0
                      ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400'
                      : 'bg-rose-100 text-rose-600 dark:bg-rose-500/20 dark:text-rose-400'
                  "
                >
                  <div
                    :class="
                      item.tb >= 0
                        ? 'i-material-symbols:trending-up'
                        : 'i-material-symbols:trending-down'
                    "
                    class="text-sm"
                  ></div>
                  <span>{{ Math.abs(item.hb) }}%</span>
                </div>
                <span class="w-6 text-xs text-gray-500 dark:text-gray-400">同比</span>
              </div>
              <div v-show="item.hb !== 0" class="flex items-center gap-1">
                <div
                  class="px-2 py-0.5 rounded text-xs font-bold flex items-center space-x-1"
                  :class="
                    item.hb >= 0
                      ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400'
                      : 'bg-rose-100 text-rose-600 dark:bg-rose-500/20 dark:text-rose-400'
                  "
                >
                  <div
                    :class="
                      item.hb >= 0
                        ? 'i-material-symbols:trending-up'
                        : 'i-material-symbols:trending-down'
                    "
                    class="text-sm"
                  ></div>
                  <span>{{ Math.abs(item.hb) }}%</span>
                </div>
                <span class="min-w-8 text-xs text-gray-500 dark:text-gray-400">环比</span>
              </div>
            </div>
          </div>

          <!-- 右侧：ECharts图表 -->
          <div class="flex-1 h-full z-10 relative">
            <MiniBarChart :items="item.charts" :max="item.total" />
          </div>

          <!-- 背景装饰：颜色自适应 -->
          <div
            class="absolute -right-6 -bottom-6 opacity-[0.05] pointer-events-none transition-transform group-hover:scale-150 duration-500 text-black dark:text-white"
          >
            <div :class="item.icon" class="text-9xl"></div>
          </div>
        </section>
      </div>
      <div class="flex justify-between">
        <div class="flex gap-4">
          <el-date-picker
            size="default"
            v-model="query.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="rangeShortcuts"
            class="!w-220px"
            @clear="handleClear"
            @change="handleChange"
            :clearable="false"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          />
          <el-button-group size="default">
            <el-button
              v-for="item in timeOptions"
              :key="item.value"
              :type="activeTimeType === item.value ? 'primary' : ''"
              @click="handleTimeChange(item.value)"
            >
              {{ item.label }}
            </el-button>
          </el-button-group>
        </div>
        <div class="flex gap-2">
          <el-button size="default" @click="handleReset">重置</el-button>
          <!-- @click="handleExport"
            :loading="exportLoading" -->
          <el-button
            @click="handleExport"
            :loading="exportLoading"
            size="default"
            plain
            type="success"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </div>
      </div>
    </div>
    <div class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg p-4 flex flex-col">
      <div class="flex-1 relative">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <ZmTable
              :data="list"
              :loading="loading"
              :width="width"
              :height="height"
              :max-height="height"
              show-border
            >
              <ZmTableColumn
                label="序号"
                type="index"
                :width="70"
                fixed="left"
                hide-in-column-settings
              />
              <ZmTableColumn label="工单类别" prop="type" min-width="110" />
              <ZmTableColumn label="生成日期" prop="createTime" min-width="140">
                <template #default="{ row }">
                  {{ row.createTime ? row.createTime.split(' ')[0] : '' }}
                </template>
              </ZmTableColumn>
              <ZmTableColumn label="公司" prop="company" min-width="120" />
              <ZmTableColumn label="项目部" prop="project" min-width="160" />
              <ZmTableColumn label="队伍" prop="deptName" min-width="140" />
              <ZmTableColumn label="状态" prop="status" min-width="100" />
              <ZmTableColumn label="设备" prop="device" min-width="180" action />
            </ZmTable>
          </template>
        </el-auto-resizer>
      </div>
      <div class="h-10 mt-4 flex items-center justify-end">
        <el-pagination
          size="default"
          v-show="total > 0"
          v-model:current-page="query.pageNo"
          v-model:page-size="query.pageSize"
          :background="true"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped></style>
