<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="720px" class="tenant-dialog" destroy-on-close>
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="92px"
      class="tenant-form">
      <!-- 基础信息 -->
      <div class="form-section">
        <div class="section-title">基础信息</div>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="租户名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入租户名" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="租户套餐" prop="packageId">
              <el-select v-model="formData.packageId" class="w-full" clearable filterable placeholder="请选择租户套餐">
                <el-option v-for="item in packageList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="租户类型" prop="tenantType">
              <el-radio-group v-model="formData.tenantType" class="radio-chip">
                <el-radio value="代理">代理</el-radio>
                <el-radio value="用户">用户</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="租户状态" prop="status">
              <el-radio-group v-model="formData.status" class="radio-chip">
                <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-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="账号额度" prop="accountCount">
              <el-input-number v-model="formData.accountCount" class="w-full" :min="0" controls-position="right"
                placeholder="请输入账号额度" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="过期时间" prop="expireTime">
              <el-date-picker v-model="formData.expireTime" class="w-full" clearable placeholder="请选择过期时间" type="date"
                value-format="x" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 分润信息（代理相关） -->
      <div v-if="formData.tenantType == '代理'" class="form-section">
        <div class="section-title">分润设置</div>

        <el-row :gutter="16">
          <el-col :span="12" v-if="formData.tenantType == '代理' && userData?.tenantLevel == 0">
            <el-form-item label="分成比例" prop="profitShareRatio">
              <el-input-number v-model="formData.profitShareRatio" class="w-full" :min="0" :max="1" :step="0.01"
                controls-position="right" placeholder="例如 0.30" />
              <div class="form-help">范围：0 ~ 1（不含 0/1），支持两位小数</div>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="formData.tenantType == '代理' && userData?.tenantLevel != 0">
            <el-form-item label="返佣比例" prop="upstreamRebateRatio">
              <el-input-number v-model="formData.upstreamRebateRatio" class="w-full" :min="0" :max="1" :step="0.01"
                controls-position="right" placeholder="例如 0.20" />
              <div class="form-help">范围：0 ~ 1（可为 0，不含 1）</div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 联系信息 -->
      <div class="form-section">
        <div class="section-title">联系信息</div>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="formData.contactName" placeholder="请输入联系人" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系手机" prop="contactMobile">
              <el-input v-model="formData.contactMobile" placeholder="请输入联系手机" maxlength="11" show-word-limit
                clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="绑定域名" prop="websites">
          <el-input-tag v-model="formData.websites" placeholder="请输入绑定域名，回车添加（如 example.com）" class="w-full" />
          <div class="form-help">支持多个域名；请勿包含 http/https 前缀</div>
        </el-form-item>
      </div>

      <!-- 账号信息（仅新增时） -->
      <div v-if="formData.id === undefined" class="form-section">
        <div class="section-title">管理员账号</div>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="用户名称" prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名称" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="formData.password" placeholder="请输入用户密码" show-password type="password" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as TenantApi from '@/api/system/tenant'
import { CommonStatusEnum } from '@/utils/constants'
import * as TenantPackageApi from '@/api/system/tenantPackage'

defineOptions({ name: 'SystemTenantForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  packageId: undefined,
  contactName: undefined,
  contactMobile: undefined,
  accountCount: undefined,
  expireTime: undefined,
  websites: [],
  profitShareRatio: undefined,
  upstreamRebateRatio: 0,
  tenantType: '用户',
  status: CommonStatusEnum.ENABLE,
  // 新增专属
  username: undefined,
  password: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '租户名不能为空', trigger: 'blur' }],
  packageId: [{ required: true, message: '租户套餐不能为空', trigger: 'blur' }],
  contactName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  contactMobile: [{ max: 11, message: '手机号不能超过11位', trigger: 'blur' }],
  status: [{ required: true, message: '租户状态不能为空', trigger: 'blur' }],
  accountCount: [{ required: true, message: '账号额度不能为空', trigger: 'blur' }],
  expireTime: [{ required: true, message: '过期时间不能为空', trigger: 'blur' }],
  profitShareRatio: [
    {
      validator: (_rule, value, callback) => {
        if (formData.value.tenantType === '代理') {
          if (value === undefined || value === null || value === '') {
            callback(new Error('分成比例不能为空'))
            return
          }
          if (value <= 0 || value >= 1) {
            callback(new Error('分成比例需大于0且小于1'))
            return
          }
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  upstreamRebateRatio: [
    {
      validator: (_rule, value, callback) => {
        if (value === undefined || value === null || value === '') {
          callback()
          return
        }
        if (value < 0 || value >= 1) {
          callback(new Error('返佣比例需大于等于0且小于1'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  username: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const packageList = ref([] as TenantPackageApi.TenantPackageVO[]) // 租户套餐

/** 打开弹窗 */
const open = async (type: string, 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)
    } finally {
      formLoading.value = false
    }
  }
  // 加载套餐列表
  packageList.value = await TenantPackageApi.getTenantPackageList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) 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)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    packageId: undefined,
    contactName: undefined,
    contactMobile: undefined,
    accountCount: undefined,
    expireTime: undefined,
    websites: [],
    status: CommonStatusEnum.ENABLE,
    tenantType: '用户',
    profitShareRatio: undefined,
    upstreamRebateRatio: 0,
    username: undefined,
    password: undefined
  }
  formRef.value?.resetFields()
}
let userData = ref()
onMounted(async () => {
  userData = await TenantApi.getcurrent()
  console.log(userData.tenantLevel)
})
</script>
<style scoped>
.tenant-dialog :deep(.el-dialog__body) {
  padding: 16px 20px 4px;
}

.tenant-form {
  max-height: calc(70vh);
  overflow: auto;
  padding-right: 2px;
}

.form-section {
  padding: 12px 12px 4px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 10px;
  margin-bottom: 12px;
  background: var(--el-fill-color-blank);
}

.section-title {
  font-size: 13px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin-bottom: 10px;
  position: relative;
  padding-left: 10px;
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 2px;
  bottom: 2px;
  width: 3px;
  border-radius: 2px;
  background: var(--el-color-primary);
}

.form-help {
  font-size: 12px;
  line-height: 18px;
  color: var(--el-text-color-secondary);
  margin-top: 6px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 让 radio 更像“标签”一点 */
.radio-chip :deep(.el-radio) {
  margin-right: 14px;
}
</style>