<template style="background-color: #edf4ff">
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :xs="24" :span="isLeftContentCollapsed ? 24 : 20">
      <!-- 统计卡片 -->
      <el-row :gutter="21" class="mb-4">
        <el-col :span="9">
          <div class="flex gap-2 bg-white p-5 rounded-lg">
            <div class="stat-card bg-blue-gradient w-[40%]">
              <Icon icon="ep:histogram" :size="40" />
              <div class="card-title">设备总数</div>
              <div class="card-value pt-5">{{ devicesCount }}</div>
            </div>

            <div class="stat-card bg-green-gradient w-[60%]">
              <div class="flex flex-col items-center h-full">
                <!-- <Icon icon="ep:odometer" :size="40" class="mb-2" /> -->
                <div class="card-title mb-2">设备状态</div>
                <div class="flex-1 w-full" style="height: calc(100% - 60px)">
                  <Echart
                    v-if="statusChartOption.series && statusChartOption.series[0].data.length > 0"
                    :options="statusChartOption"
                    :height="160"
                  />
                  <div v-else class="flex items-center justify-center h-full text-gray-500">
                    暂无数据
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="10">
          <div style="background-color: #fff" class="rounded-lg">
            <Echart :options="myoption" :height="270" />
          </div>
        </el-col>

        <el-col :span="5">
          <div class="bg-[#fff] p-2 py-5 h-[270px] rounded-lg">
            <el-form ref="queryFormRef" :model="queryParams">
              <el-form-item label="设备编码" prop="deviceCode">
                <el-input
                  style="height: 30px"
                  @keyup.enter="handleQuery"
                  v-model="queryParams.deviceCode"
                  placeholder="请输入设备编码"
                />
              </el-form-item>

              <el-form-item label="设备名称" prop="deviceName">
                <el-input
                  style="height: 30px"
                  @keyup.enter="handleQuery"
                  v-model="queryParams.deviceName"
                  placeholder="请输入设备名称"
                />
              </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 @click="resetQuery"
                  ><Icon icon="ep:refresh" class="mr-3px" />
                  {{ t('operationFill.reset') }}</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>
          </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"
          :stripe="true"
          :show-overflow-tooltip="true"
          @sort-change="handleSortChange"
          ref="tableRef"
          :height="tableHeight"
        >
          <zm-table-column :label="t('iotDevice.serial')" width="70" align="center" fixed="left">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </zm-table-column>

          <zm-table-column
            label="设备编码"
            sortable
            align="center"
            prop="deviceCode"
            fixed="left"
          />
          <zm-table-column :label="t('iotDevice.name')" sortable align="center" prop="deviceName">
            <template #default="scope">
              <el-link :underline="false" type="primary" @click="handleDetail(scope.row.id)">
                {{ scope.row.deviceName }}
              </el-link>
            </template>
          </zm-table-column>
          <zm-table-column label="公司" align="center" prop="company" />
          <zm-table-column label="部门名称" align="center" prop="deptName" />
          <zm-table-column
            :label="t('iotDevice.status')"
            align="center"
            prop="deviceStatus"
            min-width="90"
          >
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.PMS_DEVICE_STATUS" :value="scope.row.deviceStatus" />
            </template>
          </zm-table-column>
          <zm-table-column
            :label="t('iotDevice.assets')"
            align="center"
            prop="assetProperty"
            min-width="110"
          >
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.PMS_ASSET_PROPERTY" :value="scope.row.assetProperty" />
            </template>
          </zm-table-column>
          <zm-table-column
            :label="t('iotDevice.assetClass')"
            align="center"
            prop="assetClassName"
            min-width="170"
          />
          <zm-table-column label="生产厂家" align="center" prop="manufacturer" />
          <zm-table-column label="生产日期" align="center" min-width="120">
            <template #default="scope">
              {{ formatDate(scope.row.manDate).substring(0, 10) }}
            </template>
          </zm-table-column>
          <zm-table-column label="投运日期" align="center" min-width="120">
            <template #default="scope">
              {{ formatDate(scope.row.enableDate).substring(0, 10) }}
            </template>
          </zm-table-column>
          <zm-table-column :label="t('deviceForm.brand')" align="center" prop="brandName" />
          <zm-table-column :label="t('deviceForm.model')" align="center" prop="model" />
          <zm-table-column :label="t('devicePerson.rp')" align="center" prop="chargeName" action />
        </zm-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>

      <!-- <el-dialog
        v-model="exportDialogVisible"
        title="导出设置"
        width="600px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        class="export-dialog"
      >
        <div class="export-dialog-content">
          <div class="export-header mb-4">
            <p class="export-title">请选择要导出的列</p>
            <p class="export-subtitle"
              >已选择 {{ selectedColumns.length }} / {{ availableColumns.length }} 项</p
            >
          </div>

          <div class="export-options-container">
            <el-checkbox-group v-model="selectedColumns" class="export-checkbox-group">
              <el-checkbox
                v-for="column in availableColumns"
                :key="column.prop"
                :label="column.prop"
                class="export-checkbox-item"
              >
                <span class="checkbox-text">{{ column.label }}</span>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="exportDialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="confirmExport"
              :disabled="selectedColumns.length === 0"
            >
              确认导出 ({{ selectedColumns.length }})
            </el-button>
          </div>
        </template>
      </el-dialog> -->
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
import { DICT_TYPE } from '@/utils/dict'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { buildSortingField } from '@/utils'
import { useRefreshStore } from '@/store/modules/pms/refreshStore'
import Echart from '@/components/Echart/src/Echart.vue'
import echarts from '@/plugins/echarts'
import { formatDate } from '@/utils/formatTime'
import { nextTick, watch } from 'vue'
import download from '@/utils/download'
const message = useMessage() // 消息弹窗
let isLeftContentCollapsed = ref(false)
/** 设备台账 列表 */
defineOptions({ name: 'IotDevicePms' })

