<template>
    <el-drawer
      v-model="visible"
      title="租户详细信息"
      size="1000px"
      @closed="handleClosed"
    >
      <div v-loading="loading" class="detail-container">
        <el-descriptions
          :column="2"
          :label-width="110"
          border
          class="tenant-detail-descriptions"
        >
          <el-descriptions-item label="租户名称">
            <span class="detail-value">{{ detailData.tenant_name }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="租户编码">
            <el-tag type="info" effect="plain">{{ detailData.tenant_code }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            {{ detailData.contact_person || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ detailData.contact_phone || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="电子邮箱">
            {{ detailData.contact_email || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="租户地址" :span="2">
            {{ detailData.address || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="租户状态">
            <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
              {{ detailData.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ detailData.create_time || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="users-section">
          <div class="section-title">租户用户列表</div>
          <el-table :data="tenantUsers" v-loading="usersLoading" border style="width: 100%">
            <el-table-column prop="account" label="用户名" min-width="140" align="center" />
            <el-table-column prop="name" label="姓名" min-width="120" align="center" />
            <el-table-column prop="phone" label="手机号" min-width="140" align="center" />
            <el-table-column prop="email" label="邮箱" min-width="180" align="center" />
            <el-table-column prop="status" label="状态" width="90" align="center">
              <template #default="{ row }">
                <el-tag :type="Number(row.status) === 1 ? 'success' : 'danger'">
                  {{ Number(row.status) === 1 ? "启用" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140" align="center" fixed="right">
              <template #default="{ row }">
                <el-button text type="primary" @click="openPasswordDialog(row)">
                  修改密码
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
  
        <div class="footer-actions">
          <el-button @click="visible = false">关闭</el-button>
        </div>
      </div>
    </el-drawer>

    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="420px" destroy-on-close>
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="90px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" show-password placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input v-model="passwordForm.password2" type="password" show-password placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="passwordSubmitting" @click="submitPassword">确定</el-button>
      </template>
    </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive } from 'vue';
  import { ElMessage } from "element-plus";
  import { getTenantDetail } from '@/api/tenant';
  import { getTenantUserList, editTenantUser } from "@/api/tenantUser";
  
  const visible = ref(false);
  const loading = ref(false);
  const usersLoading = ref(false);
  const detailData = ref<any>({});
  const tenantUsers = ref<any[]>([]);

  const passwordDialogVisible = ref(false);
  const passwordSubmitting = ref(false);
  const currentTenantUserId = ref<number | null>(null);
  const passwordFormRef = ref();
  const passwordForm = reactive({
    password: "",
    password2: "",
  });

  const passwordRules = {
    password: [
      { required: true, message: "请输入新密码", trigger: "blur" },
      { min: 6, message: "密码至少 6 位", trigger: "blur" },
    ],
    password2: [
      { required: true, message: "请再次输入新密码", trigger: "blur" },
      {
        validator: (_rule: any, value: string, callback: any) => {
          if (!value) return callback(new Error("请再次输入新密码"));
          if (value !== passwordForm.password) return callback(new Error("两次密码不一致"));
          callback();
        },
        trigger: "blur",
      },
    ],
  };

  const openPasswordDialog = (row: any) => {
    currentTenantUserId.value = Number(row?.id || 0) || null;
    passwordForm.password = "";
    passwordForm.password2 = "";
    passwordDialogVisible.value = true;
  };

  const submitPassword = async () => {
    if (!passwordFormRef.value || !currentTenantUserId.value) return;
    await passwordFormRef.value.validate();

    passwordSubmitting.value = true;
    try {
      const res = await editTenantUser(currentTenantUserId.value, { password: passwordForm.password });
      if (res.code === 200) {
        ElMessage.success("密码修改成功");
        passwordDialogVisible.value = false;
      } else {
        ElMessage.error(res.msg || "密码修改失败");
      }
    } finally {
      passwordSubmitting.value = false;
    }
  };
  
  // 暴露给父组件的方法
  const open = async (id: number) => {
    visible.value = true;
    loading.value = true;
    usersLoading.value = true;
    try {
      const [detailRes, usersRes] = await Promise.all([
        getTenantDetail(id),
        getTenantUserList({ tid: id }),
      ]);

      if (detailRes.code === 200) {
        detailData.value = detailRes.data;
      }
      if (usersRes?.code === 200) {
        tenantUsers.value = usersRes?.data?.list || usersRes?.data || [];
      } else {
        tenantUsers.value = [];
      }
    } catch (error) {
      console.error('获取详情失败', error);
      tenantUsers.value = [];
    } finally {
      loading.value = false;
      usersLoading.value = false;
    }
  };
  
  const handleClosed = () => {
    detailData.value = {};
    tenantUsers.value = [];
  };
  
  // 必须暴露给外部
  defineExpose({ open });
  </script>
  
  <style scoped>
  .detail-container {
    padding: 10px 20px;
  }
  .detail-value {
    font-weight: bold;
    color: #333;
  }
  .footer-actions {
    margin-top: 30px;
    display: flex;
    justify-content: flex-end;
  }
  .users-section {
    margin-top: 20px;
  }
  .section-title {
    margin-bottom: 12px;
    font-size: 15px;
    font-weight: 600;
    color: #303133;
  }
  :deep(.el-descriptions__label) {
    width: 120px;
    background-color: #f5f7fa;
  }

  .tenant-detail-descriptions :deep(.el-descriptions__table) {
    width: 100%;
    table-layout: fixed;
  }
  </style>