<template>
  <div class="register-pages">
    <div class="register-bos">
      <img @click="onPath('/')" class="head-img" src="@/assets/images/head.png" alt="" />
      <div class="register-login flex-row-between">
        <div></div>
        <div @click="goLogin">
          <span>已有账号？直接</span>
          <span class="zhu">登录>></span>
        </div>
      </div>
      <div class="progress-bos">
        <div class="progress-bar" :class="nextNum == 1 ? 'hig1' : 'hig2'">
          <div>01、基本资料</div>
        </div>
        <div class="progress-bar progress-bar2" :class="nextNum == 4 ? 'hig1' : ''">
          <div>02、完成</div>
        </div>
      </div>
      <template v-if="nextNum == 1">
        <div class="form-bos">
          <div class="form-title flex-row-start">
            <div class="star">*</div>
            <div>姓名</div>
          </div>
          <el-input style="width: 448px" v-model="form.purchaseName" placeholder="请输入姓名" />
          <div class="form-tip">请输入采购人全名，方便与您联系！</div>
        </div>
        <div class="form-bos" style="margin-top: 8px">
          <div class="form-title flex-row-start">
            <div class="star">*</div>
            <div>手机号码</div>
          </div>
          <el-input :maxlength="11" style="width: 448px" v-model="form.purchasePhone" placeholder="请输入手机号码">
            <template #suffix>
              <span @click="sendSmsCode" :class="['code', countdown > 0 ? 'disabled' : '']">
                {{ codeText }}
              </span>
            </template>
          </el-input>
        </div>
        <div class="form-bos form-bos1">
          <div class="form-title flex-row-start">
            <div class="star">*</div>
            <div>验证码</div>
          </div>
          <el-input style="width: 448px" v-model="form.code" placeholder="请输入验证码" />
        </div>
        <div class="form-bos form-bos1">
          <div class="form-title flex-row-start">
            <div class="star">*</div>
            <div>密码</div>
          </div>
          <el-input type="password" show-password style="width: 448px" v-model="form.password" placeholder="请输入密码" />
        </div>
        <div class="form-bos form-bos1">
          <div class="form-title flex-row-start">
            <div class="star">*</div>
            <div>请再次输入密码</div>
          </div>
          <el-input type="password" show-password style="width: 448px" v-model="form.confirmPassword" placeholder="请输入密码" />
        </div>
      </template>
      <template v-if="nextNum == 2">
        <div class="register-success flex-column-center">
          <img src="@/assets/images/breg.png" alt="" />
          <div class="success-text">您的账户还在审核中，如有疑问，请致电{{ servicePhone }}</div>
          <el-button @click="goLogin" type="primary">返回登录</el-button>
        </div>
      </template>
      <div class="agreement flex-row-start" v-if="nextNum == 1">
        <el-checkbox v-model="radio" />
        <span class="agreement1">我已阅读并同意</span>
        <span class="agreement2" @click="openDialog">《用户服务协议》</span>
      </div>
    </div>
    <div class="pay-foot" v-if="nextNum == 1">
      <div class="foot-bos">
        <el-button @click="nextStep" class="bnt2" type="primary" :loading="loading">提交并完成注册</el-button>
        <el-button @click="onPath('/breg')" v-if="nextNum == 1" class="bnt1">企业注册</el-button>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      title="《用户服务协议》"
      width="50%"
      :before-close="
        () => {
          dialogVisible = false;
        }
      "
    >
      <div>
        <div v-html="content"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="onAgree">同意</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { smsCode, selectBusinessByCustomerName, selfRegister, selectByPhone, getPlatformConfigList } from '@/api/breg/index';
import { onUnmounted } from 'vue';
import { onPath } from '@/utils/siteConfig';
const nextNum = ref<any>(1);
const codeText = ref<string>('发送验证码');
const countdown = ref<number>(0);
const timer = ref<any>(null);
const enterprise = ref<any>({});
const loading = ref(false);
const form = ref<any>({
  purchaseName: '',
  purchasePhone: '',
  code: '',
  password: '',
  confirmPassword: '',
  customerName: ''
});
const dialogVisible = ref(false);
const content = ref('');
const servicePhone = ref<any>('');

