<template>
  <el-row :gutter="20">
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :xs="24" :span="isLeftContentCollapsed ? 24 : 20">
      <!-- 统计卡片 -->
      <el-row :gutter="18" class="mb-4">
        <el-col :span="4">
          <div style="background-color: transparent; border-radius: 10px; cursor: pointer">
            <div
              class="stat-card bg-blue-gradient"
              :class="{ 'stat-card-selected': statusList.all }"
              @click="
                () => {
                  queryParams.pageNo = 1
                  getList('all')
                }
              ">
              <Icon icon="ep:histogram" class="text-[#409eff]" :size="40" />
              <div class="card-title">故障总数</div>
              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#409eff]!"
                  :end-val="
                    statusCount.finished +
                      statusCount.trans +
                      statusCount.reporting +
                      statusCount.close || 0
                  "
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div
              class="stat-card bg-green-gradient"
              :class="{ 'stat-card-selected': statusList.finished }"
              @click="
                () => {
                  queryParams.pageNo = 1
                  getList('finished')
                }
              ">
              <Icon icon="ep:finished" class="text-[#239443]" :size="40" />
              <div class="card-title">维修完成</div>
              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#239443]!"
                  :end-val="statusCount.finished || 0"
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div
              class="stat-card bg-orange-gradient"
              :class="{ 'stat-card-selected': statusList.trans }"
              @click="
                () => {
                  queryParams.pageNo = 1
                  getList('trans')
                }
              ">
              <Icon icon="ep:more-filled" class="text-[#e8a748]" :size="40" />
              <div class="card-title">转工单</div>
              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#e8a748]!"
                  :end-val="statusCount.trans || 0"
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div
              class="stat-card bg-blue-gradient2"
              :class="{ 'stat-card-selected': statusList.reporting }"
              @click="
                () => {
                  queryParams.pageNo = 1
                  getList('reporting')
                }
              ">
              <Icon icon="ep:promotion" class="text-[#0881d9]" :size="40" />
              <div class="card-title">上报中</div>
              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#0881d9]!"
                  :end-val="statusCount.reporting || 0"
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div
              class="stat-card bg-red-gradient"
              :class="{ 'stat-card-selected': statusList.close }"
              @click="
                () => {
                  queryParams.pageNo = 1
                  getList('close')
                }
              ">
              <Icon icon="ep:close" class="text-[#f56d6d]" :size="40" />
              <div class="card-title">关闭</div>
              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#f56d6d]!"
                  :end-val="statusCount.close || 0"
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div class="bg-[#fff] p-2 py-4 rounded-lg">
            <el-form ref="queryFormRef" :model="queryParams">
              <!-- <el-form-item label="上报时间" prop="createTime">
                <el-date-picker
                  v-model="queryParams.createTime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="daterange"
                  :start-placeholder="t('operationFill.start')"
                  :end-placeholder="t('operationFill.end')"
                  :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                  class="!w-220px"
                />
              </el-form-item> -->

              <el-form-item>
                <el-button @click="handleQuery"
                  ><Icon icon="ep:search" class="mr-3px" />{{
                    t('operationFill.search')
                  }}</el-button
                >
              </el-form-item>

              <el-form-item>
                <el-button type="success" plain @click="handleExport" :loading="exportLoading"
                  ><Icon icon="ep:download" class="mr-3px" /> 导出</el-button
                >
              </el-form-item>

              <el-form-item>
                <el-button @click="resetQuery"
                  ><Icon icon="ep:refresh" class="mr-3px" />
                  {{ t('operationFill.reset') }}</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-radio-group v-model="dateType" size="default" fill="#409eff">
            <el-radio-button label="年" value="year" />
            <el-radio-button label="月" value="month" />
            <el-radio-button label="日" value="day" />
          </el-radio-group>
        </el-col>
      </el-row>

      <!-- 列表 -->
      <ContentWrap style="border: 0; margin-top: 10px">
        <zm-table
          :loading="loading"
          :data="list"
          height="48vh"
          :stripe="true"
          :show-overflow-tooltip="true">
          <zm-table-column :label="t('fault.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </zm-table-column>

          <zm-table-column :label="t('fault.faultTitle')" prop="failureName" align="center" />
          <zm-table-column :label="t('iotMaintain.deviceCode')" align="center" prop="deviceCode" />
          <zm-table-column :label="t('fault.deviceName')" align="center" prop="deviceName" />
          <zm-table-column :label="t('fault.status')" align="center" prop="status" min-width="110">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.PMS_FAILURE_STATUS" :value="scope.row.status" />
            </template>
          </zm-table-column>
          <zm-table-column
            :label="t('faultForm.failureType')"
            align="center"
            prop="failureType"
            min-width="110">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.FAILURE_TYPE" :value="scope.row.failureType" />
            </template>
          </zm-table-column>

          <zm-table-column label="故障系统" align="center" prop="failureSystem" />

          <zm-table-column label="故障频次" align="center" prop="failureNum" />
          <zm-table-column
            :label="t('fault.approvalStatus')"
            align="center"
            prop="auditStatus"
            min-width="130">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.CRM_AUDIT_STATUS" :value="scope.row.auditStatus" />
            </template>
          </zm-table-column>
          <zm-table-column :label="t('fault.solve')" align="center" prop="ifDeal">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.ifDeal" />
            </template>
          </zm-table-column>
          <zm-table-column
            :label="t('fault.failureTime')"
            align="center"
            prop="failureTime"
            :formatter="dateFormatter"
            min-width="180px" />
          <zm-table-column :label="t('fault.solveTime')" align="center" prop="dealHour">
            <template #default="scope">
              {{ scope.row.dealHour && scope.row.dealHour > 0 ? scope.row.dealHour + 'H' : '' }}
            </template>
          </zm-table-column>
          <zm-table-column
            label="上报时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            min-width="180px"
            action />
        </zm-table>

        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getAllList" />
      </ContentWrap>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { IotInspectOrderApi, IotInspectOrderVO } from '@/api/pms/inspect/order'
