<template>
  <div class="camera-page">
    <!-- 顶部标签页 -->
    <div class="camera-header" v-if="Object.values(oldTotalObj).reduce((t,c) => t+c, 0)">
      <el-tabs v-model="tabActive" @tab-change="handleTabClick">
        <el-tab-pane 
          v-for="item in tabList" 
          :key="item.id"
          :label="`${item.name}(${totalObj[item.id]})`"
          :name="item.id"
          v-show="oldTotalObj[item.id]"
        />
      </el-tabs>
      
      <!-- 操作栏 -->
      <div class="main-list">
        <div class="btns">
          <!-- 批量操作提示 -->
          <!-- <div v-show="!isImgType && selectedArr.length > 0" class="selection-info">
            已选择 {{ selectedArr.length }} 项
          </div> -->

          <i
            v-if="tabActive !== 0 && selectedArr.length > 0"
            @click="multCop"
            class="iconfont icon-menu_cooperation1"
            :title="$t('manage.myDevices.pictle')"
            :class="{ active: isImgType }"
          ></i>
          
          <!-- 解绑按钮 -->
          <i 
            v-if="tabActive !== 0 && selectedArr.length > 0"
            @click="multDel"
            class="iconfont icon-unbind"
            :title="$t('manage.myDevices.unbind')"
            :class="{ active: isImgType }"
          ></i>
        </div>

        <div class="rig-con">
          <!-- 添加设备 -->
          <h-icon :title="$t('manage.deviceAdmin.collaborative')"  @click="multCop" type="icon-new_camera" class="icon main-list-left-icon icon-new_camera" />
          
          <!-- 视图切换 -->
          <div v-if="tabActive !== 0">
            <i
              @click="changeType(true)"
              v-if="!isImgType"
              class="iconfont icon-main_grid"
              :title="$t('manage.myDevices.pictle')"
              :class="{ active: isImgType }"
            ></i>
            <i
              @click="changeType(false)"
              v-else
              class="iconfont icon-view_list"
              :title="$t('manage.myDevices.listtle')"
              :class="{ active: !isImgType }"
            ></i>
          </div>
          
          <!-- 搜索框 -->
          <el-input
            v-model="searchKey"
            placeholder="搜索设备ID"
            class="search-input"
            @keyup.enter="handleSearch"
            clearable
          >
            <template #prepend>
              <el-select v-model="selectedType" placeholder="选择类型" style="width: 100px">
                <el-option
                  v-for="item in searchTypeList"
                  :key="item.value"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </template>
            <template #suffix>
              <h-icon
                class="search-btn"
                type="search"
              />
            </template>
          </el-input>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <table-list
        :data="cameraList"
        :header="tabHeader"
        :selection="tabActive !== 0"
        :show-card-view="isImgType"
        @selection-change="selectHandle"
        @cooperation="handleCooperation"
        @unbind="unbind"
        @renew="handleRenew"
        ref="tableRef"
      >
        <!-- 自定义插槽内容 -->
        <template #item="{ data, subKey, type, item, canclick }">
          <div v-if="type === 'image'" class="flex-avatar">
            <div v-if="isMember(item)" class="vip-icon"></div>
            <div v-else-if="isExpiredMember(item)" class="vip-icon vip-expired-icon"></div>
            <span>{{ data }}</span>
          </div>
          
          <div v-else-if="type === 'qingkuang'">
            <span>{{ item.usedSpaceStr || '0B' }}/{{ item.totalSpaceStr || '0B' }}</span>
          </div>
          
          <div v-else-if="type === 'spaceEndStr'">
            <span :class="{ 'text-danger': isExpired(item) }">
              {{ data || '-' }}
            </span>
          </div>
          
          <div v-else-if="canclick && subKey === 'operation'" class="operation-buttons">
            <span 
              v-if="tabActive === 0"
              class="table-btn"
              @click="handleCooperation(item)"
            >
              协作
            </span>
            <template v-else>
              <span 
                class="table-btn"
                @click="handleCooperation(item)"
                style="margin-right: 10px;"
              >
                协作
              </span>
              <span 
                class="table-btn"
                @click="unbind(item)"
                style="margin-right: 10px;"
              >
                解绑
              </span>
              <span 
                v-if="item.userIncrementId"
                class="table-btn"
                @click="handleRenew(item)"
              >
                续费
              </span>
            </template>
          </div>
          
          <span v-else>{{ data || '-' }}</span>
        </template>
      </table-list>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-if="!loading && !total">
      <el-empty description="暂无数据">
        <template v-if="!Object.values(oldTotalObj).reduce((t,c) => t+c, 0)">
          <el-button type="primary" @click="addDevice">添加设备</el-button>
        </template>
      </el-empty>
    </div>
