<template>
  <Dialog :title="'租户续费'" v-model="dialogVisible" :draggable="false">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <!-- id：选中租户的 id，只读展示 -->
      <el-form-item label="租户 ID" prop="id">
        <el-input v-model="formData.id" disabled />
      </el-form-item>

      <!-- packageId：套餐选择框 -->
      <el-form-item label="续费套餐" prop="packageId">
        <div class="package-selection-container">
          <el-radio-group v-model="activePackageCategory" class="category-tabs">
            <el-radio-button label="normal">常规套餐</el-radio-button>
            <!-- <el-radio-button label="test">测试套餐</el-radio-button> -->
          </el-radio-group>

          <div v-show="activePackageCategory === 'normal'" class="filter-section">
            <div class="filter-row">
              <span class="filter-label">包含功能：</span>
              <el-checkbox-group v-model="selectedFeatures">
                <el-checkbox :label="1">爬主播</el-checkbox>
                <el-checkbox :label="2">爬大哥</el-checkbox>
                <el-checkbox :label="4">AI套餐</el-checkbox>
              </el-checkbox-group>
            </div>
            <div class="filter-row" style="margin-top: 8px;">
              <span class="filter-label">套餐周期：</span>
              <el-radio-group v-model="selectedDays" size="small">
                <el-radio-button :label="null">全部</el-radio-button>
                <el-radio-button :label="30">30 天</el-radio-button>
                <el-radio-button :label="185">185 天</el-radio-button>
                <el-radio-button :label="365">365 天</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <div class="package-card-grid">
            <div v-for="item in filteredPackages" :key="item.id" class="package-card"
              :class="{ 'is-active': formData.packageId === item.id }" @click="formData.packageId = item.id">
              <div v-if="formData.packageId === item.id" class="active-badge">
                <el-icon>
                  <Check />
                </el-icon>
              </div>

              <div class="card-title">{{ item.name }}</div>
              <div class="card-price">
                <span class="currency">¥</span>
                <span class="amount">{{ item.price }}</span>
              </div>
              <div class="card-desc">时长: {{ item.days === 9999 ? '永久有效' : item.days + ' 天' }}</div>
            </div>
          </div>

          <el-empty v-if="filteredPackages.length === 0" description="暂无匹配的套餐，请调整筛选条件" :image-size="60" />
        </div>
      </el-form-item>

      <!-- remark：备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" :rows="3" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" :loading="formLoading" @click="submitForm">
        确 定
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { Check } from '@element-plus/icons-vue'
import { useMessage } from '@/hooks/web/useMessage'
import * as TenantApi from '@/api/system/tenant'
import * as TenantPackageApi from '@/api/system/tenantPackage'

const message = useMessage()
const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)

// 表单数据：id / packageId / remark
const formData = reactive({
  id: null,
  packageId: null,
  remark: ''
})

const formRules = {
  packageId: [{ required: true, message: '请选择续费套餐', trigger: 'change' }],
  // 如果备注必填就放开下面这一条
  // remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
}

// 套餐列表
const packageList = ref<TenantPackageApi.TenantPackageVO[]>([])

// UI 交互状态
const activePackageCategory = ref('normal') // 套餐大类：'normal' | 'test'
const selectedFeatures = ref<number[]>([]) // 功能勾选
const selectedDays = ref<number | null>(null) // 按套餐天数筛选

// 计算最终展示的套餐列表
const filteredPackages = computed(() => {
  let list = packageList.value || []
  if (!list.length) return []

  let result: any[] = []

  // 1. 首先排除代理套餐
  list = list.filter(item => !item.name.includes('代理') && item.packageType !== 999)

  // 2. 根据顶部 Tab 进行大类粗筛
  if (activePackageCategory.value === 'test') {
    // 测试套餐特征：名称含'测试'
    result = list.filter(item => item.name.includes('测试'))
  } else {
    // 常规套餐：排除测试套餐
    result = list.filter(item => !item.name.includes('测试'))

    // 3. 常规套餐继续应用「功能勾选」过滤
    if (selectedFeatures.value.length > 0) {
      result = result.filter(item => {
        const typeStr = String(item.packageType ?? '')
        return selectedFeatures.value.every(flag => typeStr.includes(String(flag)))
      })
    }

    // 4. 常规套餐继续应用「天数过滤」
    if (selectedDays.value != null) {
      result = result.filter(item => item.days === selectedDays.value)
    }
  }

  return result
})

// 对外暴露的 open 方法：传入租户 id
const open = async (id: number) => {
  // 重置表单
  formData.id = id
  formData.packageId = null
  formData.remark = ''
  dialogVisible.value = true

  // 重置筛选条件
  selectedFeatures.value = []
  selectedDays.value = null
  activePackageCategory.value = 'normal' // 回到默认Tab

  // 需要时再加载套餐列表
  if (!packageList.value.length) {
    packageList.value = await TenantPackageApi.getTenantPackageList()
  }
}

defineExpose({ open })

// 提交
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    formLoading.value = true
    try {
      // 🔴 根据你原来续费的接口改这里的调用
      // 假设后端有一个 TenantApi.renewTenant
      await TenantApi.renewal({
        id: formData.id,
        packageId: formData.packageId,
        remark: formData.remark
      })

      message.success('续费成功')
      dialogVisible.value = false
      emit('success') // 通知父组件刷新列表
    } catch (e) {
      console.error(e)
    } finally {
      formLoading.value = false
    }
  })
}
</script>

<style scoped>
/* ================= 卡片与筛选样式 ================= */
.package-selection-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.category-tabs {
  margin-bottom: 4px;
}

/* 过滤区域样式 */
.filter-section {
  background-color: #f8f9fa;
  padding: 12px 16px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.filter-row {
  display: flex;
  align-items: center;
}

.filter-label {
  font-size: 13px;
  color: #606266;
  width: 80px;
  flex-shrink: 0;
  font-weight: 500;
}

/* 卡片网格布局：自适应排列 */
.package-card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
  gap: 16px;
  margin-top: 8px;
}

/* 单个套餐卡片 */
.package-card {
  position: relative;
  background: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  overflow: hidden;
}

.package-card:hover {
  border-color: #c0c4cc;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.05);
  transform: translateY(-2px);
}

/* 选中状态 */
.package-card.is-active {
  border-color: #409eff;
  background-color: #ecf5ff;
  box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.1);
}

/* 选中时的右上角角标 */
.active-badge {
  position: absolute;
  top: 0;
  right: 0;
  width: 0;
  height: 0;
  border-top: 36px solid #409eff;
  border-left: 36px solid transparent;
}

.active-badge .el-icon {
  position: absolute;
  top: -32px;
  right: 2px;
  color: #fff;
  font-size: 14px;
}

/* 卡片内部排版 */
.card-title {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 12px;
  line-height: 1.4;
  height: 40px;
  /* 固定高度防止因名称长短不同导致卡片高度不一 */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.card-price {
  color: #f56c6c;
  margin-bottom: 6px;
}

.card-price .currency {
  font-size: 14px;
  margin-right: 2px;
}

.card-price .amount {
  font-size: 24px;
  font-weight: bold;
}

.card-desc {
  font-size: 12px;
  color: #909399;
}
</style>
