<!-- src/views/EnterpriseRealNameAuth.vue -->
<template>
  <div class="enterprise-real-name-auth">
    <!-- 步骤条 -->
    <a-steps :current="0" class="steps">
      <a-step title="填写证件信息" />
      <a-step title="后台审核" />
      <a-step title="完成认证" />
    </a-steps>

    <!-- 表单 -->
    <a-form
      ref="formRef"
      :model="formState"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      layout="horizontal"
      class="auth-form"
    >
      <!-- 企业信息 -->
      <div class="section-title">企业信息</div>

      <a-alert
        message="企业信息、法人/被授权人信息仅用于进行实名认证，不会泄露您的信息"
        type="warning"
        show-icon
        style="margin-bottom: 24px"
      />

      <a-form-item
        label="企业证件类型："
        name="certType"
        :rules="[{ required: true, message: '请选择企业证件类型' }]"
      >
        <a-select
          v-model:value="formState.certType"
          placeholder="请选择"
          style="width: 400px"
        >
          <a-select-option value="business_license">营业执照</a-select-option>
          <!-- 可扩展其他类型 -->
        </a-select>
      </a-form-item>

      <a-form-item
        label="上传企业证件附件："
        :rules="[{ required: true, validator: validateBusinessLicense }]"
      >
        <div class="upload-area">
          <a-upload
            name="file"
            list-type="picture-card"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            @change="handleBusinessLicenseChange"
            accept="image/png,image/jpeg"
          >
            <div class="upload-placeholder">
              <UserOutlined />
              <div style="margin-top: 8px">企业法人营业执照</div>
            </div>
          </a-upload>
          <div v-if="formState.businessLicenseUrl" class="upload-preview">
            <img :src="formState.businessLicenseUrl" alt="营业执照" />
          </div>
        </div>
        <div class="upload-tips">支持 jpg、jpeg、png 格式图片，大小不超过 10M</div>
      </a-form-item>

      <a-form-item
        label="企业名称："
        name="enterpriseName"
        :rules="[{ required: true, message: '请输入企业名称' }]"
      >
        <a-input
          v-model:value="formState.enterpriseName"
          placeholder="请输入企业名称"
          style="width: 400px"
        />
      </a-form-item>

      <a-form-item
        label="统一社会信用代码："
        name="creditCode"
        :rules="[
          { required: true, message: '请输入统一社会信用代码' },
          { pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, message: '请输入有效的统一社会信用代码' }
        ]"
      >
        <a-input
          v-model:value="formState.creditCode"
          placeholder="请输入统一社会信用代码"
          style="width: 400px"
        />
      </a-form-item>

      <!-- 法人/被授权人信息 -->
      <div class="section-title">法人/被授权人信息</div>

      <a-form-item
        label="请选择您的身份："
        name="identity"
        :rules="[{ required: true, message: '请选择身份' }]"
      >
        <a-radio-group v-model:value="formState.identity">
          <a-radio value="legal_representative">法定代表人</a-radio>
          <a-radio value="authorized_person">被授权人</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 身份证正反面 -->
      <a-form-item
        label="上传身份证件附件："
        :rules="[
          { required: true, validator: validateIdCardFront },
          { required: true, validator: validateIdCardBack }
        ]"
      >
        <div class="id-card-uploads">
          <!-- 正面 -->
          <div class="upload-area">
            <a-upload
              name="file"
              list-type="picture-card"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleIdCardFrontChange"
              accept="image/png,image/jpeg"
            >
              <div class="upload-placeholder">
                <IdcardOutlined />
                <div style="margin-top: 8px">身份证件正面</div>
              </div>
            </a-upload>
            <div v-if="formState.idCardFrontUrl" class="upload-preview">
              <img :src="formState.idCardFrontUrl" alt="身份证正面" />
            </div>
          </div>

          <!-- 背面 -->
          <div class="upload-area">
            <a-upload
              name="file"
              list-type="picture-card"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              @change="handleIdCardBackChange"
              accept="image/png,image/jpeg"
            >
              <div class="upload-placeholder">
                <IdcardOutlined />
                <div style="margin-top: 8px">身份证件背面</div>
              </div>
            </a-upload>
            <div v-if="formState.idCardBackUrl" class="upload-preview">
              <img :src="formState.idCardBackUrl" alt="身份证背面" />
            </div>
          </div>
        </div>
        <div class="upload-tips">支持 jpg、jpeg、png 格式图片，大小不超过 10M</div>
      </a-form-item>

      <a-form-item
        label="姓名："
        name="name"
        :rules="[{ required: true, message: '请输入姓名' }]"
      >
        <a-input
          v-model:value="formState.name"
          placeholder="请输入姓名"
          style="width: 400px"
        />
      </a-form-item>

      <a-form-item
        label="证件号码："
        name="idNumber"
        :rules="[
          { required: true, message: '请输入证件号码' },
          { pattern: /^\d{17}[\dXx]$/, message: '请输入有效的18位身份证号码' }
        ]"
      >
        <a-input
          v-model:value="formState.idNumber"
          placeholder="请输入证件号码"
          style="width: 400px"
        />
      </a-form-item>

      <!-- 协议同意 -->
      <a-form-item :wrapper-col="{ offset: 4 }">
        <a-checkbox v-model:checked="formState.agreed">
          同意
          <a href="/docs/real_name_cert/" target="_blank">《AutoDL实名认证服务协议》</a>
          <a href="/docs/privacy_policy/" target="_blank">《隐私政策》</a>
          ，请务必提供真实信息，AutoDL算力云有权自行或委托第三方，审查您提供的信息是否真实/有效，若提供虚假信息，由此带来的后果由您承担。
        </a-checkbox>
      </a-form-item>

      <!-- 操作按钮 -->
      <a-form-item :wrapper-col="{ offset: 4 }">
        <a-button type="primary" @click="handleSubmit">确认提交</a-button>
        <a-button style="margin-left: 12px" @click="handleCancel">取消</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  UploadChangeParam,
  UploadFile
} from 'vue';
import {
  message,
  FormInstance,
  UploadProps
} from 'ant-design-vue';
import {
  UserOutlined,
  IdcardOutlined
} from '@ant-design/icons-vue';

