<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" @click="gotoScene(item)">
            <div v-if="isMember(item)" class="vip-icon"></div>
            <div v-else-if="isExpiredMember(item)" class="vip-icon vip-expired-icon"></div>
            <span class="device-id">{{ data }}</span>
          </div>
          
          <div v-else-if="type === 'qingkuang'" class="capacity-info">
            <div class="capacity-text">
              {{ item.usedSpaceStr || '0B' }}
              {{ (isMember(item) || item.cameraType == 10 || item.cameraType == 11 || item.cameraType == 12) ? '' : `/${item.totalSpaceStr || '0B'}` }}
            </div>
          </div>
          
          <div v-else-if="type === 'spaceEndStr'">
            {{ item.spaceEndStr || "--" }}
            <span class="expired-icon-w">
              <el-popover :visible="item.popoverVisible" popper-class="expired-ctrls-w" placement="bottom" :width="200">
                <p v-if="!validExpired(item.spaceEndStr).expiredTime">权益今天到期</p>
                <p v-else-if="validExpired(item.spaceEndStr).trueExpired"> 权益已过期，请及时续费。</p>
                <p v-else v-html="$t('权益还有 {expired} 天到期', { expired: validExpired(item.spaceEndStr).expiredText }) "></p>
                <div class="ctrls-w">
                  <div class="btn cancel-btn" @click="item.popoverVisible = false">取消</div>
                  <div class="btn submit-btn" @click="handleRepay(item)">续费</div>
                </div>
                <template #reference>
                  <h-icon
                    type="register_agreement"
                    v-if="validExpired(item.spaceEndStr).isExpired"
                    class="expired-icon kuoda-click-after"
                    @click.stop="item.popoverVisible = true"
                  ></h-icon>
                </template>
              </el-popover>
            </span>
          </div>
          
          <div v-else-if="canclick && subKey === 'operation'" class="operation-buttons">
            <li class="table-btn" @click="handleCooperationaa(item)">
              协作
            </li>
            <el-popover trigger="hover" popper-class="info-content" placement="bottom" :width="400">
                <div class="more-info-content">
                  <span class="th">拍摄场景数量</span><span class="th">最后拍摄时间</span>
                  <span class="td">{{item.sceneNum || '-'}}</span><span class="td">{{item.lastTime || '-'}}</span>
                </div>
                <template #reference>
                  <li class="table-btn">
                    拍摄信息
                  </li> 
                </template>
              </el-popover>         
          </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>

    <!-- 分页 -->
    <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>

    <!-- 协作设置弹窗 -->
    <CooperationModal
      v-model="showCooperationModal"
      :item="cooperationItem"
      @refresh="handleCooperationRefresh"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TableList from '@/components/tableList/index.vue'
