<template>
  <div class="member-table">
    <div class="table-card">
      <div class="table-header">
        <p>会员权益</p>
        <div class="member-intro">
          <el-tooltip class="box-item" effect="dark" content="Bottom Center prompts info" placement="bottom"><h-icon type="register_help"></h-icon></el-tooltip>
        </div>
        
        <div class="search-wrapper">
          <el-input
            v-model="keyword"
            placeholder="搜索相机SN码"
            class="search-input"
          >
            <template #suffix>
              <h-icon
                class="search-btn"
                type="search"
                @click="handleKeywordSearch"
              />
            </template>
          </el-input>
        </div>
      </div>
      
      <div class="table-content">
        <el-table
          :data="list"
          style="width: 100%"
          stripe
          border
          v-loading="loading"
        >
          <el-table-column
            prop="id"
            label="会员权益ID"
            width="180"
            align="center"
          >
            <template #default="{ row }">
              <span>{{ row.id || '--' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column
            prop="snCode"
            label="授权相机S/N码"
            width="200"
            align="center"
          >
            <template #default="{ row }">
              <span>{{ row.snCode || '-' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column
            prop="incrementStartStr"
            label="购买日期"
            width="150"
            align="center"
          >
            <template #default="{ row }">
              <span>{{ row.incrementStartStr || '--' }}</span>
            </template>
          </el-table-column>
          
          <el-table-column
            prop="incrementEndStr"
            label="到期日期"
            width="150"
            align="center"
          >
            <template #default="{ row }">
              <div v-if="row.isExpire" class="is-expired">
                {{ $t("manage.information.memberTable.isExpired") }}
              </div>
              <div v-else class="expired-icon-l">
                {{row.incrementEndStr}}
                <h-icon
                  type="register_agreement"
                  class="expired-icon"
                  v-if="isWillExpired(row)"
                  @click.stop="setTimeoutShowCtrls(true, row)"
                ></h-icon>
                <div
                  v-show="showCtrls === row.id"
                  class="expired-ctrls-w"
                  @click.stop
                >
                  <p v-if="!expired(row).expiredTime">{{$t('manage.member.memberjtdq')}}</p>
                  <p v-else-if="expired(row).trueExpired">
                    {{ $t("manage.deviceAdmin.memberExpired") }}
                  </p>
                  <p
                    v-else
                    v-html="
                      expired(row).expiredTime ? $t('manage.deviceAdmin.memberWillExpired', {
                        expired: expired(row).expiredText,
                      }) : $t('manage.member.memberjtdq')
                    "
                  ></p>
                  <div class="ctrls-w">
                    <div class="btn cancel-btn" @click="showCtrls = null">
                      {{ $t("common.cancle") }}
                    </div>
                    <div class="btn submit-btn" @click="renew(row)">
                      {{$t('manage.member.xf')}}
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column
            label="操作"
            width="200"
            align="center"
          >
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  link
                  @click="handleBind(row)" 
                >
                  {{ row.snCode ? '解除' : '授权' }}
                </el-button>
                <el-button
                  type="primary"
                  link
                  @click="renew(row)"
                >
                  续费
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- <el-pagination
          v-if="total > 0"
          v-model:current-page="form.pageNum"
          v-model:page-size="form.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        /> -->

        <Paging
            v-if="total"
            :total="total"
            :current="pageNum"
            @clickHandle="pageChange"
          />
        
        <div v-if="total === 0 && !loading" class="no-data">
          <div class="no-data-img"></div>
          <p v-if="isSearching">
            未找到相关数据
          </p>
          <p v-else>
            暂无会员数据，<el-button type="primary" link @click="goToBuy">去购买</el-button>
          </p>
        </div>
      </div>
    </div>
    
    <!-- 绑定设备弹窗 -->
    <el-dialog
      v-model="showBindDialog"
      title="绑定设备"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="bind-form">
        <el-form :model="bindForm" label-width="120px">
          <el-form-item label="设备序列号:">
            <el-input
              v-model="bindForm.snCode"
              placeholder="请输入设备序列号"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="showBindDialog = false">取消</el-button>
        <el-button type="primary" @click="handleBindConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import Paging from '@/components/pc/Paging/index.vue'
const emit = defineEmits(['search', 'page-change'])
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  total: {
    type: Number,
    default: 0
  },
  pageNum: {
    type: Number,
    default: 1
  },
  loading: {
    type: Boolean,
    default: false
  },
  snCode: {
    type: String,
    default: ''
  }
})

// UI 状态
const showBindDialog = ref(false)
const selectedItem = ref({})
const isSearching = ref(false)
const keyword = ref(props.snCode || '')
const showCtrls = ref(null)
const timer = ref(null)

watch(() => props.snCode, (val) => {
  if (val !== keyword.value) keyword.value = val || ''
})

const bindForm = reactive({
  snCode: ''
})
const isWillExpired = (item) => {
  return new Date(item.incrementEndStr) - new Date() <= 86400000 * 30
}

const expired = (item) => {
  if (!item.incrementEndStr) {
    return {}
  }
  let expired =
    Math.floor((new Date(item.incrementEndStr) - new Date()) / 86400000) + 1

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

const setTimeoutShowCtrls = (show, item) => {
  if (timer.value) {
    clearTimeout(timer.value)
  }
  timer.value = setTimeout(() => {
    showCtrls.value = show ? item.id : null
  }, 200)
}

const renew = (item) => {
  selectedItem.value = item
  ElMessage.info('跳转到续费页面')
  // 这里可以添加路由跳转逻辑
}
// 方法
const handleKeywordSearch = () => {
  isSearching.value = !!keyword.value
  emit('search', keyword.value.trim())
}

const handleBind = (item) => {
  selectedItem.value = item
  bindForm.snCode = item.snCode || ''
  showBindDialog.value = true
}

const handleBindConfirm = () => {
  if (!bindForm.snCode.trim()) {
    ElMessage.warning('请输入设备序列号')
    return
  }
  
  // 模拟绑定API调用
  setTimeout(() => {
    ElMessage.success('绑定成功')
    showBindDialog.value = false
    emit('search', keyword.value.trim())
  }, 1000)
}


const goToBuy = () => {
  ElMessage.info('跳转到购买页面')
  // 这里可以添加路由跳转逻辑
}

// removed unused isExpired

const pageChange = (newPage) => {
  emit('page-change', newPage)
}

// 全局点击事件处理
const handleGlobalClick = () => {
  setTimeoutShowCtrls(false, {})
}

onMounted(() => {
  document.documentElement.addEventListener('click', handleGlobalClick)
})

onUnmounted(() => {
  document.documentElement.removeEventListener('click', handleGlobalClick)
  if (timer.value) {
    clearTimeout(timer.value)
  }
})
</script>

<style lang="less" scoped>
.member-table {
  .table-card {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .table-header {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 0 30px;
    border-bottom: 1px solid #f0f0f0;
    position: relative;
    
    p {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
    
    .member-intro {
      position: relative;
      margin-left: 10px;
      
      .help-icon {
        cursor: pointer;
        color: #999;
        font-size: 14px;
      }
      
      &:hover .intro-tooltip {
        display: block;
      }
      
      .intro-tooltip {
        position: absolute;
        bottom: -15px;
        left: -50px;
        transform: translateY(100%);
        padding: 12px 16px;
        background: #333;
        color: #fff;
        border-radius: 4px;
        font-size: 12px;
        white-space: nowrap;
        display: none;
        z-index: 1000;
        
        &::before {
          content: '';
          position: absolute;
          top: -6px;
          left: 50px;
          border-left: 6px solid transparent;
          border-right: 6px solid transparent;
          border-bottom: 6px solid #333;
        }
        
        p {
          margin: 0;
          line-height: 1.4;
          
          &:not(:last-child) {
            margin-bottom: 8px;
          }
        }
      }
    }
    
    .search-wrapper {
      position: absolute;
      right: 30px;
      
      .search-input {
        width: 250px;
        
        :deep(.el-input__wrapper) {
          border-radius: 6px;
          height: 40px;
        }
      }
      
      .search-btn {
        cursor: pointer;
        color: #999;
      }
    }
  }
  
  .table-content {
    padding: 20px 30px 30px;
    
    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 16px;
    }
    .is-expired {
      color: #ff0000;
    }
    .expired-icon {
      margin-left: 6px;
      color: #ff0000;
      font-size: 14px;
      cursor: pointer;
    }
    
    .expired-icon-l {
      position: relative;
      
      .expired-ctrls-w {
        position: absolute;
        right: 0px;
        background: #fff;
        z-index: 1000;
        min-width: 172px;
        padding: 12px 16px;
        box-shadow: 0px 2px 12px 0px rgba(50, 50, 51, 0.12);
        bottom: -10px;
        transform: translateY(100%);
        border-radius: 4px;
        font-size: 14px;
        color: #323233;
        line-height: 22px;

        p {
          white-space: nowrap;
          margin: 0;
        }
        
        &::before {
          content: "";
          display: block;
          border: 8px solid transparent;
          border-bottom-color: #fff;
          position: absolute;
          top: -15px;
          left: 90px;
          z-index: 1;
        }
        
        .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;
          font-size: 12px;
        }
        
        .submit-btn {
          background: #15bec8;
          margin-left: 8px;
          border-radius: 2px;
          color: #fff;
        }
      }
    }
    
    .pagination {
      margin-top: 20px;
      justify-content: center;
    }
    
    .no-data {
      padding: 60px 0;
      text-align: center;
      color: #666;
      
      .no-data-img {
        width: 120px;
        height: 120px;
        margin: 0 auto 16px;
        background: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgdmlld0JveD0iMCAwIDEyMCAxMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiBmaWxsPSIjRjVGNUY1Ii8+CjxwYXRoIGQ9Ik02MCA0MEMzNS44IDQwIDE2IDU5LjggMTYgODRTMzUuOCAxMjggNjAgMTI4UzEwNCAxMDguMiAxMDQgODRTODQuMiA0MCA2MCA0MFoiIGZpbGw9IiNEREREREQiLz4KPHBhdGggZD0iTTQ4IDc2QzQ4IDcyLjcgNTAuNyA3MCA1NCA3MEg2NkM2OS4zIDcwIDcyIDcyLjcgNzIgNzZWODhDNzIgOTEuMyA2OS4zIDk0IDY2IDk0SDU0QzUwLjcgOTQgNDggOTEuMyA0OCA4OFY3NloiIGZpbGw9IiNCQkJCQkIiLz4KPC9zdmc+Cg==') no-repeat center;
        background-size: contain;
      }
      
      p {
        margin: 0;
        font-size: 14px;
      }
    }
  }
  
  .bind-form {
    padding: 20px 0;
  }
}

// Element Plus 样式覆盖
:deep(.el-table) {
  .el-table__header-wrapper {
    .el-table__header {
      th {
        background-color: #fafafa;
        color: #333;
        font-weight: 600;
      }
    }
  }
  
  .el-table__body-wrapper {
    .el-table__body {
      tr:hover > td {
        background-color: #f5f7fa;
      }
    }
  }
}

:deep(.el-pagination) {
  justify-content: flex-start!important;
  .el-pagination__total,
  .el-pagination__jump {
    color: #666;
  }
}
</style>
