<template>
  <view style="background-color: #fff; height: calc(100vh);">
    <view class="top-bar">
      <image class="top-bar-bg" src="@/static/images/mingqi-beij@2x.png" mode="aspectFill"></image>
      <view class="library-info">
        <image class="avatar" src="@/static/images/logo.jpg" mode="aspectFill"></image>
        <view class="library-name">葛店经济技术开发区图书馆</view>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-box">
      <!-- 姓名 -->
      <view class="form-item">
        <uni-icons class="form-icon" custom-prefix="iconfont" type="icon-user" size="24"></uni-icons>
        <input 
          class="input" 
          placeholder="请输入姓名" 
          v-model="formData.name"
          maxlength="20"
        />
      </view>

      <!-- 身份证号 -->
      <view class="form-item">
        <uni-icons class="form-icon" custom-prefix="iconfont" type="icon-shenfen" size="24"></uni-icons>
        <input 
          class="input" 
          placeholder="请输入身份证号" 
          v-model="formData.idCard"
          maxlength="18"
        />
      </view>

      <!-- 手机号 -->
      <view class="form-item">
        <uni-icons class="form-icon" type="phone" size="24"></uni-icons>
        <input 
          class="input" 
          placeholder="请输入手机号" 
          v-model="formData.phone"
          type="number"
          maxlength="11"
        />
        <button class="get-phone-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
          获取手机号
        </button>
      </view>

      <!-- 密码 -->
      <view class="form-item">
        <uni-icons class="form-icon" type="locked" size="24"></uni-icons>
        <input 
          class="input" 
          placeholder="请输入密码" 
          :password="!showPwd" 
          v-model="formData.password"
          maxlength="20"
        />
        <uni-icons 
          class="pwd-icon" 
          :type="showPwd ? 'eye-slash' : 'eye'" 
          size="20"
          @click="togglePwd"
        ></uni-icons>
      </view>

      <!-- 确认密码 -->
      <view class="form-item">
        <uni-icons class="form-icon" type="locked" size="24"></uni-icons>
        <input 
          class="input" 
          placeholder="请再次输入密码" 
          :password="!showConfirmPwd" 
          v-model="formData.confirmPassword"
          maxlength="20"
        />
        <uni-icons 
          class="pwd-icon" 
          :type="showConfirmPwd ? 'eye-slash' : 'eye'" 
          size="20"
          @click="toggleConfirmPwd"
        ></uni-icons>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" type="primary" @click="submit" :loading="loading">
        {{ loading ? '提交中...' : '提交办证' }}
      </button>
    </view>

    <!-- 温馨提示 -->
    <!-- <view class="tips">
      <text class="tips-title">温馨提示：</text>
      <view class="tips-content">
        <text>1、请确保填写的信息真实准确</text>
        <text>2、密码建议设置为6-20位数字和字母组合</text>
        <text>3、提交后工作人员将在1-3个工作日内审核</text>
      </view>
    </view> -->
  </view>
</template>

<script>
import config from '@/utils/config';
import { getOpenId } from '@/utils/storage';