// 表单引用
const formRef = ref<FormInstance>();

// 表单数据
interface FormState {
  certType: string | null;
  businessLicenseUrl: string | null;
  enterpriseName: string;
  creditCode: string;
  identity: 'legal_representative' | 'authorized_person' | null;
  idCardFrontUrl: string | null;
  idCardBackUrl: string | null;
  name: string;
  idNumber: string;
  agreed: boolean;
}

const formState = reactive<FormState>({
  certType: null,
  businessLicenseUrl: null,
  enterpriseName: '',
  creditCode: '',
  identity: null,
  idCardFrontUrl: null,
  idCardBackUrl: null,
  name: '',
  idNumber: '',
  agreed: false
});

// 文件大小限制：10MB
const MAX_FILE_SIZE = 10 * 1024 * 1024;

// 上传前校验
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isLt10M = file.size < MAX_FILE_SIZE;
  if (!isLt10M) {
    message.error('文件大小不能超过 10MB!');
  }
  const isValidType = ['image/jpeg', 'image/png'].includes(file.type);
  if (!isValidType) {
    message.error('仅支持 JPG/PNG 格式!');
  }
  return isLt10M && isValidType;
};

// 处理营业执照上传
const handleBusinessLicenseChange = (info: UploadChangeParam<UploadFile>) => {
  if (info.file.status === 'done') {
    // 模拟获取 URL（实际应调用上传接口）
    const url = URL.createObjectURL(info.file.originFileObj!);
    formState.businessLicenseUrl = url;
  }
};

// 处理身份证正面
const handleIdCardFrontChange = (info: UploadChangeParam<UploadFile>) => {
  if (info.file.status === 'done') {
    const url = URL.createObjectURL(info.file.originFileObj!);
    formState.idCardFrontUrl = url;
  }
};

// 处理身份证背面
const handleIdCardBackChange = (info: UploadChangeParam<UploadFile>) => {
  if (info.file.status === 'done') {
    const url = URL.createObjectURL(info.file.originFileObj!);
    formState.idCardBackUrl = url;
  }
};

// 自定义校验函数
const validateBusinessLicense = () => {
  if (!formState.businessLicenseUrl) {
    return Promise.reject(new Error('请上传企业证件'));
  }
  return Promise.resolve();
};

const validateIdCardFront = () => {
  if (!formState.idCardFrontUrl) {
    return Promise.reject(new Error('请上传身份证正面'));
  }
  return Promise.resolve();
};

const validateIdCardBack = () => {
  if (!formState.idCardBackUrl) {
    return Promise.reject(new Error('请上传身份证背面'));
  }
  return Promise.resolve();
};

// 提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validateFields();
    if (!formState.agreed) {
      message.error('请阅读并同意协议');
      return;
    }
    message.success('提交成功！');
    // TODO: 调用 API 提交表单
  } catch (error) {
    console.log('Validation failed:', error);
  }
};

// 取消
const handleCancel = () => {
  // TODO: 返回上一页或重置
  message.info('已取消');
};
</script>

<style scoped>
.enterprise-real-name-auth {
  padding: 24px;
  background-color: #fff;
  min-height: 100vh;
}

.steps {
  max-width: 800px;
  margin-bottom: 32px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 24px 0 16px;
}

.upload-area {
  display: inline-block;
  margin-right: 24px;
  position: relative;
}

.upload-placeholder {
  text-align: center;
  color: #999;
}

.upload-placeholder i {
  font-size: 24px;
  margin-bottom: 8px;
}

.upload-preview {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.upload-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.id-card-uploads {
  display: flex;
  gap: 24px;
}

.upload-tips {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
}

/* 响应式 */
@media (max-width: 768px) {
  .auth-form :deep(.ant-form-item-label) {
    text-align: left;
  }

  .id-card-uploads {
    flex-direction: column;
  }

  .upload-area {
    margin-right: 0;
  }
}
</style>