// 启动倒计时
const startCountdown = () => {
  countdown.value = 60;
  codeText.value = `${countdown.value}s 后重新发送`;

  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value > 0) {
      codeText.value = `${countdown.value}s 后重新发送`;
    } else {
      clearInterval(timer.value);
      timer.value = null;
      codeText.value = '发送验证码';
    }
  }, 1000);
};

// 获取验证码
const sendSmsCode = () => {
  // 防止倒计时期间重复点击
  if (countdown.value > 0) return;

  const phone = form.value.purchasePhone;

  // 1. 基础格式校验
  if (!validateMobile(phone)) {
    ElMessage({
      message: '请输入正确的手机号码',
      type: 'warning'
    });
    return;
  }

  // 2. 【新增】先调用接口查询用户是否存在
  selectByPhone(phone, '3')
    .then((res: any) => {
      // --- 后端返回 200 ---
      // 根据你的后端逻辑：返回 200 代表 "用户不存在" (R.ok)，允许注册
      if (res.code === 200) {
        // 手机号可用，继续执行发送验证码逻辑
        smsCode({ phonenumber: phone })
          .then((smsRes: any) => {
            if (smsRes.code === 200) {
              ElMessage({
                message: '验证码已发送',
                type: 'success'
              });
              startCountdown(); // 开始倒计时
            } else {
              // 发送短信接口业务失败
              ElMessage.error(smsRes.msg || '发送验证码失败');
            }
          })
          .catch((err: any) => {
            // 发送短信接口网络错误或异常
            ElMessage.error(err.msg || '发送验证码请求异常');
          });
      } else {
      }
    })
    .catch((error: any) => {
      // --- 后端返回非 200 (进入 catch) ---
      // 根据你的后端逻辑：返回 fail 代表 "用户已存在" (R.fail("该手机号已注册"))
      const msg = error.msg || '该手机号已注册，请直接登录';

      ElMessage({
        message: msg,
        type: 'warning' // 或者使用 'error'
      });
    });
};

// 验证手机号
const validateMobile = (phone: any) => {
  const reg = /^1[3-9]\d{9}$/;
  return reg.test(phone);
};