currentPage{{ currentPage }}
    <!-- 分页 -->
    <Paging
      v-if="total"
      :total="total"
      :current="currentPage"
      @clickHandle="pageChange"
    />

    <!-- 绑定设备弹窗 -->
    <el-dialog v-model="showBinding" title="绑定设备" width="600px">
      <div>绑定设备功能</div>
      <template #footer>
        <el-button @click="showBinding = false">取消</el-button>
        <el-button type="primary" @click="handleBindingSuccess">确定</el-button>
      </template>
    </el-dialog>

    <!-- 续费弹窗 -->
    <el-dialog v-model="showRenew" title="会员续费" width="600px">
      <div>会员续费功能</div>
      <template #footer>
        <el-button @click="showRenew = false">取消</el-button>
        <el-button type="primary" @click="handleRenewSuccess">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TableList from '@/components/tableList/index.vue'
import { getlistNew } from '@/api/camera/index'

defineOptions({
  name: 'DeviceIndex'
})

// 静态数据
const tabList = ref([
  { id: 4, name: '四维看看' },
  { id: 9, name: '四维看见' },
  { id: 10, name: '四维深时' },
  { id: 11, name: '四维深光' },
  { id: 12, name: '四维深巡' }
])

const searchTypeList = ref([
  { name: 'S/N码', value: 2 },
  { name: '协作者', value: 1 }
])

// 表格头部配置
const tabHeader = ref([
  { key: 'snCode', name: 'S/N码', type: 'image' },
  { key: 'status', name: '状态' },
  { key: 'qingkuang', name: '云容量', type: 'qingkuang' },
  { key: 'spaceEndStr', name: '到期时间', type: 'spaceEndStr'},
  { key: 'operation', name: '操作', canclick: true }
])


// 响应式数据
const tabActive = ref(4)
const currentPage = ref(1)
const pageSize = ref(9)
const total = ref(0)
const isImgType = ref(localStorage.getItem("isImgTypeForDevice") !== "false")
const searchKey = ref("")
const loading = ref(false)
const selectedArr = ref([])
const showBinding = ref(false)
const showRenew = ref(false)
const reNewItem = ref({})
const selectedType = ref({ name: 'S/N码', value: 2 })
const cameraData = ref([])

// 计算属性
const totalObj = ref({
  4: 0,
  9: 0, 
  10: 0,
  11: 0,
  12: 0
})

const oldTotalObj = ref({
  4: 0,
  9: 0,
  10: 0, 
  11: 0,
  12: 0
})

const cameraList = ref([])

// 组件引用
const tableRef = ref()

// 方法
const getCameraList = async (cameraType = tabActive.value, pageNum = currentPage.value) => {
  try {
    loading.value = true
    const params = {
      cameraType,
      selecttype: selectedType.value.value,
      childName: searchKey.value,
      pageNum,
      pageSize: pageSize.value
    }
    
    const response = await getlistNew(params)
    
    if (cameraType === tabActive.value) {
      // 只有当前标签页的数据才更新cameraData
      cameraList.value = response.list || []
      total.value = response.total || 0
    }
    
    return response.total || 0
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
    return 0
  } finally {
    loading.value = false
  }
}

const getAllTabsTotalCount = async () => {
  try {
    // 循环调用所有tab栏的接口获取总数
    const promises = tabList.value.map(async (tab) => {
      const params = {
        cameraType: tab.id,
        selecttype: 2, // 默认使用S/N码搜索
        childName: "",
        pageNum: 1,
        pageSize: 1 // 只需要获取总数，所以设置为1
      }
      
      try {
        const response = await getlistNew(params)
        return {
          id: tab.id,
          total: response.total || 0
        }
      } catch (error) {
        console.error(`获取标签页 ${tab.name} 数据失败:`, error)
        return {
          id: tab.id,
          total: 0
        }
      }
    })
    
    const results = await Promise.all(promises)
    
    // 更新totalObj和oldTotalObj
    results.forEach(result => {
      totalObj.value[result.id] = result.total
      oldTotalObj.value[result.id] = result.total
    })
  } catch (error) {
    console.error('获取所有标签页总数失败:', error)
  }
}

const handleTabClick = async (tab) => {
  tabActive.value = parseInt(tab)
  currentPage.value = 1
  await getCameraList()
}


const changeType = (status) => {
  isImgType.value = status
  localStorage.setItem("isImgTypeForDevice", status.toString())
}

const handleSearch = async () => {
  currentPage.value = 1
  await getCameraList()
}



const selectHandle = (selection) => {
  selectedArr.value = selection
}

const multCop = () => {
  if (selectedArr.value.length === 0) {
    ElMessage.warning('请至少选择一个设备')
    return
  }
  ElMessage.success('批量协作功能')
}

const multDel = async () => {
  if (selectedArr.value.length === 0) {
    ElMessage.warning('请至少选择一个设备')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要解绑选中的设备吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    ElMessage.success('解绑成功')
    selectedArr.value = []
  } catch {
    // 用户取消
  }
}

