<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="50%" :draggable="false">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
      <el-divider>基础信息</el-divider>
      <el-form-item label="租户名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入租户名" />
      </el-form-item>

      <el-form-item v-if="tenantLevel <= 1" label="租户类型" prop="tenantType">
        <el-radio-group v-model="formData.tenantType" @change="handleTenantTypeChange">
          <el-radio value="代理">代理</el-radio>
          <el-radio value="用户">用户</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="联系人" prop="contactName">
        <el-input v-model="formData.contactName" placeholder="请输入联系人" />
      </el-form-item>

      <el-form-item label="联系手机" prop="contactMobile">
        <el-input v-model="formData.contactMobile" placeholder="请输入联系手机" />
      </el-form-item>

      <el-form-item v-if="formData.id === undefined" label="用户名称" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名称" />
      </el-form-item>

      <el-form-item v-if="formData.id === undefined" label="用户密码" prop="password">
        <el-input v-model="formData.password" placeholder="请输入用户密码" show-password type="password" />
      </el-form-item>

      <el-form-item label="账号额度" prop="accountCount">
        <el-input-number v-model="formData.accountCount" :min="0" controls-position="right" placeholder="请输入账号额度" />
      </el-form-item>

      <el-form-item v-if="tenantLevel == 0" label="AI过期时间" prop="aiExpireTime">
        <el-date-picker v-model="formData.aiExpireTime" clearable placeholder="请选择AI过期时间" type="date"
          value-format="x" />
      </el-form-item>

      <el-form-item v-if="tenantLevel == 0" label="爬大哥过期时间" prop="brotherExpireTime">
        <el-date-picker v-model="formData.brotherExpireTime" clearable placeholder="请选择爬大哥过期时间" type="date"
          value-format="x" />
      </el-form-item>

      <el-form-item v-if="tenantLevel == 0" label="爬虫过期时间" prop="crawlExpireTime">
        <el-date-picker v-model="formData.crawlExpireTime" clearable placeholder="请选择爬虫过期时间" type="date"
          value-format="x" />
      </el-form-item>

      <el-form-item v-if="tenantLevel == 0" label="后台过期时间" prop="expireTime">
        <el-date-picker v-model="formData.expireTime" clearable placeholder="请选择过期时间" type="date" value-format="x" />
      </el-form-item>
      <el-form-item v-else label="后台过期时间" prop="expireTime">
        <el-date-picker v-model="formData.expireTime" clearable placeholder="请选择过期时间" disabled type="date"
          value-format="x" />
      </el-form-item>

      <el-form-item label="绑定域名" prop="website">
        <el-input v-model="formData.website" placeholder="请输入绑定域名" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>

      <el-form-item label="租户状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="formType !== 'create'" label="选择用户" prop="userId">
        <el-select v-model="userData.id" @change="changeUser" clearable placeholder="请选择租户用户">
          <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>
      </el-form-item>

      <template v-if="userData.id">
        <el-form-item label="爬虫" prop="status">
          <el-radio-group v-model="userData.crawl">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="爬大哥" prop="status">
          <el-radio-group v-model="userData.bigBrother" :disabled="!formData.brotherExpireTime">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="ios自动化" prop="status">
          <el-radio-group v-model="userData.aiChat" :disabled="!formData.aiExpireTime">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="ai回复" prop="status">
          <el-radio-group v-model="userData.aiReplay" :disabled="!formData.aiExpireTime">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="即时消息" prop="status">
          <el-radio-group v-model="userData.webAi" :disabled="!formData.aiExpireTime">
            <el-radio :value="1">开启</el-radio>
            <el-radio :value="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>

      <el-divider>套餐 & 权限</el-divider>
      <el-form-item label="租户套餐" prop="packageId">
        <el-select v-if="(formData.parentId == 1 || formData.parentId == null) && tenantLevel == 0"
          v-model="formData.packageId" clearable placeholder="请选择租户套餐" style="width: 100%;">
          <el-option v-for="item in packageList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>

        <div v-else class="package-selection-container">
          <el-radio-group v-model="activePackageCategory" class="category-tabs">
            <el-radio-button label="normal" :disabled="formData.tenantType === '代理'">常规套餐</el-radio-button>

            <el-radio-button label="agent" :disabled="formData.tenantType === '用户'">代理套餐</el-radio-button>

            <el-radio-button label="test" :disabled="formData.tenantType === '代理'">测试套餐</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 filteredAgencyPackages" :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="filteredAgencyPackages.length === 0" description="暂无匹配的套餐，请调整筛选条件" :image-size="60" />
        </div>
      </el-form-item>

    </el-form>

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

<script lang="ts" setup>
import { ref, reactive, watch, computed } from 'vue'
import { Check } from '@element-plus/icons-vue' // 引入对号图标
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as TenantApi from '@/api/system/tenant'
import { getUserByTenant, updateRoleUser } from '@/api/system/user'
import { CommonStatusEnum } from '@/utils/constants'
import * as TenantPackageApi from '@/api/system/tenantPackage'
import * as userApi from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'
// 假设有 useI18n 和 useMessage 的全局引入或在此处补全引入
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'

defineOptions({ name: 'SystemTenantForm' })

const tenantLevel = ref(3)
TenantApi.getSelfTenantLevel().then(res => {
  tenantLevel.value = res.tenantLevel
})

const { t } = useI18n()
const message = useMessage()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')
const userStore = useUserStore()