import { watch } from 'vue'

import { DICT_TYPE } from '@/utils/dict'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { dateFormatter } from '@/utils/formatTime'

const message = useMessage() // 消息弹窗
import download from '@/utils/download'

const { params } = useRoute()
/** 巡检工单 列表 */
defineOptions({ name: 'IotInspectOrder' })

const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const list = ref<IotInspectOrderVO[]>([]) // 列表的数据
const deptId = params.deptId
const createTime = params.createTime
const total = ref(0) // 列表的总页数
let isLeftContentCollapsed = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: undefined,
  createTime: [],
  deptId: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 部门树节点点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.status = undefined
  queryParams.deptId = row.id

  const currentStatus = Object.keys(statusList.value).find((key) => statusList.value[key])
  queryParams.pageNo = 1
  await getList(currentStatus || 'all', false) // 不重置状态

  await getCounts()
}

const statusList = ref({
  all: false,
  reporting: false,
  finished: false,
  trans: false,
  close: false
})

let exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true

    const data = await IotInspectOrderApi.exportFaultReport(queryParams)
    download.excel(data, '故障上报报表.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 查询列表 */
const getList = async (status: string = '', shouldResetStatus = true) => {
  if (shouldResetStatus) {
    Object.keys(statusList.value).forEach((key) => {
      statusList.value[key] = false
    })
    statusList.value[status] = true
  }
  loading.value = true
  try {
    if (status === 'all') {
      queryParams.status = undefined
    } else if (status === 'trans') {
      queryParams.status = 'trans'
    } else if (status === 'finished') {
      queryParams.status = 'finished'
    } else if (status === 'reporting') {
      queryParams.status = 'reporting'
    } else if (status === 'close') {
      queryParams.status = 'close'
    }
    const data = await IotInspectOrderApi.getFaultReportList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const getAllList = async () => {
  // 获取当前选中的状态
  const currentStatus = Object.keys(statusList.value).find((key) => statusList.value[key])
  await getList(currentStatus || '', false) // 不重置状态
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  const currentStatus = Object.keys(statusList.value).find((key) => statusList.value[key])
  getList(currentStatus || '', false)
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

let statusCount = ref({
  finished: 0,
  trans: 0,
  reporting: 0,
  close: 0
})
async function getCounts() {
  const res = await IotInspectOrderApi.getFaultReportStatus({
    deptId: queryParams.deptId,
    createTime: queryParams.createTime
  })

  statusCount.value = res

  console.log('statusCount', statusCount.value)
}

/** 初始化 **/
onMounted(() => {
  getCounts()

  if (deptId != null) {
    queryParams.deptId = deptId
  }

  if (createTime) {
    queryParams.createTime = createTime
  }
  getList()
})

let dateType = ref('year')
watch(
  dateType,
  () => {
    const now = new Date()
    let startTime: Date
    let endTime: Date

    switch (dateType.value) {
      case 'year':
        // 当年：1月1日 00:00:00 到 12月31日 23:59:59
        startTime = new Date(now.getFullYear(), 0, 1, 0, 0, 0, 0)
        endTime = new Date(now.getFullYear(), 11, 31, 23, 59, 59, 999)
        break

      case 'month':
        // 当月：月初 00:00:00 到 月末 23:59:59
        startTime = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0, 0)
        // 下个月的第0天就是当月的最后一天
        endTime = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999)
        break

      case 'day':
        // 当日：当天 00:00:00 到 23:59:59
        const year = now.getFullYear()
        const month = now.getMonth()
        const date = now.getDate()
        startTime = new Date(year, month, date, 0, 0, 0, 0)
        endTime = new Date(year, month, date, 23, 59, 59, 999)
        break

      default:
        startTime = new Date(now.getFullYear(), 0, 1, 0, 0, 0, 0)
        endTime = new Date(now.getFullYear(), 11, 31, 23, 59, 59, 999)
    }

    // 使用本地时间格式化函数，避免时区转换问题
    const formatLocalDateTime = (date: Date): string => {
      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}`
    }
    // 设置查询参数 - 使用本地时间格式化
    queryParams.createTime = [formatLocalDateTime(startTime), formatLocalDateTime(endTime)]

    const currentStatus = Object.keys(statusList.value).find((key) => statusList.value[key])
    queryParams.pageNo = 1
    getList(currentStatus || 'all', false) // 不重置状态
  },
  {
    immediate: true
  }
)
</script>
<style scoped>
/* 添加异常行高亮样式 */
:deep(.exception-row) {
  background-color: #f29a90 !important;
}

:deep(.exception-row:hover) {
  background-color: #fff0e0 !important;
}

.reason-confirm-container {
  margin: 20px;
}

/* 调整文本框样式 */
:deep(.el-textarea__inner) {
  font-size: 14px;
}

/* 调整表单项间距 */
:deep(.el-form-item) {
  margin-bottom: 15px;
}

.stat-card {
  padding: 14px 16px;
  border-radius: 10px;
  text-align: center;
  font-size: 14px;
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease,
    border-color 0.3s ease;
  height: 170px;
  cursor: pointer;
  overflow: hidden; /* 防止闪光效果溢出 */
  background: linear-gradient(180deg, #ffffff 0%, #f7faff 100%);

  box-shadow: 0 4px 12px rgb(31 91 184 / 8%);
  color: #6b7280;
}

.card-title {
  margin: 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #6b7280;
  line-height: 1.4;
}

.card-value {
  margin: 8px 0;
  font-size: 28px;
  font-weight: 700;
  line-height: 1;
  color: #1f5bb8;
}

.card-trend {
  font-size: 12px;
  opacity: 0.9;
}

/* 毛玻璃渐变背景 —— 不再使用 background-image */
.bg-blue-gradient {
  background: linear-gradient(180deg, #ffffff 0%, #f7faff 100%);
  border-color: #e4ecf7;
}
.bg-blue-gradient2 {
  background: linear-gradient(180deg, #ffffff 0%, #a5d1ff 100%);
  border-color: #e4ecf7;
}

.bg-blue-gradient .card-value {
  color: #2563eb;
}

.bg-green-gradient {
  background: linear-gradient(180deg, #f7fcf8 0%, #edf8f1 100%);
  border-color: #d6efdc;
}

.bg-green-gradient .card-value {
  color: #16a34a;
}

.bg-orange-gradient {
  background: linear-gradient(180deg, #fff8ef 0%, #ffeed9 100%);
  border-color: #ffd7a1;
}

.bg-orange-gradient .card-value {
  color: #d97706;
}

.bg-red-gradient {
  background: linear-gradient(180deg, #fff4f4 0%, #ffe8e8 100%);
  border-color: #ffcfcf;
}

.bg-red-gradient .card-value {
  color: #de3b3b;
}

/* 确保内容不溢出 */
:deep(.el-row) {
  flex-wrap: wrap;
}

.text-truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

::v-deep .el-table__header-wrapper {
  position: sticky !important;
  width: 100%;
  top: 0px;
  z-index: 2000;
}

.stat-card-selected {
  position: relative;
  transform: translateY(-2px);
  transition: all 0.2s;
  box-shadow: 0 10px 20px rgb(31 91 184 / 12%);
  border-color: #bfd5ee;
}
</style>
