<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
      <!-- ========== 1. 基础信息 ========== -->
      <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">
          <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="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>

      <!-- 爬虫：不受限制 -->
      <el-form-item v-if="userData.id" 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 v-if="userData.id" 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>

      <!-- ai自动化：依赖 AI 过期时间 -->
      <el-form-item v-if="userData.id" label="ai自动化" 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>

      <!-- ai回复：依赖 AI 过期时间 -->
      <el-form-item v-if="userData.id" 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>

      <!--WEB回复：依赖 AI 过期时间 -->
      <el-form-item v-if="userData.id" label="WEB客户端" 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>
      <!-- ========== 2. 套餐 & 权限 ========== -->
      <el-divider>套餐 & 权限</el-divider>
      <el-form-item label="租户套餐" prop="packageId">
        <!-- 顶层租户或无 parentId，走原来的下拉选择 -->
        <el-select v-if="(formData.parentId == 1 || formData.parentId == null) && tenantLevel == 0"
          v-model="formData.packageId" clearable placeholder="请选择租户套餐">
          <el-option v-for="item in packageList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>

        <!-- 代理租户：用功能勾选 + 套餐单选 -->
        <div v-else style="display: block;">
          <!-- 功能勾选：1=爬大哥，2=爬主播，3=AI套餐 -->
          <el-checkbox-group v-model="selectedFeatures">
            <el-checkbox :label="1">爬主播</el-checkbox>
            <el-checkbox :label="2">爬大哥</el-checkbox>
            <el-checkbox :label="3">AI套餐</el-checkbox>
            <el-checkbox :label="9">代理</el-checkbox>
          </el-checkbox-group>

          <!-- 按天数过滤：30 / 180 / 360 天 -->
          <div style="margin-top: 8px;">
            <el-radio-group v-model="selectedDays">
              <el-radio-button :label="30">30 天</el-radio-button>
              <el-radio-button :label="180">180 天</el-radio-button>
              <el-radio-button :label="365">365 天</el-radio-button>
            </el-radio-group>
          </div>
          <!-- 根据勾选结果筛选套餐，用单选框选择一个套餐 -->
          <div class="package-radio-wrapper">
            <el-radio-group v-model="formData.packageId">
              <el-radio-button v-for="item in filteredAgencyPackages" :key="item.id" :label="item.id"
                class="package-radio">

                {{ item.name }}

              </el-radio-button>
            </el-radio-group>

            <div v-if="filteredAgencyPackages.length === 0" class="package-empty-tip">
              暂无匹配套餐，请调整上方功能勾选
            </div>
          </div>

        </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 { 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'

defineOptions({ name: 'SystemTenantForm' })
const tenantLevel = ref(3)
TenantApi.getSelfTenantLevel().then(res => {
  tenantLevel.value = res.tenantLevel
  console.log(tenantLevel.value)
})
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,
  tenantType: undefined as number | undefined,
  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[])
// 代理套餐功能勾选：1=爬大哥，2=爬主播，3=AI套餐
const selectedFeatures = ref<number[]>([])
// 按套餐天数筛选：30 / 180 / 360（不选则不过滤）
const selectedDays = ref<number | null>(null)
// 二级代理套餐的 ID
const SECOND_AGENT_PACKAGE_ID = 10001
// 根据 selectedFeatures + packageAgencyList 计算可选套餐
const filteredAgencyPackages = computed(() => {
  // 1. 根据创建/编辑确定基础套餐列表
  let list: any[] = []
  if (formType.value === 'create') {
    list = packageList.value || []
  } else {
    list = packageAgencyList.value || []
  }
  if (!list.length) return []

  const selected = selectedFeatures.value

  // 2. 先按功能勾选过滤（保持你原来的逻辑）
  let result: any[] = []
  if (!selected.length) {
    // 一个功能都没勾选时，直接返回全部套餐
    result = list
  } else {
    // 有勾选时才进行过滤
    result = list.filter((item: any) => {
      const typeStr = String(item.packageType ?? '')
      // 要求选中的功能全部包含在 packageType 里
      // 例如勾选 [1,2] -> 匹配 '12'、'123' 等
      return selected.every(flag => typeStr.includes(String(flag)))
    })
  }

  // 3. 按天数过滤：item.days === 30 / 180 / 360
  if (selectedDays.value != null) {
    result = result.filter((item: any) => item.days === selectedDays.value)
  }

  // 4. 再根据租户类型进行限制
  const tenantType = formData.value.tenantType
  if (tenantType === '代理') {
    // 只能选二级代理套餐（10001）
    result = result.filter(item => item.id === SECOND_AGENT_PACKAGE_ID)
  } else if (tenantType === '租户') {
    // 租户不能选二级代理套餐
    result = result.filter(item => item.id !== SECOND_AGENT_PACKAGE_ID)
  }

  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 {
      // 1. 租户基础信息
      formData.value = await TenantApi.getTenant(id)

      // 2. 拉取租户用户列表
      const res = await getUserByTenant(id)
      userList.value = res || []

      // 3. 默认选中第一个用户（有的话）
      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
  }
  userData.value = {} as any
  userList.value = [
    {
      id: 0,
      aiChat: 0,
      bigBrother: 0,
      crawl: 0
    } as any
  ]
  // ⭐ 每次打开弹窗时都清空功能选择
  selectedFeatures.value = []

  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
    }
  })
}

/** 联动：AI 过期时间 -> AI 权限 */
watch(
  () => formData.value.aiExpireTime,
  (val) => {
    if (!val && userData.value) {
      userData.value.aiChat = 0
      userData.value.aiReplay = 0
    }
  }
)

/** 联动：爬大哥过期时间 -> bigBrother 权限 */
watch(
  () => formData.value.brotherExpireTime,
  (val) => {
    if (!val && userData.value) {
      userData.value.bigBrother = 0
    }
  }
)
</script>
<style scoped>
.package-radio-wrapper {
  margin-top: 10px;
}

/* 让按钮自动换行，并留点间隔 */
.package-radio-wrapper :deep(.el-radio-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 美化每个 radio-button 的外观（胶囊 + 内边距） */
.package-radio-wrapper :deep(.el-radio-button__inner) {
  border-radius: 999px;
  padding: 4px 10px;
  border: 1px solid #dcdfe6;
  height: 30px;
}

/* 选中状态可以稍微加粗/加边框，Element Plus 自带选中样式，这里可选 */
.package-radio-wrapper :deep(.is-active .el-radio-button__inner) {
  border-color: #409eff;
}

/* 空数据提示 */
.package-empty-tip {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}
</style>