const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转

const refreshStore = useRefreshStore()
const loading = ref(true) // 列表的加载中
const list = ref<IotDeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceCode: undefined,
  deviceName: undefined,
  brand: undefined,
  brandName: undefined,
  model: undefined,
  deptId: undefined,
  deviceStatus: undefined,
  assetProperty: undefined,
  picUrl: undefined,
  remark: undefined,
  manufacturerId: undefined,
  supplierId: undefined,
  manDate: [],
  nameplate: undefined,
  expires: undefined,
  plPrice: undefined,
  plDate: [],
  plYear: undefined,
  plStartDate: [],
  plMonthed: undefined,
  plAmounted: undefined,
  remainAmount: undefined,
  infoId: undefined,
  infoType: undefined,
  infoName: undefined,
  infoRemark: undefined,
  infoUrl: undefined,
  templateJson: undefined,
  creator: undefined,
  sortingFields: [],
  assetClass: undefined,
  yfDeviceCode: undefined,
  createTime: []
})
const queryFormRef = ref(null) // 搜索的表单
const contentSpan = ref(20)
const treeShow = ref(true)

const exportDialogVisible = ref(false) // 导出对话框显示状态
const selectedColumns = ref([]) // 选中的列
const availableColumns = ref<any>([]) // 可用的列选项

// 获取表格列信息
const getTableColumns = () => {
  // 根据表格定义动态获取列信息
  availableColumns.value = [
    { prop: 'deviceCode', label: '设备编码', visible: true },
    { prop: 'deviceName', label: '设备名称', visible: true },
    { prop: 'company', label: '公司', visible: true },
    { prop: 'deptName', label: '部门名称', visible: true },
    { prop: 'deviceStatus', label: '设备状态', visible: true },
    { prop: 'assetProperty', label: '资产性质', visible: true },
    { prop: 'assetClassName', label: '资产类别', visible: true },
    { prop: 'manufacturer', label: '生产厂家', visible: true },
    { prop: 'manDate', label: '生产日期', visible: true },
    { prop: 'enableDate', label: '投运日期', visible: true },
    { prop: 'brandName', label: '品牌', visible: true },
    { prop: 'model', label: '规格型号', visible: true },
    { prop: 'chargeName', label: '责任人', visible: true }
  ]

  // 默认选中所有列
  selectedColumns.value = availableColumns.value.map((col) => col.prop)

  // 全选功能
  const selectAllColumns = () => {
    selectedColumns.value = availableColumns.value.map((col) => col.prop)
  }

  // 清空选择
  const clearAllColumns = () => {
    selectedColumns.value = []
  }
}

// 导出功能
// const handleExport = async () => {
//   exportDialogVisible.value = true
//   getTableColumns()
// }