import CooperationModal from './components/cooperationaa.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: 'qingkuang', name: '云容量', type: 'qingkuang' },
  { key: 'spaceEndStr', name: '到期时间', type: 'spaceEndStr'},
  { key: 'cooperationUserName', name: '协作者' },
  { 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 showCtrls = ref(null)
const timer = ref(null)
const showCooperationModal = ref(false)
const cooperationItem = 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 isMember = (item) => {
  const expiredInfo = getExpiredInfo(item)
  return item.userIncrementId && !expiredInfo.trueExpired
}

const isExpiredMember = (item) => {
  const expiredInfo = getExpiredInfo(item)
  return item.userIncrementId && expiredInfo.trueExpired
}

const getExpiredInfo = (item) => {
  if (!item.spaceEndTime) {
    return {}
  }
  let expired = Math.floor((new Date(item.spaceEndTime) - new Date()) / 86400000) + 1
  return {
    expiredTime: `<span class="expired">${expired}</span>`,
    isExpired: expired <= 30,
    trueExpired: expired < 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
      // 为每个设备项添加独立的 visible 属性
      cameraList.value = (response.list || []).map(item => ({
        ...item,
        popoverVisible: false,
      }))
      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 handleCooperationaa = (item) => {
  cooperationItem.value = item
  showCooperationModal.value = true
}

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 setTimeoutShowCtrls = (bool, item) => {
  clearTimeout(timer.value)
  console.log(bool, item, 7777)
  timer.value = setTimeout(() => {
    showCtrls.value = bool ? item.id : null
  }, 200)
}

const handleRepay = (item) => {
  reNewItem.value = item
  showRenew.value = true
  item.popoverVisible = false
  showCtrls.value = null
}

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 handleCooperationRefresh = async () => {
  // 刷新列表
  await getCameraList()
}


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

// 工具方法
const validExpired = (time) => {
  if (!time) {
    return {}
  }
  let expired = Math.floor((new Date(time) - new Date()) / 86400000) + 1

  return {
    expiredTime: expired,
    expiredText: `<span class="expired">${expired}</span>`,
    isExpired: expired <= 30,
    trueExpired: expired < 0
  }
}

const getBar = (a, b) => {
  if (a === 0) {
    return 0
  }
  let temp = (a / b) * 100
  if (temp < 1) {
    return '1%'
  }
  return (temp > 100 ? 100 : Math.round(temp)) + '%'
}

const getColor = (a, b) => {
  let temp = (a / b) * 100
  let point = 80
  let color = ''
  switch (true) {
    case temp < point:
      color = '#15BEC8'
      break
    default:
      color = '#ff0000'
      break
  }
  return color
}

const gotoScene = (item) => {
  // 根据设备类型跳转到对应的场景页面
  const tabActiveMap = {
    10: 3,
    9: 2, 
    11: 4,
    12: 6
  }
  
  // 这里可以根据实际需求调整路由跳转逻辑
  console.log('跳转到场景页面', {
    item,
    cameraid: item.snCode || item.childName,
    tabActive: tabActiveMap[item.cameraType] || 1
  })
  
  // 如果有路由，可以取消注释下面的代码
  // router.push({
  //   name: 'scenesearch',
  //   params: { id: '4' },
  //   query: {
  //     cameraid: item.snCode || item.childName,
  //     tabActive: tabActiveMap[item.cameraType] || 1
  //   }
  // })
}

// 点击外部关闭弹窗
const handleDocumentClick = () => {
  showCtrls.value = null
}

// 生命周期
onMounted(async () => {
  // 先获取所有标签页的总数
  await getAllTabsTotalCount()
  // 然后获取当前标签页的数据
  await getCameraList()
  
  // 添加全局点击事件监听
  document.documentElement.addEventListener('click', handleDocumentClick)
})

onUnmounted(() => {
  // 清理定时器和事件监听
  if (timer.value) {
    clearTimeout(timer.value)
  }
  document.documentElement.removeEventListener('click', handleDocumentClick)
})

// 监听器
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;
    }
  }
}
.expired-icon {
  margin-left: 6px;
  color: #ff0000;
  font-size: 14px;
  cursor: pointer;
}
.table-btn {
  color: #15bec8;
  cursor: pointer;
  
  &:hover {
    text-decoration: underline;
  }
}

.flex-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
  
  .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;
    }
  }
  
  .device-id {
    color: #15bec8;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

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

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

.text-danger {
  color: #f56c6c;
}

// 容量相关样式
.capacity-info {
  .capacity-text {
    margin-bottom: 5px;
  }
  
  .capacity-bar {
    .c-line {
      width: 100%;
      height: 4px;
      background: #f0f0f0;
      border-radius: 2px;
      overflow: hidden;
      
      .active {
        height: 100%;
        border-radius: 2px;
        transition: all 0.3s ease;
      }
    }
  }
}

// 过期相关样式
.expired-icon {
  cursor: pointer;
}

.expired-ctrls-w {
  background: #fff;
  z-index: 1;
  min-width: 190px;
  height: 85px;
  padding: 12px 16px;
  box-shadow: 0px 2px 12px 0px rgba(50, 50, 51, 0.12);
  border-radius: 4px;
  font-size: 14px;
  color: #323233;
  line-height: 22px;
  p {
    white-space: nowrap;
  }
  &::before {
    content: "";
    display: block;
    border: 8px solid transparent;
    border-bottom-color: #fff;
    position: absolute;
    top: -15px;
    right: 14px;
    left: auto;
    z-index: 1;
    // transform: translateX(-50%);
  }
  .ctrls-w {
    display: flex;
    justify-content: flex-end;
    margin-top: 13px;
  }
  .btn {
    padding: 0 8px;
    line-height: 24px;
    border-radius: 2px;
    background: #ebebeb;
    display: inline-block;
    cursor: pointer;
  }
  .submit-btn {
    background: #15BEC8;
    margin-left: 8px;
    color: #fff;
  }
}
.info-content{
  .more-info-content {
    span {
      float: left;
      width: 50%;
      text-align: center;
      color: #202020;
      font-size: 14px;
      padding: 5px;
      box-sizing: border-box;

      &.th {
        font-weight: 600;
      }
    }
  }
}
</style>