<template>
  <el-row :gutter="20">
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1" style="border: 0">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 统计卡片 -->
      <el-row :gutter="18" class="mb-4">
        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div class="stat-card bg-blue-gradient">
              <Icon icon="ep:histogram" :size="40" />
              <div class="card-title">工单数量</div>
              <div class="card-value pt-5">{{
                deviceCount.finished + deviceCount.ignore + deviceCount.todo
              }}</div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div class="stat-card bg-green-gradient">
              <Icon icon="ep:finished" :size="40" />
              <div class="card-title">完成数量</div>
              <div class="card-value pt-5">{{ deviceCount.finished }}</div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div class="stat-card bg-orange-gradient">
              <Icon icon="ep:more-filled" :size="40" />
              <div class="card-title">未完成数量</div>
              <div class="card-value pt-5">{{ deviceCount.todo }}</div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div class="stat-card bg-green-gradient">
              <Icon icon="ep:hide" :size="40" />
              <div class="card-title">已忽略</div>
              <div class="card-value pt-5">{{ deviceCount.ignore }}</div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div class="stat-card bg-red-gradient">
              <Icon icon="ep:bell" :size="40" />
              <div class="card-title">异常设备数量</div>
              <div class="card-value pt-5">{{ exceptions?.exceptionNum || 0 }}</div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div style="background-color: #fff; border-radius: 10px">
            <div class="stat-card bg-warn-gradient">
              <Icon icon="ep:info-filled" :size="40" />
              <div class="card-title">异常点数量</div>
              <div class="card-value pt-5">{{ exceptionPoint.value }}</div>
            </div>
          </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">
        <el-table
          v-loading="loading"
          :row-class-name="tableRowClassName"
          :data="list"
          :show-overflow-tooltip="true"
          @row-click="handleRowClick"
        >
          <el-table-column :label="t('iotDevice.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            :label="t('bomList.name')"
            align="center"
            prop="inspectOrderTitle"
            min-width="300"
          />

          <el-table-column label="项目" align="center" prop="project" min-width="110" />

          <el-table-column
            :label="t('route.orderType')"
            align="center"
            prop="type"
            min-width="90"
          />
          <el-table-column
            :label="t('operationFill.status')"
            align="center"
            prop="status"
            min-width="95"
          >
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.PMS_INSPECT_ORDER_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>

          <el-table-column label="设备明细" align="center" prop="deviceInfo" min-width="110" />

          <el-table-column
            :label="t('iotMaintain.PersonInCharge')"
            align="center"
            prop="chargeName"
            min-width="110"
          />

          <!-- 
          <el-table-column
            :label="t('inspect.generateTime')"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            min-width="180px"
          />
          <el-table-column
            :label="t('inspect.executeTime')"
            align="center"
            prop="executeDate"
            :formatter="dateFormatter"
            min-width="180px"
          /> -->
          <el-table-column
            :label="t('iotMaintain.operation')"
            align="center"
            min-width="160px"
            fixed="right"
          >
            <template #default="scope">
              <el-button link type="primary" @click="openForm(scope.row.id)">
                异常巡检点
              </el-button>
            </template>
          </el-table-column>
        </el-table>

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

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { IotInspectOrderApi, IotInspectOrderVO } from '@/api/pms/inspect/order'
import { DICT_TYPE } from '@/utils/dict'
import DeptTree from '@/views/system/user/DeptTree.vue'
import { watch } from 'vue'

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

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const list = ref<IotInspectOrderVO[]>([]) // 列表的数据
const status = params.status
const deptId = params.deptId
const createTime = params.createTime
const total = ref(0) // 列表的总页数
const dialogVisible = ref(false)
let dateType = ref('year')
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  inspectOrderTitle: undefined,
  inspectOrderCode: undefined,
  status: undefined,
  remark: undefined,
  createTime: [],
  deptId: undefined,
  deviceIds: undefined
})
const queryFormRef = ref() // 搜索的表单

let exceptions = ref(null)
let exceptionPoint = ref([])
let deviceCount = ref([])

const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
  await getCounts()
}

const tableRowClassName = ({ row }) => {
  if (row.exceptionCount > 0) {
    return 'exception-row'
  }
  return ''
}

const handleRowClick = (row, column: any, event: Event) => {
  // 只有当行有异常时才允许点击跳转
  if (row.exceptionCount > 0) {
    // 阻止事件冒泡，避免与按钮点击冲突
    event.stopPropagation()

    push({
      name: 'IotInspectItemStat',
      query: { orderName: row.inspectOrderTitle, ifNormal: false }
    })
  }
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotInspectOrderApi.getIotInspectOrderList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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)]

    // 重新获取数据
    getList()
    getCounts()
  },
  {
    immediate: true
  }
)

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

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

const reasonFormRef = ref(null)
const form = reactive({
  id: undefined,
  reason: ''
})

// 重置表单
const resetForm = () => {
  reasonFormRef.value?.resetFields()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (id?: number) => {
  push({ name: 'InspectOrderDetail', params: { id } })
}

async function getCounts() {
  exceptions.value = await IotInspectOrderApi.getIotInspectOrderExceptionDeviceCount({
    deptId: queryParams.deptId,
    createTime: queryParams.createTime
  })

  exceptionPoint.value = await IotInspectOrderApi.getIotInspectOrderExceptionPointCount({
    deptId: queryParams.deptId,
    createTime: queryParams.createTime
  })

  deviceCount.value = await IotInspectOrderApi.getInspectItemStatus({
    deptId: queryParams.deptId,
    createTime: queryParams.createTime
  })
}

/** 初始化 **/
onMounted(() => {
  getCounts()
  if (params.status) {
    queryParams.status = params.status
  }
  if (deptId != null) {
    queryParams.deptId = deptId
  }

  if (createTime) {
    queryParams.createTime = createTime
  }
  getList()
})
</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: 20px;
  border-radius: 10px;
  color: white;
  text-align: center;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease;
  backdrop-filter: blur(12px);
  height: 200px;
}
.stat-card::before {
  position: absolute;
  filter: blur(20px);
  z-index: -1;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.card-title {
  margin: 8px 0;
  font-size: 16px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  margin: 8px 0;
}

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

/* 毛玻璃渐变背景 —— 不再使用 background-image */
.bg-blue-gradient {
  background: linear-gradient(135deg, rgba(77, 147, 255, 0.5), rgba(75, 132, 254));
}

.bg-green-gradient {
  background: linear-gradient(135deg, rgba(101, 226, 136, 0.1), #52d7a2);
  background-color: rgba(76, 175, 80, 0.1);
}

.bg-orange-gradient {
  background: linear-gradient(135deg, rgba(152, 82, 4, 0.5), rgba(255, 152, 4, 0.6));
}

.bg-red-gradient {
  background: linear-gradient(135deg, rgba(232, 65, 51), rgba(252, 242, 236));
}

.bg-warn-gradient {
  background: linear-gradient(135deg, rgba(255, 201, 103), rgba(243, 162, 152));
}

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

.text-truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
