<template>
  <div class="app-container p-6 bg-white rounded" v-loading="loading">
    <!-- 顶部：公司认证信息 -->
    <div class="mb-10">
      <div class="section-title">公司认证信息</div>

      <div class="info-wrapper p-2 pl-6">
        <!-- 公司信息部分 -->
        <div class="company-section">
          <h3 class="font-bold text-[#1d2129] mb-6 flex items-center text-base">
            公司信息
          </h3>
          <div class="info-list space-y-4 text-sm">
            <div class="flex items-center">
              <span class="w-32 text-[#4e5969]">企业名称：</span>
              <span class="text-[#1d2129] font-medium">{{ detail.companyName || '-' }}</span>
              <el-link type="primary" :underline="false" class="ml-4" @click="copyText(detail.companyName || '')">复制</el-link>
            </div>
            <div class="flex items-center">
              <span class="w-32 text-[#4e5969]">官方邮箱：</span>
              <span class="text-[#1d2129]">{{ detail.officialAccount || '-' }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-32 text-[#4e5969]">办公地址：</span>
              <span class="text-[#1d2129]">{{ detail.officeAddress || '-' }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-32 text-[#4e5969]">统一社会信用代码：</span>
              <span class="text-[#1d2129]">{{ detail.creditCode || '-' }}</span>
            </div>
            
            <div class="flex mt-6" v-if="authLetterUrl">
              <span class="w-32 text-[#4e5969]">委托招聘证明：</span>
              <div class="flex gap-4">
                <el-image style="width: 120px; height: 80px" class="border rounded border-gray-200 bg-gray-50" :src="authLetterUrl" :preview-src-list="[authLetterUrl]" fit="contain"></el-image>
              </div>
            </div>
          </div>
        </div>

        <!-- 联系人信息部分 -->
        <div class="contact-section">
          <h3 class="font-bold text-[#1d2129] mb-6 text-base">
            联系人信息
          </h3>
          <div class="info-list space-y-4 text-sm">
            <div class="mb-6">
               <el-avatar :size="64" :src="avatarUrl || undefined" class="bg-gray-200 text-lg">
                 {{ detail.surname || '头像' }}
               </el-avatar>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-[#4e5969]">联系人：</span>
              <span class="text-[#1d2129] font-medium">{{ detail.surname || '' }}{{ detail.name || '-' }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-[#4e5969]">手机号：</span>
              <span class="text-[#1d2129]">{{ detail.mobile || '-' }}</span>
            </div>
            <div class="flex items-center">
              <span class="w-24 text-[#4e5969]">提交时间：</span>
              <span class="text-[#1d2129]">{{ detail.applyCreateTime || '-' }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部：审核信息 -->
    <div class="mb-10">
      <div class="section-title">审核信息</div>
      
      <div class="form-content">
        <!-- 已审核状态显示 -->
        <div v-if="detail.auditResult !== 0" class="flex flex-col gap-6 text-[14px] pl-6 py-4 bg-gray-50/50 rounded border border-gray-100">
          <div class="flex items-center">
            <div class="w-[100px] pr-4 text-right text-[#4e5969] shrink-0">审核结果:</div>
            <div class="text-[#1d2129]">
              <el-tag :type="detail.auditResult === 1 ? 'success' : 'danger'" effect="dark">
                {{ getAuditResultLabel(detail.auditResult) }}
              </el-tag>
            </div>
          </div>
          
          <div class="flex items-start">
            <div class="w-[100px] pr-4 text-right text-[#4e5969] shrink-0">备注:</div>
            <div class="text-[#1d2129] max-w-3xl leading-relaxed">{{ detail.auditRemark || '-' }}</div>
          </div>

          <div class="flex items-center">
            <div class="w-[100px] pr-4 text-right text-[#4e5969] shrink-0">审核时间:</div>
            <div class="text-[#1d2129]">{{ detail.auditTime || '-' }}</div>
          </div>

          <div class="flex items-center">
            <div class="w-[100px] pr-4 text-right text-[#4e5969] shrink-0">审核人:</div>
            <div class="text-[#1d2129]">{{ detail.auditBy || '-' }}</div>
          </div>
        </div>

        <!-- 待审核状态 - 显示审核表单 -->
        <div v-else class="max-w-2xl pt-4 pl-[40px] bg-gray-50/40 p-8 rounded border border-gray-100">
          <el-form :model="auditForm" label-width="80px">
            <el-form-item label="审核备注">
              <el-input 
                v-model="auditForm.remark" 
                type="textarea" 
                :rows="5" 
                placeholder="说明说明说明说明说明说明..."
              />
            </el-form-item>
          </el-form>

          <div class="flex gap-4 mt-8 pl-20">
            <el-button type="primary" @click="handleAuditPass" :loading="submitLoading" class="px-8">审核通过</el-button>
            <el-button type="danger" @click="handleAuditReject" :loading="submitLoading" class="px-8">审核驳回</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 返回按钮 -->
    <div class="mt-12 text-center pb-10">
      <el-button @click="handleBack" class="px-12 !bg-[#f2f3f5] !border-none !text-[#4e5969] hover:!bg-[#e5e6eb]">返回列表</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getAudit, auditPass, auditReject } from '@/api/system/audit';
import { listByIds } from '@/api/system/oss';

const baseApi = import.meta.env.VITE_APP_BASE_API;
import { AuditVO } from '@/api/system/audit/types';

const router = useRouter();
const route = useRoute();
const loading = ref(true);
const submitLoading = ref(false);
const detail = ref<AuditVO>({} as AuditVO);
const avatarUrl = ref('');
const authLetterUrl = ref('');
const auditForm = ref({
  remark: ''
});

const getDetail = async () => {
  loading.value = true;
  try {
    const id = route.query.id as string;
    const res = await getAudit(id);
    detail.value = res.data;

    // 获取联系人头像真实URL
    if (res.data.avatar) {
      listByIds(res.data.avatar).then(ossRes => {
        if (ossRes.data && ossRes.data.length) {
          const rawUrl = ossRes.data[0].url;
          avatarUrl.value = rawUrl.startsWith('http') ? rawUrl : baseApi + rawUrl;
        }
      });
    }

    // 获取委托招聘证明真实URL
    if (res.data.authLetter) {
      listByIds(res.data.authLetter).then(ossRes => {
        if (ossRes.data && ossRes.data.length) {
          const rawUrl = ossRes.data[0].url;
          authLetterUrl.value = rawUrl.startsWith('http') ? rawUrl : baseApi + rawUrl;
        }
      });
    }
  } catch (error) {
    ElMessage.error('获取详情失败');
  } finally {
    loading.value = false;
  }
};

const getAuditResultLabel = (result: number) => {
  const map: Record<number, string> = {
    0: '待审核',
    1: '通过',
    2: '未通过'
  };
  return map[result] || '未知';
};

const copyText = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('复制成功');
  });
};

const handleAuditPass = async () => {
  try {
    await ElMessageBox.confirm('确定要审核通过吗？', '提示', { type: 'warning' });
    submitLoading.value = true;
    await auditPass(route.query.id as string, auditForm.value.remark);
    ElMessage.success('审核通过成功');
    await getDetail();
  } catch (error: any) {
    if (error !== 'cancel') ElMessage.error('审核失败');
  } finally {
    submitLoading.value = false;
  }
};

const handleAuditReject = async () => {
  if (!auditForm.value.remark?.trim()) {
    ElMessage.warning('请输入驳回原因');
    return;
  }
  try {
    await ElMessageBox.confirm('确定要驳回此申请吗？', '提示', { type: 'warning' });
    submitLoading.value = true;
    await auditReject(route.query.id as string, auditForm.value.remark);
    ElMessage.success('审核驳回成功');
    await getDetail();
  } catch (error: any) {
    if (error !== 'cancel') ElMessage.error('操作失败');
  } finally {
    submitLoading.value = false;
  }
};

const handleBack = () => {
  router.back();
};

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

<style scoped lang="scss">
.app-container {
  min-height: calc(100vh - 84px);
  color: #1d2129;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1d2129;
  background-color: #f7f8fa;
  padding: 14px 16px;
  border-left: 3px solid #165dff;
  margin-bottom: 24px;
}

.info-wrapper {
  display: flex;
  gap: 15%;
}

.company-section {
  flex: 1;
  max-width: 600px;
}

.contact-section {
  flex: 1;
}

:deep(.el-textarea__inner) {
  border-radius: 4px;
}
</style>