export default {
  data() {
    return {
      formData: {
        name: '',
        idCard: '',
        phone: '',
        password: '',
        confirmPassword: ''
      },
      showPwd: false,
      showConfirmPwd: false,
      loading: false
    };
  },

  onLoad() {
  },

  methods: {
    /**
     * 获取手机号（通过后端接口解密）
     */
    getPhoneNumber(e) {
      if (e.detail.errMsg !== 'getPhoneNumber:ok') {
        uni.showToast({ title: '取消授权', icon: 'none' });
        return;
      }
      
      // #ifdef MP-WEIXIN
      // 获取 login code
      uni.login({
        success: (loginRes) => {
          // 调用后端接口解密手机号
          uni.request({
            url: config.baseUrl + '/api/wx/decryptPhone',
            method: 'POST',
            data: {
              code: loginRes.code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv
            },
            success: (res) => {
              if (res.data && res.data.code === 200) {
                this.formData.phone = res.data.data.phoneNumber || '';
              } else {
                uni.showToast({
                  title: res.data?.message || '获取手机号失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              uni.showToast({
                title: '获取手机号失败',
                icon: 'none'
              });
            }
          });
        },
        fail: () => {
          uni.showToast({
            title: '获取手机号失败',
            icon: 'none'
          });
        }
      });
      // #endif
      
      // #ifndef MP-WEIXIN
      uni.showToast({ title: '该功能仅支持微信小程序', icon: 'none' });
      // #endif
    },


    /**
     * 切换密码显示
     */
    togglePwd() {
      this.showPwd = !this.showPwd;
    },

    /**
     * 切换确认密码显示
     */
    toggleConfirmPwd() {
      this.showConfirmPwd = !this.showConfirmPwd;
    },

    /**
     * 验证身份证号
     */
    validateIdCard(idCard) {
      const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
      return reg.test(idCard);
    },

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

    /**
     * 表单验证
     */
    validateForm() {
      const { name, idCard, phone, password, confirmPassword } = this.formData;

      if (!name || name.trim().length === 0) {
        uni.showToast({ title: '请输入姓名', icon: 'none' });
        return false;
      }

      if (!idCard || idCard.trim().length === 0) {
        uni.showToast({ title: '请输入身份证号', icon: 'none' });
        return false;
      }

      if (!this.validateIdCard(idCard)) {
        uni.showToast({ title: '身份证号格式不正确', icon: 'none' });
        return false;
      }

      if (!phone || phone.trim().length === 0) {
        uni.showToast({ title: '请输入手机号', icon: 'none' });
        return false;
      }

      if (!this.validatePhone(phone)) {
        uni.showToast({ title: '手机号格式不正确', icon: 'none' });
        return false;
      }

      if (!password || password.length < 6) {
        uni.showToast({ title: '密码至少需要6位', icon: 'none' });
        return false;
      }

      if (password !== confirmPassword) {
        uni.showToast({ title: '两次输入的密码不一致', icon: 'none' });
        return false;
      }

      return true;
    },

    /**
     * 提交表单
     */
    async submit() {
      if (!this.validateForm()) {
        return;
      }

      this.loading = true;

      try {
        const openId = await getOpenId();
        if (!openId) {
          uni.showToast({ title: '获取用户信息失败', icon: 'none' });
          this.loading = false;
          return;
        }

        const res = await uni.request({
          url: config.baseUrl + '/api/reader/register',
          method: 'POST',
          data: {
            name: this.formData.name,
            idCard: this.formData.idCard,
            phone: this.formData.phone,
            password: this.formData.password,
            openId: openId,
            libcode: config.LIB_CODE
          }
        });

        if (res.data && res.data.code === 200) {
          uni.showToast({ title: '提交成功', icon: 'success' });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({ title: res.data?.message || '提交失败', icon: 'none' });
        }
      } catch (error) {
        console.error('注册失败:', error);
        uni.showToast({ title: '提交失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.top-bar {
  position: relative;
  width: 100%;
  height: 180px;
  
  .top-bar-bg {
    width: 100%;
    height: 100%;
  }
  
  .page-title {
    position: absolute;
    bottom: 20px;
    left: 20px;
    font-size: 28px;
    font-weight: bold;
    color: #fff;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
}

.form-box {
  padding: 20px 15px;
}
.form-item {
  position: relative;
  display: flex;
  align-items: center;
  height: 44px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 10px;
  
  .form-icon {
    margin-right: 12px;
    color: #01a4fe;
  }
  
  .input {
    flex: 1;
    height: 100%;
    font-size: 14px;
    color: #333;
  }
  
  .pwd-icon {
    margin-left: 10px;
    color: #999;
  }
  
  .get-phone-btn {
    background-color: #01a4fe;
    color: #fff;
    font-size: 12px;
    border-radius: 20px;
    border: none;
  }
}

.submit-btn {
  width: 100%;
  height: 48px;
  background-color: #01a4fe;
  color: #fff;
  border-radius: 24px;
  font-size: 16px;
  margin-top: 20px;
  border: none;
  
  &::after {
    border: none;
  }
}

.tips {
  padding: 15px;
  background-color: #fff;
  margin: 0 15px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  
  .tips-title {
    font-size: 14px;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 8px;
  }
  
  .tips-content {
    text {
      display: block;
      font-size: 13px;
      color: #999;
      line-height: 1.8;
    }
  }
}
</style>
