<template>
  <div class="container-box">
    <div class="header-bar">
      <h2>我的域名</h2>
      <el-button type="primary" @click="dialogVisible = true">
        <el-icon><Plus /></el-icon>
        申请二级域名
      </el-button>
    </div>

    <el-divider></el-divider>

    <!-- 我的域名列表 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      border
      v-loading="loading"
      element-loading-text="正在加载..."
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="sub_domain" label="二级域名前缀" width="150" />
      <el-table-column prop="main_domain" label="主域名" min-width="150" />
      <el-table-column prop="full_domain" label="完整域名" min-width="200">
        <template #default="scope">
          <el-link
            type="primary"
            :href="'http://' + scope.row.full_domain"
            target="_blank"
          >
            {{ scope.row.full_domain }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">审核中</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success"
            >已生效</el-tag
          >
          <el-tag v-else type="danger">已禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="申请时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button
            size="small"
            text
            type="primary"
            @click="handleCopy(scope.row.full_domain)"
          >
            复制
          </el-button>
          <el-button
            size="small"
            text
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 申请域名弹窗 -->
    <el-dialog v-model="dialogVisible" title="申请二级域名" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="选择主域名" prop="main_domain">
          <el-select
            v-model="form.main_domain"
            placeholder="请选择主域名"
            style="width: 100%"
          >
            <el-option
              v-for="item in domainList"
              :key="item.main_domain"
              :label="item.main_domain"
              :value="item.main_domain"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="二级前缀" prop="sub_domain">
          <el-input v-model="form.sub_domain" placeholder="请输入二级域名前缀">
            <template #append>{{
              form.main_domain ? "." + form.main_domain : ""
            }}</template>
          </el-input>
          <div class="form-tip">
            只能包含字母、数字和连字符，不能以连字符开头或结尾
          </div>
        </el-form-item>
        <el-form-item label="预览">
          <div class="domain-preview">
            {{
              form.sub_domain
                ? form.sub_domain + "." + (form.main_domain || "example.com")
                : "请填写上方信息"
            }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading"
          >提交申请</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import {
  getMyDomains,
  applyTenantDomain,
  getEnabledDomains,
  deleteTenantDomain,
} from "@/api/domain";
import { useAuthStore } from "@/stores/auth";

const authStore = useAuthStore();
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const formRef = ref();

const tableData = ref<any[]>([]);
const domainList = ref<any[]>([]);

const form = reactive({
  main_domain: "",
  sub_domain: "",
});

const rules = {
  main_domain: [{ required: true, message: "请选择主域名", trigger: "change" }],
  sub_domain: [
    { required: true, message: "请输入二级域名前缀", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$/,
      message: "格式不正确",
      trigger: "blur",
    },
  ],
};

const fetchDomains = async () => {
  loading.value = true;
  try {
    // 获取我的域名列表
    const res = await getMyDomains({ tid: authStore.user.tid });
    if (res.code === 200) {
      tableData.value = res.data || [];
    }

    // 获取可选主域名
    const domainRes = await getEnabledDomains();
    if (domainRes.code === 200) {
      domainList.value = domainRes.data || [];
    }
  } finally {
    loading.value = false;
  }
};

const handleSubmit = async () => {
  await formRef.value.validate();
  submitLoading.value = true;
  try {
    const res = await applyTenantDomain({
      tid: authStore.user.tid,
      main_domain: form.main_domain,
      sub_domain: form.sub_domain,
    });
    if (res.code === 200) {
      ElMessage.success(res.msg);
      dialogVisible.value = false;
      form.sub_domain = "";
      fetchDomains();
    } else {
      ElMessage.error(res.msg || "申请失败");
    }
  } finally {
    submitLoading.value = false;
  }
};

const handleCopy = (domain: string) => {
  navigator.clipboard.writeText("http://" + domain);
  ElMessage.success("链接已复制到剪贴板");
};

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除域名 "${row.full_domain}" 吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    const res = await deleteTenantDomain(row.id);
    if (res.code === 200) {
      ElMessage.success("删除成功");
      fetchDomains();
    } else {
      ElMessage.error(res.msg || "删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
    }
  }
};

onMounted(() => {
  fetchDomains();
});
</script>

<style lang="less" scoped>
.container-box {
  padding: 20px;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h2 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.domain-preview {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  color: #409eff;
}
</style>