const handleCooperation = (item) => {
  ElMessage.success(`设备 ${item.snCode} 协作功能`)
}

const unbind = async (item) => {
  try {
    await ElMessageBox.confirm(`确定要解绑设备 ${item.snCode} 吗？`, '提示', {
      confirmButtonText: '确定', 
      cancelButtonText: '取消',
      type: 'warning'
    })
    ElMessage.success('解绑成功')
  } catch {
    // 用户取消
  }
}

const handleRenew = (item) => {
  reNewItem.value = item
  showRenew.value = true
}

const addDevice = () => {
  showBinding.value = true
}

const handleBindingSuccess = async () => {
  showBinding.value = false
  ElMessage.success('绑定成功')
  // 重新获取所有标签页总数和当前数据
  await getAllTabsTotalCount()
  await getCameraList()
}

const handleRenewSuccess = () => {
  showRenew.value = false
  ElMessage.success('续费成功')
}


const pageChange = async (page) => {
  currentPage.value = page
  await getCameraList()
}

// 工具方法
const isMember = (item) => {
  return item.userIncrementId && !isExpired(item)
}

const isExpiredMember = (item) => {
  return item.userIncrementId && isExpired(item)
}

const isExpired = (item) => {
  if (!item.spaceEndTime) return false
  const expired = Math.floor((new Date(item.spaceEndTime).getTime() - new Date().getTime()) / 86400000) + 1
  return expired < 0
}

// 生命周期
onMounted(async () => {
  // 先获取所有标签页的总数
  await getAllTabsTotalCount()
  // 然后获取当前标签页的数据
  await getCameraList()
})

// 监听器
watch(()=>tabActive, () => {
  selectedArr.value = []
})

watch(()=>selectedType, async () => {
  currentPage.value = 1
  await getCameraList()
}, { deep: true })
</script>

<style lang="less" scoped>
.camera-page {
  padding: 20px 30px!important;
}

.camera-header {
  
  :deep(.el-tabs__header) {
    margin-bottom: 10px;
    .el-tabs__item{
      font-size: 16px;
    }
    .el-tabs__item.is-active, .el-tabs__item:hover{
      color: #15bec8;
    }
    .el-tabs__active-bar{
      background-color: #15bec8;
    }
  }

  :deep(.el-tabs__nav-wrap:after) {
    height: 0;
  }
  
  .main-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #e5e5e5;
    
    .btns {
      display: flex;
      align-items: center;
      gap: 20px;
      
      .selection-info {
        color: #15bec8;
        font-size: 14px;
        font-weight: 500;
      }
    }
    
    .rig-con {
      display: flex;
      align-items: center;
      gap: 20px;
      
      .view-toggle {
        margin: 0 10px;
      }
      
      .search-input {
        width: 300px;
        
        :deep(.el-input-group__prepend) {
          padding: 0;
          
          .el-select {
            border: none;
            
            .el-input__wrapper {
              box-shadow: none;
            }
          }
        }
      }
      :deep(.el-input-group__prepend .el-select){
        margin: 0!important;
      }
    }
  }
}

.camera-cards {
  padding: 20px 0;
  
  .camera-item {
    margin-bottom: 20px;
    
    .card-wrapper {
      position: relative;
      background: #f7f7f7;
      padding: 20px;
      border-radius: 8px;
      min-height: 180px;
      
      .item-checkbox {
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 1;
      }
    }
  }
}

.table-list {
  margin: 20px 0;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.pagination-wrapper {
  margin-top: 40px;
  text-align: center;
}

// 工具提示样式
.info-wrapper, .expired-icon {
  position: relative;
  
  .info-tooltip, .expired-tooltip {
    position: absolute;
    background: #fff;
    border: 1px solid #e5e5e5;
    border-radius: 4px;
    padding: 10px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    min-width: 200px;
    top: 100%;
    left: 0;
    
    .info-content {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 5px;
      
      .th {
        font-weight: 600;
        color: #323233;
      }
      
      .td {
        color: #666;
      }
    }
    
    .ctrls-w {
      margin-top: 10px;
      text-align: right;
    }
  }
}

.table-btn {
  color: #15bec8;
  cursor: pointer;
  
  &:hover {
    text-decoration: underline;
  }
}

.flex-avatar {
  display: flex;
  align-items: center;
  
  .vip-icon {
    width: 16px;
    height: 16px;
    background: url('@/assets/images/information/avatar_vip.png') no-repeat center center;
    background-size: cover;
    margin-right: 5px;
    
    &.vip-expired-icon {
      opacity: 0.5;
    }
  }
}

.content-wrapper {
  margin: 20px 0;
}

.operation-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.text-danger {
  color: #f56c6c;
}
</style>