const formData = ref({
  id: 0,
  name: undefined as string | undefined,
  packageId: undefined as number | undefined,
  contactName: undefined as string | undefined,
  contactMobile: undefined as string | undefined,
  accountCount: undefined as number | undefined,
  expireTime: Date.now() as number | undefined,
  website: undefined as string | undefined,
  status: CommonStatusEnum.ENABLE,
  username: undefined as string | undefined,
  password: undefined as string | undefined,
  remark: undefined as string | undefined,
  aiExpireTime: undefined as number | undefined,
  brotherExpireTime: undefined as number | undefined,
  crawlExpireTime: undefined as number | undefined,
  tenantType: undefined as string | number | undefined, // 修改为兼容 string，因 radio 值是'代理'
  parentId: undefined as number | undefined,
})

const userData = ref({} as userApi.UserVO)
const userList = ref<userApi.UserVO[]>([{ id: 0, aiChat: 0, bigBrother: 0, crawl: 0 } as any])

const formRules = reactive({
  name: [{ required: true, message: '租户名不能为空', trigger: 'blur' }],
  packageId: [{ required: true, message: '租户套餐不能为空', trigger: 'blur' }],
  contactName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '租户状态不能为空', trigger: 'blur' }],
  accountCount: [{ required: true, message: '账号额度不能为空', trigger: 'blur' }],
  expireTime: [{ required: true, message: '过期时间不能为空', trigger: 'blur' }],
  website: [{ required: true, message: '绑定域名不能为空', trigger: 'blur' }],
  username: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]+$/, message: '用户名称只能包含数字和字母', trigger: 'blur' }
  ],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }]
})

const formRef = ref()
const packageList = ref([] as TenantPackageApi.TenantPackageVO[])
const packageAgencyList = ref([] as TenantPackageApi.TenantPackageVO[])

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

const SECOND_AGENT_PACKAGE_ID = 10001 // 二级代理套餐的 ID

// 当选择租户类型时，智能切换 Tab
const handleTenantTypeChange = (val: string) => {
  if (val === '代理') {
    activePackageCategory.value = 'agent'  // 自动跳到代理套餐 Tab
    formData.value.packageId = undefined // 清空之前选的错误套餐
  } else if (val === '用户') {
    activePackageCategory.value = 'normal' // 自动跳到常规套餐 Tab
    formData.value.packageId = undefined // 清空之前选的错误套餐
  }
}

// ====== 核心：计算最终展示的套餐列表 ======
const filteredAgencyPackages = computed(() => {
  let list: any[] = formType.value === 'create' ? packageList.value || [] : packageAgencyList.value || []
  if (!list.length) return []

  let result: any[] = []

  // 1. 根据顶部 Tab 进行大类粗筛
  if (activePackageCategory.value === 'agent') {
    // 假设代理套餐特征：名称含'代理' 或 天数9999 或 ID是二级代理
    result = list.filter(item => item.name.includes('代理') || item.days === 9999 || item.id === SECOND_AGENT_PACKAGE_ID)
  }
  else if (activePackageCategory.value === 'test') {
    // 假设测试套餐特征：名称含'测试'
    result = list.filter(item => item.name.includes('测试'))
  }
  else {
    // 常规套餐：排除代理和测试套餐
    result = list.filter(item => !item.name.includes('代理') && !item.name.includes('测试') && item.days !== 9999)

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

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

  // 4. 原有的租户类型强制限制逻辑 (兜底保护)
  // 4. 最终兜底：利用后端的 packageType 进行限制
  const tenantType = formData.value.tenantType
  if (tenantType === '代理') {
    // 租户类型选了“代理”，强制只能看到 packageType 为 999 的套餐
    result = result.filter(item => item.packageType === 999)
  } else if (tenantType === '用户') {
    // 租户类型选了“用户”，强制不能看到代理(999)和测试(99)的套餐
    result = result.filter(item => item.packageType !== 999)
  }

  return result
})

/** 打开弹窗 */
const open = async (type: 'create' | 'update', id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  if (id) {
    formLoading.value = true
    try {
      formData.value = await TenantApi.getTenant(id)
      const res = await getUserByTenant(id)
      userList.value = res || []
      if (userList.value.length > 0) {
        userData.value = userList.value[0]
          ; (userData.value as any).tenantId = formData.value.id
      }
    } finally {
      formLoading.value = false
    }
  }

  packageList.value = await TenantPackageApi.getTenantPackageList()
  if (userStore.getUser.id === 1) {
    packageAgencyList.value = await TenantPackageApi.getTenantPackageListagency()
  }
}
defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  formLoading.value = true
  try {
    const data = formData.value as unknown as TenantApi.TenantVO
    if (formType.value === 'create') {
      await TenantApi.createTenant(data)
      message.success(t('common.createSuccess'))
    } else {
      await TenantApi.updateTenant(data)
      await updateRoleUser(userData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined as any,
    name: undefined,
    packageId: undefined,
    contactName: undefined,
    contactMobile: undefined,
    accountCount: undefined,
    expireTime: Date.now(),
    website: undefined,
    status: CommonStatusEnum.ENABLE,
    username: undefined,
    password: undefined,
    remark: undefined,
    aiExpireTime: undefined,
    brotherExpireTime: undefined,
    tenantType: undefined,
    parentId: undefined
  }
  userData.value = {} as any
  userList.value = [{ id: 0, aiChat: 0, bigBrother: 0, crawl: 0 } as any]

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

  formRef.value?.resetFields?.()
}

/** 切换用户 */
function changeUser(val: number) {
  userList.value.forEach((item) => {
    if (item.id === val) {
      userData.value = item
        ; (userData.value as any).tenantId = formData.value.id
    }
  })
}

/** 联动逻辑 */
watch(
  () => formData.value.aiExpireTime,
  (val) => {
    if (!val && userData.value) {
      userData.value.aiChat = 0
      userData.value.aiReplay = 0
      userData.value.webAi = 0
    }
  }
)

watch(
  () => formData.value.brotherExpireTime,
  (val) => {
    if (!val && userData.value) {
      userData.value.bigBrother = 0
    }
  }
)
</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>