<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-click="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>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[9, 18, 36, 72]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 绑定设备弹窗 -->
    <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 lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TableList from '@/components/tableList/index.vue'

defineOptions({
  name: 'DeviceIndex'
})

// 静态数据
const tabList = ref([
  { id: 0, name: '四维看看' },
  { id: 4, 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 mockCameraData = ref([
  {
    id: 1,
    snCode: 'CAM001',
    status: 1,
    usedSpaceStr: '2.5GB',
    totalSpaceStr: '10GB',
    spaceEndStr: '2024-12-31',
    spaceEndTime: '2024-12-31',
    userIncrementId: 'inc_001',
    sceneNum: 5,
    lastTime: '2024-01-15 10:30:00',
    selected: false,
    cameraType: 4,
    cooperationUserName: '张三',
    goodsId: 0,
    usedSpace: 2684354560, // 2.5GB in bytes
    totalSpace: 10737418240 // 10GB in bytes
  },
  {
    id: 2,
    snCode: 'CAM002', 
    status: 1,
    usedSpaceStr: '5.2GB',
    totalSpaceStr: '20GB',
    spaceEndStr: '2024-11-30',
    spaceEndTime: '2024-11-30',
    userIncrementId: 'inc_002',
    sceneNum: 8,
    lastTime: '2024-01-14 15:20:00',
    selected: false,
    cameraType: 9,
    cooperationUserName: '李四',
    goodsId: 0,
    usedSpace: 5583457484, // 5.2GB in bytes
    totalSpace: 21474836480 // 20GB in bytes
  },
  {
    id: 3,
    snCode: 'CAM003',
    status: 0,
    usedSpaceStr: '1.8GB',
    totalSpaceStr: '5GB', 
    spaceEndStr: '2024-10-15',
    spaceEndTime: '2024-10-15',
    userIncrementId: null,
    sceneNum: 3,
    lastTime: '2024-01-13 09:15:00',
    selected: false,
    cameraType: 10,
    cooperationUserName: '',
    goodsId: 0,
    usedSpace: 1932735283, // 1.8GB in bytes
    totalSpace: 5368709120 // 5GB in bytes
  },
  {
    id: 4,
    snCode: 'CAM004',
    status: 1,
    usedSpaceStr: '8.5GB',
    totalSpaceStr: '50GB',
    spaceEndStr: '2025-03-15',
    spaceEndTime: '2025-03-15',
    userIncrementId: 'inc_004',
    sceneNum: 12,
    lastTime: '2024-01-16 14:22:00',
    selected: false,
    cameraType: 11,
    cooperationUserName: '王五',
    goodsId: 0,
    usedSpace: 9126805504, // 8.5GB in bytes
    totalSpace: 53687091200 // 50GB in bytes
  },
  {
    id: 5,
    snCode: 'CAM005',
    status: 1,
    usedSpaceStr: '15.2GB',
    totalSpaceStr: '100GB',
    spaceEndStr: '2024-09-20',
    spaceEndTime: '2024-09-20',
    userIncrementId: 'inc_005',
    sceneNum: 20,
    lastTime: '2024-01-16 16:45:00',
    selected: false,
    cameraType: 12,
    cooperationUserName: '赵六',
    goodsId: 0,
    usedSpace: 16321863680, // 15.2GB in bytes
    totalSpace: 107374182400 // 100GB in bytes
  },
  {
    id: 6,
    snCode: 'CAM006',
    status: 1,
    usedSpaceStr: '3.8GB',
    totalSpaceStr: '15GB',
    spaceEndStr: '2024-08-30',
    spaceEndTime: '2024-08-30',
    userIncrementId: null,
    sceneNum: 6,
    lastTime: '2024-01-12 11:30:00',
    selected: false,
    cameraType: 4,
    cooperationUserName: '',
    goodsId: 0,
    usedSpace: 4080218931, // 3.8GB in bytes
    totalSpace: 16106127360 // 15GB in bytes
  },
  {
    id: 7,
    snCode: 'TOW_001',
    status: 1,
    balance: '¥128.50',
    childName: 'TOW_001',
    selected: false,
    cameraType: 4,
    goodsId: 1,
    lastTime: '2024-01-16 09:20:00'
  },
  {
    id: 8,
    snCode: 'TOW_002',
    status: 1,
    balance: '¥256.80',
    childName: 'TOW_002',
    selected: false,
    cameraType: 9,
    goodsId: 8,
    lastTime: '2024-01-15 17:35:00'
  }
])

// 响应式数据
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<any[]>([])
const showBinding = ref(false)
const showRenew = ref(false)
const reNewItem = ref<any>({})
const showCtrls = ref<number | null>(null)
const showInfo = ref<number | null>(null)
const selectedType = ref({ name: '设备编号', value: 2 })

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

const oldTotalObj = ref<Record<number, number>>({
  0: 0,
  4: 0,
  10: 0, 
  11: 0,
  12: 0
})

const filteredData = computed(() => {
  let data = mockCameraData.value
  
  // 根据当前标签页过滤
  data = mockCameraData.value.filter(item => {
    if (tabActive.value === 0) return item.status === 0 // 协作设备
    if (tabActive.value === 4) return item.goodsId === 0 && item.status !== 0 // 我的设备（排除充值设备，排除协作设备）
    if (tabActive.value === 10) return item.cooperationUserName && item.goodsId === 0 // 共享设备（有协作用户）
    if (tabActive.value === 11) return item.goodsId === 1 || item.goodsId === 8 // 租赁设备（充值设备）
    if (tabActive.value === 12) return item.cameraType === 12 // 四维深巡
    return true
  })
  
  // 搜索过滤
  if (searchKey.value) {
    data = data.filter(item => {
      if (selectedType.value.value === 2) {
        return item.snCode && item.snCode.toLowerCase().includes(searchKey.value.toLowerCase())
      } else if (selectedType.value.value === 1) {
        return item.cooperationUserName && item.cooperationUserName.toLowerCase().includes(searchKey.value.toLowerCase())
      }
      return true
    })
  }
  
  return data
})

const cameraList = computed(() => {
  const data = filteredData.value
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  return data.slice(start, end)
})

// 监听过滤数据变化更新总数
watch(filteredData, (newData) => {
  total.value = newData.length
}, { immediate: true })

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

// 方法
const handleTabClick = (tab: any) => {
  tabActive.value = parseInt(tab.name)
  currentPage.value = 1
  updateTotalCount()
}

const updateTotalCount = () => {
  // 更新各个标签的数量
  totalObj.value[0] = mockCameraData.value.filter(item => item.status === 0).length // 协作设备
  totalObj.value[4] = mockCameraData.value.filter(item => item.goodsId === 0 && item.status !== 0).length // 我的设备（排除充值设备，排除协作设备）
  totalObj.value[10] = mockCameraData.value.filter(item => item.cooperationUserName && item.goodsId === 0).length // 共享设备（有协作用户）
  totalObj.value[11] = mockCameraData.value.filter(item => item.goodsId === 1 || item.goodsId === 8).length // 租赁设备（充值设备）
  totalObj.value[12] = mockCameraData.value.filter(item => item.cameraType === 12).length // 四维深巡
  
  oldTotalObj.value = { ...totalObj.value }
}

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

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


const handleItemSelect = () => {
  updateSelectedArr()
}

const updateSelectedArr = () => {
  selectedArr.value = cameraList.value.filter(item => item.selected)
}

const selectHandle = (selection: any[]) => {
  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: any) => {
  ElMessage.success(`设备 ${item.snCode} 协作功能`)
}

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

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

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

const handleBindingSuccess = () => {
  showBinding.value = false
  ElMessage.success('绑定成功')
  updateTotalCount()
}

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

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

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

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

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

// 生命周期
onMounted(() => {
  updateTotalCount()
})

// 监听器
watch(tabActive, () => {
  selectedArr.value = []
})
</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>