const nextStep = () => {
  if (nextNum.value == 1) {
    if (!radio.value) {
      ElMessage({
        message: '请勾选协议内容~',
        type: 'warning'
      });
      return;
    }
    const errorMsg = {
      purchaseName: '请输入姓名',
      purchasePhone: '请输入手机号码',
      code: '请输入验证码',
      password: '请输入密码',
      confirmPassword: '请再次输入密码'
    };
    let next1 = true;
    Object.keys(errorMsg).forEach((key) => {
      if ((form.value[key] == '' || form.value[key] == undefined || form.value[key] == null) && next1) {
        next1 = false;
        ElMessage({
          message: `${errorMsg[key]}`,
          type: 'warning'
        });
        return;
      }
    });
    if (!next1) return;
    if (form.value.password != form.value.confirmPassword) {
      ElMessage({
        message: `密码不一致`,
        type: 'warning'
      });
      return;
    }
    loading.value = true;
    selfRegister(form.value)
      .then((res: any) => {
        loading.value = false;
        if (res.code == 200) {
          nextNum.value = 2;
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }
};

const goLogin = () => {
  onPath('/login');
};

const radio = ref<any>(false);

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});

const openDialog = () => {
  dialogVisible.value = true;
};

const onAgree = () => {
  radio.value = true;
  dialogVisible.value = false;
};

getPlatformConfigList({ configKey: 'customerLoginAgreement' }).then((res) => {
  if (res.code == 200) {
    if (res.rows && res.rows.length > 0) {
      content.value = res.rows[0].value;
    }
  }
});

getPlatformConfigList({ configKey: 'servicePhone' }).then((res) => {
  if (res.code == 200) {
    if (res.rows && res.rows.length > 0) {
      servicePhone.value = res.rows[0].value;
    }
  }
});
</script>

<style lang="scss" scoped>
.register-pages {
  width: 100%;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;

  .register-bos {
    flex: 1;
    width: 100%;
    min-width: 1200px;
    max-width: 1500px;
    margin: 0 auto;
    padding-top: 20px;

    .head-img {
      width: 185px;
      height: 90px;
    }

    .register-login {
      font-weight: 400;
      font-size: 14px;
      color: #101828;
      margin-top: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #e5e7eb;

      .zhu {
        color: #e7000b;
        cursor: pointer;
      }
    }

    .progress-bos {
      padding: 20px;
      display: flex;
      margin-bottom: 24px;

      .progress-bar {
        width: 320px;
        height: 40px;
        background: #f7f8fa;
        font-weight: 500;
        font-size: 16px;
        line-height: 40px;
        padding-left: 16px;
        color: #4e5969;
        position: relative;

        &.hig1 {
          background: #e7000b;
          color: #ffffff;
        }

        &.hig2 {
          background: #ffe8e8;
          color: #1d2129;
        }

        .triangle10 {
          position: absolute;
          width: 0;
          height: 0;
          border-left: 20px solid transparent;
          /* 左边透明 */
          border-right: 20px solid transparent;
          /* 右边透明 */
          border-bottom: 20px solid #f7f8fa;
          /* 底部边为实际显示的三角形部分 */
          transform: rotate(90deg);
          /* 向左旋转90度 */
          top: 10px;
          right: -30px;
          transform-origin: 50% 50%;
          /* 设置旋转中心点在元素的中心 */
          z-index: 3;
        }

        .triangle20 {
          position: absolute;
          width: 0;
          height: 0;
          border-left: 20px solid transparent;
          /* 左边透明 */
          border-right: 20px solid transparent;
          /* 右边透明 */
          border-bottom: 20px solid #ffffff;
          /* 底部边为实际显示的三角形部分 */
          transform: rotate(90deg);
          /* 向左旋转90度 */
          top: 10px;
          right: -35px;
          transform-origin: 50% 50%;
          /* 设置旋转中心点在元素的中心 */
          z-index: 2;
        }
      }

      .progress-bar2 {
        width: 354px;
      }
    }

    .form-bos {
      padding-left: 20px;

      // :deep(.el-input__wrapper) {
      //   border: none;
      //   box-shadow: none;
      //   outline: none;
      //   background: #f4f6f8;
      // }

      .form-title {
        font-size: 14px;
        color: #1d2129;
        margin-bottom: 8px;

        .star {
          width: 10px;
          color: #f53f3f;
        }
      }

      .form-tip {
        font-size: 12px;
        color: #86909c;
        margin-top: 4px;
      }

      .code {
        font-size: 14px;
        color: #e7000b;
        cursor: pointer;

        &.disabled {
          color: #999;
          cursor: not-allowed;
        }
      }
    }

    .form-bos1 {
      margin-top: 30px;
    }

    .agreement {
      padding-left: 20px;
      margin-top: 30px;
      font-size: 13px;

      .agreement1 {
        color: #999999;
        margin-left: 5px;
      }

      .agreement2 {
        color: #e7000b;
        cursor: pointer;
      }
    }
  }

  .pay-foot {
    width: 100%;
    height: 82px;
    background: #ffffff;
    box-shadow: 0px -2px 13px 0px rgba(0, 0, 0, 0.05);
    margin-top: 47px;

    .foot-bos {
      width: 100%;
      min-width: 1200px;
      max-width: 1500px;
      margin: 0 auto;
      padding-top: 16px;
      padding-left: 20px;

      .bnt1 {
        width: 120px;
        height: 32px;
        background: #f7f8fa;
      }

      .bnt2 {
        width: 120px;
        height: 32px;
      }
    }
  }

  .descriptions-head {
    width: 448px;
    height: 32px;
    background: #f2f3f5;
    border-radius: 2px 2px 2px 2px;
    padding: 0 12px;
    margin-bottom: 30px;
    font-size: 14px;
    color: #1d2129;
    line-height: 32px;
  }

  .descriptions-title {
    font-weight: 500;
    font-size: 16px;
    color: #1d2129;
    padding-left: 10px;
    position: relative;

    &::after {
      content: '';
      width: 4px;
      height: 16px;
      background: #e7000b;
      position: absolute;
      left: 0;
      top: 4px;
    }
  }

  .register-success {
    width: 100%;
    padding-bottom: 30px;

    img {
      width: 324px;
    }

    .success-text {
      font-weight: 400;
      font-size: 14px;
      color: #000000;
      margin: 20px 0 30px 0;
    }
  }

  :deep(.is-bordered-label) {
    font-weight: 400;
  }
}
</style>
