<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="border-radius: 10px">
            <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-[#2563eb]!" :size="40" />
              <div class="card-title text-[#6b7280]!">工单数量</div>

              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#2563eb]!"
                  :end-val="deviceCount.finished + deviceCount.ignore + deviceCount.todo || 0"
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>

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

        <el-col :span="4">
          <div
            style="border-radius: 10px"
            @click="
              () => {
                queryParams.pageNo = 1
                getList('todo')
              }
            "
            :class="{ 'stat-card-selected': statusList.todo }">
            <div class="stat-card bg-orange-gradient">
              <Icon icon="ep:more-filled" class="text-[#fc9a03]!" :size="40" />
              <div class="card-title">未完成数量</div>
              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#fc9a03]!"
                  :end-val="deviceCount.todo || 0"
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div
            style="border-radius: 10px"
            @click="
              () => {
                queryParams.pageNo = 1
                getList('ignore')
              }
            "
            :class="{ 'stat-card-selected': statusList.ignore }">
            <div class="stat-card bg-green-gradient">
              <Icon icon="ep:hide" :size="40" />
              <div class="card-title">已忽略</div>
              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#6b7280]!"
                  :end-val="deviceCount.ignore || 0"
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div
            style="border-radius: 10px"
            @click="
              () => {
                queryParams.pageNo = 1
                getExceptionList()
              }
            ">
            <div
              class="stat-card bg-red-gradient"
              :class="{ 'stat-card-selected': statusList.exception }">
              <Icon icon="ep:bell" class="text-[#d45336]!" :size="40" />
              <div class="card-title">异常设备数量</div>
              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#d45336]!"
                  :end-val="exceptions?.exceptionNum || 0"
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="4">
          <div
            style="border-radius: 10px"
            @click="
              () => {
                queryParams.pageNo = 1
                getExceptionPoint()
              }
            ">
            <div
              class="stat-card bg-warn-gradient"
              :class="{ 'stat-card-selected': statusList.exceptionPoint }">
              <Icon icon="ep:info-filled" class="text-[#e6a23c]!" :size="40" />
              <div class="card-title">异常点数量</div>
              <div class="card-value pt-5">
                <CountTo
                  class="text-3xl text-[#e6a23c]!"
                  :end-val="exceptionPoint.value || 0"
                  :decimals="0" />
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="22">
          <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-col :span="2">
          <el-button type="success" plain @click="handleExport" :loading="exportLoading"
            ><Icon icon="ep:download" class="mr-3px" /> 导出</el-button
          >
        </el-col>
      </el-row>

      <!-- 列表 -->
      <ContentWrap style="border: 0; margin-top: 10px">
        <!-- 异常设备 -->
        <zm-table
          v-if="isException"
          :loading="loading"
          :data="list3"
          :stripe="true"
          :show-overflow-tooltip="true">
          <zm-table-column :label="t('iotDevice.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </zm-table-column>

          <zm-table-column label="设备编码" align="center" prop="deviceCode" />
          <zm-table-column :label="t('monitor.deviceName')" align="center">
            <template #default="{ row }">
              <el-link type="primary" :underline="false" @click="goDetail(row.deviceCode)">{{
                row.deviceName
              }}</el-link>
            </template>
          </zm-table-column>
          <zm-table-column label="工单数量" align="center" prop="orderCount" />
        </zm-table>

        <!-- 巡检异常点 -->
        <zm-table
          v-else-if="isExceptionPoint"
          :loading="loading"
          :data="list2"
          :stripe="true"
          :show-overflow-tooltip="true">
          <zm-table-column :label="t('iotDevice.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </zm-table-column>
          <zm-table-column :label="t('bomList.name')" align="center" prop="orderName" />
          <zm-table-column :label="t('iotDevice.code')" align="center" prop="deviceCode" />
          <zm-table-column :label="t('monitor.deviceName')" align="center" prop="deviceName" />
          <zm-table-column :label="t('operationFill.duty')" align="center" prop="charge" />
          <zm-table-column :label="t('inspect.InspectionItems')" align="center" prop="item" />
          <zm-table-column :label="t('inspect.isException')" align="center" prop="ifNormal">
            <template #default="scope">
              <span v-if="scope.row.ifNormal" style="color: dodgerblue">正常</span>
              <span v-else-if="scope.row.ifNormal === null" style="color: #101010">待填写</span>
              <span v-else-if="!scope.row.ifNormal" style="color: orangered">异常</span>
            </template>
          </zm-table-column>
          <zm-table-column
            :label="t('inspect.exceptionDes')"
            align="center"
            prop="description"
            action />
        </zm-table>

        <zm-table
          v-else
          :loading="loading"
          :row-class-name="tableRowClassName"
          :data="list"
          :show-overflow-tooltip="true"
          @row-click="handleRowClick"
          height="48vh">
          <zm-table-column :label="t('iotDevice.serial')" width="70" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </zm-table-column>
          <zm-table-column :label="t('bomList.name')" align="center" prop="inspectOrderTitle" />

          <zm-table-column label="公司" align="center" prop="company" />
          <zm-table-column label="项目" align="center" prop="project" />

          <zm-table-column
            :label="t('route.orderType')"
            align="center"
            prop="type"
            min-width="90" />
          <zm-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>
          </zm-table-column>

          <zm-table-column v-if="statusList.ignore" label="忽略原因" align="center" prop="reason" />

          <zm-table-column label="设备明细" align="center" prop="deviceInfo" />

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

          <zm-table-column
            :label="t('iotMaintain.operation')"
            align="center"
            min-width="150px"
            fixed="right"
            action>
            <template #default="scope">
              <el-button link type="primary" @click="openForm(scope.row.id)">
                异常巡检点
              </el-button>
            </template>
          </zm-table-column>
        </zm-table>

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

  <el-drawer v-model="drawerVisible" title="异常点数量" direction="rtl" size="50%">
    <zm-table :loading="loading" :data="deviceDetail" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column :label="t('iotDevice.serial')" width="70" align="center">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <zm-table-column :label="t('bomList.name')" align="center" prop="orderName" />
      <zm-table-column :label="t('iotDevice.code')" align="center" prop="deviceCode" />
      <zm-table-column :label="t('monitor.deviceName')" align="center" prop="deviceName" />
      <zm-table-column :label="t('operationFill.duty')" align="center" prop="charge" />
      <zm-table-column :label="t('inspect.InspectionItems')" align="center" prop="item" />
      <zm-table-column :label="t('inspect.isException')" align="center" prop="ifNormal">
        <template #default="scope">
          <span v-if="scope.row.ifNormal" style="color: dodgerblue">正常</span>
          <span v-else-if="scope.row.ifNormal === null" style="color: #101010">待填写</span>
          <span v-else-if="!scope.row.ifNormal" style="color: orangered">异常</span>
        </template>
      </zm-table-column>
      <zm-table-column
        :label="t('inspect.exceptionDes')"
        align="center"
        prop="description"
        action />
    </zm-table>

    <Pagination
      :total="detailTotal"
      v-model:page="detailQueryParams.pageNo"
      v-model:limit="detailQueryParams.pageSize"
      @pagination="goDetail(detailQueryParams.deviceCode)" />
  </el-drawer>
</template>

<script setup lang="ts">
import { IotInspectOrderApi, IotInspectOrderVO } from '@/api/pms/inspect/order'
import { DICT_TYPE } from '@/utils/dict'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { IotInspectItemVO, IotInspectOrderDetailApi } from '@/api/pms/inspect/order/detail'
const message = useMessage() // 消息弹窗
import { watch } from 'vue'
import download from '@/utils/download'
let isLeftContentCollapsed = ref(false)
const { push } = useRouter()
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) // 列表的总页数

