<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="套餐名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入套餐名" />
      </el-form-item>

      <el-form-item label="租户状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="0">正常</el-radio>
          <el-radio :value="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>

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

      <!-- ✅ 改成树形菜单选择 -->
      <el-form-item label="菜单权限" prop="menuIds">
        <el-card class="w-full h-400px !overflow-y-scroll" shadow="never">
          <template #header>
            全选/全不选：
            <el-switch v-model="treeNodeAll" active-text="是" inactive-text="否" inline-prompt
              @change="handleCheckedTreeNodeAll" />
            &nbsp;全部展开/折叠：
            <el-switch v-model="menuExpand" active-text="展开" inactive-text="折叠" inline-prompt
              @change="handleCheckedTreeExpand" />
          </template>
          <el-tree ref="treeRef" :data="menuOptions" :props="defaultProps" empty-text="加载中，请稍候" node-key="id"
            show-checkbox />
        </el-card>
      </el-form-item>

      <el-form-item label="套餐天数" prop="days">
        <el-input v-model="formData.days" placeholder="请输入套餐天数" />
      </el-form-item>
      <el-form-item label="套餐价格" prop="price">
        <el-input v-model="formData.price" placeholder="请输入套餐价格" />
      </el-form-item>
      <!-- 爬大哥：必须先选“爬大哥过期时间” -->
      <el-form-item label="爬大哥">
        <el-radio-group v-model="formData.brotherClient">
          <el-radio :value="1">开启</el-radio>
          <el-radio :value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- ai自动化：必须先选“AI过期时间” -->
      <el-form-item label="爬主播">
        <el-radio-group v-model="formData.hostslClient">
          <el-radio :value="1">开启</el-radio>
          <el-radio :value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- ai回复：必须先选“AI过期时间” -->
      <el-form-item label="AI客户端">
        <el-radio-group v-model="formData.aiClient">
          <el-radio :value="1">开启</el-radio>
          <el-radio :value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- ai回复：必须先选“AI过期时间” -->
      <el-form-item label="AI回复">
        <el-radio-group v-model="formData.aiReplay">
          <el-radio :value="1">开启</el-radio>
          <el-radio :value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- WEB回复：必须先选“AI过期时间” -->
      <el-form-item label="WEB客户端">
        <el-radio-group v-model="formData.webAi">
          <el-radio :value="1">开启</el-radio>
          <el-radio :value="0">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="套餐类型" prop="packageType">
        <el-input v-model="formData.packageType" placeholder="请输入套餐类型" />
      </el-form-item>
    </el-form>

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

<script setup lang="ts">
import { TenantAgencyPackageApi, TenantAgencyPackageVO } from '@/api/system/tenantagencypackage'
import * as MenuApi from '@/api/system/menu'
import { defaultProps, handleTree } from '@/utils/tree'
import { ElTree } from 'element-plus'

/** 代理租户套餐 表单 */
defineOptions({ name: 'TenantAgencyPackageForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref<'create' | 'update' | string>('')

const formData = ref({
  id: undefined as number | undefined,
  name: undefined as string | undefined,
  status: 0 as 0 | 1 | undefined,     // 默认正常
  remark: undefined as string | undefined,
  menuIds: [] as number[],            // ✅ 改成数组
  days: undefined as number | undefined,
  price: undefined as number | undefined,
  hostslClient: undefined as number | undefined,
  brotherClient: undefined as number | undefined,
  aiClient: undefined as number | undefined,
  aiReplay: undefined as number | undefined,
  webAi: undefined as number | undefined,
  packageType: undefined as string | undefined

})

const formRules = reactive({
  name: [{ required: true, message: '套餐名不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '租户状态不能为空', trigger: 'change' }],
  // menuIds: [{ required: true, message: '关联的菜单编号不能为空', trigger: 'change' }], // ✅ 校验菜单
  days: [{ required: true, message: '套餐天数不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '套餐价格不能为空', trigger: 'blur' }]
})
const formRef = ref()

// ✅ 菜单树相关
const menuOptions = ref<any[]>([])
const menuExpand = ref(false)
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeNodeAll = ref(false)

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

  // 先加载菜单树数据（一定要先有数据，后 setChecked）
  formLoading.value = true
  try {
    const menus = await MenuApi.getSimpleMenusList()
    menuOptions.value = handleTree(menus)
  } finally {
    formLoading.value = false
  }

  // 编辑：回显数据并勾选
  if (id) {
    formLoading.value = true
    try {
      const data = await TenantAgencyPackageApi.getTenantAgencyPackage(id)
      formData.value = {
        ...formData.value,
        ...data,
        menuIds: Array.isArray(data.menuIds) ? data.menuIds : []
      }
      // 勾选已有关联
      formData.value.menuIds.forEach((mid: number) => {
        treeRef.value?.setChecked(mid, true, false)
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  // 1. 先做表单校验
  await formRef.value.validate()

  // 2. 从树组件拿选中的菜单 id（包含半选）
  const checked = (treeRef.value?.getCheckedKeys(false) || []) as number[]
  const half = (treeRef.value?.getHalfCheckedKeys() || []) as number[]
  const menuIds = Array.from(new Set([...checked, ...half])) // 去重一下

  // 3. 把 menuIds 塞回 formData（或者直接合并到 data 里）
  formData.value.menuIds = menuIds

  formLoading.value = true
  try {
    // 4. 组装真正发给后端的参数
    const data = {
      ...(formData.value as any),
      menuIds // ✅ 确保有这个字段
    } as TenantAgencyPackageVO
    if (formType.value === 'create') {
      await TenantAgencyPackageApi.createTenantAgencyPackage(data)
      message.success(t('common.createSuccess'))
    } else {
      await TenantAgencyPackageApi.updateTenantAgencyPackage(data)
      message.success(t('common.updateSuccess'))
    }

    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = async () => {
  treeNodeAll.value = false
  menuExpand.value = false
  formData.value = {
    id: undefined,
    name: undefined,
    status: 0,
    remark: undefined,
    menuIds: [],          // ✅ 清空
    days: undefined,
    price: undefined,
    hostslClient: undefined,
    brotherClient: undefined,
    aiClient: undefined,
    aiReplay: undefined,
    packageType: undefined
  }
  treeRef.value?.setCheckedNodes([])
  formRef.value?.resetFields()
}

/** 全选/全不选 */
const handleCheckedTreeNodeAll = () => {
  treeRef.value?.setCheckedNodes(treeNodeAll.value ? menuOptions.value : [])
}

/** 展开/折叠全部 */
const handleCheckedTreeExpand = () => {
  const nodes = (treeRef.value as any)?.store?.nodesMap
  if (!nodes) return
  for (const key in nodes) {
    if (Object.prototype.hasOwnProperty.call(nodes, key)) {
      nodes[key].expanded = menuExpand.value
    }
  }
}
</script>