let exportLoading = ref(false)
const handleExport = async () => {
  try {
    const exportParams = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      deviceCode: queryParams.deviceCode,
      deviceName: queryParams.deviceName,

      exportFields: selectedColumns.value.join(',')
    }
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await IotDeviceApi.exportDeviceReport(exportParams)
    download.excel(data, '设备报表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 确认导出
const confirmExport = async () => {
  if (selectedColumns.value.length === 0) {
    ElMessage.warning('请至少选择一列进行导出')
    return
  }

  try {
    // 构建导出参数
    const exportParams = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      deviceCode: queryParams.deviceCode,
      deviceName: queryParams.deviceName,

      exportFields: selectedColumns.value.join(',')
    }

    // 调用后端导出接口
    const res = await IotDeviceApi.exportDeviceReport(exportParams)

    download.excel(res, '设备报表.xlsx')
    exportDialogVisible.value = false
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

const handleSortChange = (params: any) => {
  //console.log(`排序字段: ${prop}, 排序方式: ${order}`);
  queryParams.sortingFields = []
  queryParams.sortingFields = [buildSortingField(params)]
  getList()
}

const myoption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: deviceClassify.value.map((item) => item.category),
      axisLabel: { color: '#000', rotate: 50 }
    },
    yAxis: {
      name: '分类top',
      type: 'value'
    },
    series: [
      {
        data: deviceClassify.value.map((item) => item.value),
        type: 'bar',
        barWidth: 20,
        barCategoryGap: '30%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  }
})

let tableRef = ref(null)
let tableHeight = ref(250)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotDeviceApi.getIotDeviceList(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

    console.log('查询参数>>>>>>>>>>>>>>>>>', typeof queryParams.createTime[0])
    queryParams.pageNo = 1
    getList() // 不重置状态
  },
  {
    immediate: true
  }
)

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  deviceCountQueryParams.deptId = row.id
  deviceCountQueryParams.createTime = queryParams.createTime
  await getList()
  await getDeviceCount()
}

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

const handleDetail = (id: number) => {
  push({ name: 'DeviceDetailInfo', params: { id } })
}

// 设备数量
let devicesCount = ref(0)
const deviceCountQueryParams = reactive({
  deptId: undefined,
  createTime: []
})

// 设备状态
let deviceStatus = ref([])
const statusChartOption = computed(() => {
  // 将 deviceStatus 转换为饼图需要的格式
  const data = deviceStatus.value.map((item) => ({
    value: item.value,
    name: item.name
  }))

  // 如果没有数据，返回空配置
  if (data.length === 0) {
    return {
      series: [
        {
          type: 'pie',
          data: []
        }
      ]
    }
  }

  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      show: false
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}\n{d}%',
          fontSize: 10
        },
        labelLine: {
          show: true
        },
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
})
// 分类top10
let deviceClassify = ref([])
const getDeviceCount = async () => {
  devicesCount.value = await IotDeviceApi.getIotDeviceCount(deviceCountQueryParams)
  deviceStatus.value = await IotDeviceApi.getIotDeviceStatus(deviceCountQueryParams)
  deviceClassify.value = await IotDeviceApi.getIotDeviceClassify(deviceCountQueryParams)
}

// 计算表格高度
const calculateTableHeight = () => {
  if (!tableRef.value) return
  let h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
  tableHeight.value = h - 460
}

// 防抖处理（防止频繁触发）
const debounce = (fn, delay) => {
  let timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => fn(...args), delay)
  }
}
/** 初始化 **/
onMounted(async () => {
  getDeviceCount()
  nextTick(() => {
    calculateTableHeight()
    // 使用防抖避免频繁触发
    const handleResize = debounce(calculateTableHeight, 150)
    window.addEventListener('resize', handleResize)
  })

  const sort = {
    field: 'sortColumn',
    order: 'asc'
  }
  queryParams.sortingFields.push(sort)
  await getList()

  refreshStore.registerCallback('devicerouter', getList)
})
</script>

<style scoped>
.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: 230px;
}
.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, #ff9800, #f57c00);
  background-color: rgba(255, 152, 0, 0.5);
}

/* 确保内容不溢出 */
: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;
}

.export-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.export-dialog-content {
  padding: 0 10px;
}

.export-header {
  text-align: center;
}

.export-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px 0;
}

.export-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.export-options-container {
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background-color: #fafafa;
}

.export-checkbox-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  padding: 10px;
}

.export-checkbox-item {
  margin-bottom: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
  background-color: #fff;
}

.export-checkbox-item:hover {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.export-checkbox-item:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #409eff;
  font-weight: 500;
}

.checkbox-text {
  font-size: 14px;
  color: #606266;
}

.export-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
}

/* 滚动条样式 */
.export-options-container::-webkit-scrollbar {
  width: 6px;
}

.export-options-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.export-options-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}

.export-options-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .export-checkbox-group {
    grid-template-columns: 1fr;
  }

  .export-dialog {
    width: 90% !important;
  }
}
</style>