const statusList = ref({
  all: false,
  exception: false,
  exceptionPoint: false,
  finished: false,
  ignore: false,
  todo: 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
})

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

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

const handleDeptNodeClick = async (row) => {
  queryParams.status = undefined
  queryParams.deptId = row.id

  // 保持当前表格视图和状态
  if (isExceptionPoint.value) {
    // 当前显示异常点表
    queryParams.pageNo = 1
    await getPointList()
  } else if (isException.value) {
    // 当前显示异常设备表
    queryParams.pageNo = 1
    await getExceptionList()
  } else {
    // 当前显示普通工单表
    const currentStatus = Object.keys(statusList.value).find((key) => statusList.value[key])
    queryParams.pageNo = 1
    await getList(currentStatus || 'all', false) // 不重置状态
  }

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

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

    if (isException.value) {
      const data = await IotInspectOrderApi.exportExceptionDeviceInspectReport(queryParams)
      download.excel(data, '异常设备报表.xlsx')
    } else if (isExceptionPoint.value) {
      const data = await IotInspectOrderApi.exportExceptionPointInspectReport(queryParams)
      download.excel(data, '异常点报表.xlsx')
    } else {
      const data = await IotInspectOrderApi.exportInspectReport(queryParams)
      download.excel(data, '巡检报表.xlsx')
    }
    // const data = await IotInspectOrderApi.exportInspectReport(queryParams)
    // download.excel(data, '巡检报表.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

let isExceptionPoint = ref(false)
const list2 = ref<IotInspectItemVO[]>([]) // 列表的数据

const getPointList = async () => {
  isException.value = false
  isExceptionPoint.value = true

  loading.value = true
  try {
    queryParams.status = '异常'
    const data = await IotInspectOrderDetailApi.getIotInspectItemStatusPage(queryParams)
    list2.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const getExceptionPoint = () => {
  Object.keys(statusList.value).forEach((key) => {
    statusList.value[key] = false
  })
  statusList.value['exceptionPoint'] = true

  isExceptionPoint.value = true
  getPointList()
}

let isException = ref(false)
const list3 = ref([])
const getExceptionList = async () => {
  isException.value = true
  isExceptionPoint.value = false

  Object.keys(statusList.value).forEach((key) => {
    statusList.value[key] = false
  })
  statusList.value['exception'] = true

  loading.value = true
  try {
    queryParams.status = undefined
    const data = await IotInspectOrderApi.getExceptionDeviceList(queryParams)
    list3.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const getList = async (status: string = '', shouldResetStatus = true) => {
  isExceptionPoint.value = false
  isException.value = false

  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 === 'todo') {
      queryParams.status = 'todo'
    } else if (status === 'finished') {
      queryParams.status = 'finished'
    } else if (status === 'ignore') {
      queryParams.status = 'ignore'
    }
    const data = await IotInspectOrderApi.getIotInspectOrderList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 修改 getAllList 函数
const getAllList = async () => {
  if (isExceptionPoint.value) {
    await getPointList()
  } else if (isException.value) {
    await getExceptionList()
  } else {
    // 获取当前选中的状态
    const currentStatus = Object.keys(statusList.value).find((key) => statusList.value[key])
    await getList(currentStatus || '', 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)]

    console.log('查询参数>>>>>>>>>>>>>>>>>', typeof queryParams.createTime[0])

    // 重新获取数据，保持当前状态和表格视图
    if (isExceptionPoint.value) {
      // 当前显示异常点表
      queryParams.pageNo = 1
      getPointList()
    } else if (isException.value) {
      // 当前显示异常设备表
      queryParams.pageNo = 1
      getExceptionList()
    } else {
      // 当前显示普通工单表
      const currentStatus = Object.keys(statusList.value).find((key) => statusList.value[key])
      queryParams.pageNo = 1
      getList(currentStatus || 'all', false) // 不重置状态
    }
    getCounts()
  },
  {
    immediate: true
  }
)
const openForm = (id?: number) => {
  push({ name: 'InspectOrderDetail', params: { id } })
}

let drawerVisible = ref(false)
const deviceDetail = ref([])
let detailTotal = ref(0)
const detailQueryParams = ref({
  pageNo: 1,
  pageSize: 20,
  status: '异常',
  deviceCode: '',
  createTime: []
})
const goDetail = async (code: string) => {
  // 抽屉打开设备详情
  drawerVisible.value = true
  detailQueryParams.value.deviceCode = code
  detailQueryParams.value.createTime = queryParams.createTime

  const data = await IotInspectOrderDetailApi.getIotInspectItemStatusPage(detailQueryParams.value)
  deviceDetail.value = data.list
  detailTotal.value = data.total
}

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: 14px 16px;
  background: linear-gradient(180deg, #ffffff 0%, #f7faff 100%);
  /* border: 1px solid #e4ecf7; */
  border-radius: 10px;
  box-shadow: 0 4px 12px rgb(31 91 184 / 8%);
  text-align: center;
  font-size: 14px;
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease,
    border-color 0.3s ease;
  color: #6b7280;
  height: 170px;
  cursor: pointer;
  overflow: hidden;
}

.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;
}

.bg-blue-gradient {
  background: linear-gradient(180deg, #ffffff 0%, #f7faff 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;
}

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

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

/* ???????????*/
: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>
