<template>
  <view style="background-color: #fff; height: calc(100vh);">
    <view class="user-info-section">
      <!-- 点击获取头像 -->
      <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-btn">
        <image v-if="avatarUrl" :src="avatarUrl" class="avatar-img"></image>
        <image v-else src="@/static/images/avatar.png" class="avatar-img"></image>
        <text class="tip-text">点击选择头像</text>
      </button>
    </view>

    <view class="form-box">
      <view class="item">
        <uni-icons class="form-icon" type="person" size="24"></uni-icons>
        <view class="uni-input-wrapper">
					<input class="input" type="nickname" v-model="nickName" @blur="onNicknameBlur" placeholder="请输入昵称"  @input="clearInput" />
					<uni-icons class="clear-icon" v-if="showClearIcon" @click="clearIcon" type="close" size="20"></uni-icons>
				</view>
      </view>
      <view class="item">
        <uni-icons class="form-icon" custom-prefix="iconfont" type="icon-duzhezheng" size="24"></uni-icons>
        <view class="uni-input-wrapper">
					<input class="input" placeholder="请输入读者证号" v-model="queryvalue"  @input="clearInput" />
					<uni-icons class="clear-icon" v-if="showClearIcon" @click="clearIcon" type="close" size="20"></uni-icons>
				</view>
      </view>
      <view class="item">
        <uni-icons class="form-icon" type="locked" size="24"></uni-icons>
        <input class="input" placeholder="请输入密码" :password="!showPwd" v-model="rdpasswd" />
        <uni-icons class="form-right-icon" :type="showPwd ? 'eye-slash' : 'eye'" size="20"
          @click="togglePwd"></uni-icons>
      </view>
      <button class="login-btn" type="primary" @click="submit">绑定</button>
    </view>

    <view class="tips">
      温馨提示：<br />
      1、密码默认为 <text style="color:#e74c3c">身份证后6位</text>，如果身份证号最后一位为“X”，“X”需要大写;
    </view>
  </view>
</template>

<script>
import { FetchInitScreenSetting, FetchReaderList } from '@/api/user';

const TOKEN_KEY = 'token';
const USER_KEY = 'user-info';

export default {
  data() {
    return {
      queryvalue: '',
      rdpasswd: '',
      showPwd: false,
      screenConfig: {},
      avatarUrl: '',
      nickName: '',
      showClearIcon: false,
    };
  },

  onLoad() {
    this.getScreenSetting();
  },

  methods: {
    // 获取微信头像
    onChooseAvatar(e) {
      console.log('获取微信头像',e)
      this.avatarUrl = e.detail.avatarUrl;
    },
    onNicknameBlur(e) {
      this.nickName = e.detail.value.trim()
    },
    clearInput(event) {
      this.queryvalue = event.detail.value;
      if (event.detail.value.length > 0) {
          this.showClearIcon = true;
      } else {
          this.showClearIcon = false;
      }
    },
    clearIcon() {
      this.queryvalue = '';
      this.showClearIcon = false;
    },

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

    async getScreenSetting() {
      try {
        const res = await FetchInitScreenSetting({ libcode: '1201' });
        const data = res.data;
        this.screenConfig = {
          thirdUrl: data.open_lib_http?.context || '',
          thirdAppid: data.open_lib_appId?.context || '',
          thirdSecret: data.open_lib_secret?.context || '',
          sm4Key: data.sm4_key?.context || ''
        };
      } catch (err) {
        console.error('获取配置失败：', err);
      }
    },

    async submit() {
      // if (!this.avatarUrl) {
      //   uni.showToast({ title: '请选择头像', icon: 'none' });
      //   return;
      // }
      // if (!this.nickName) {
      //   uni.showToast({ title: '请输入昵称', icon: 'none' });
      //   return;
      // }
      if (!this.queryvalue || !this.rdpasswd) {
        uni.showToast({ title: '请输入读者证号和密码', icon: 'none' });
        return;
      }
      uni.showLoading({ title: '绑定中...' });

      try {
        const params = {
          ...this.screenConfig,
          selecttype: 'rdid',
          queryvalue: this.queryvalue,
          rdpasswd: this.rdpasswd,
        };

        const res = await FetchReaderList(params);

        let result = {};
        try {
          result = JSON.parse(res.data);
        } catch (e) {
          uni.hideLoading();
          uni.showToast({ title: '数据解析失败', icon: 'none' });
          return;
        }

        // 2. 统一提取错误信息（兼容大小写、各种格式）
        let errMsg = '';
        // 兼容小写 messagelist
        if (result.messagelist && result.messagelist.length > 0) {
          const item = result.messagelist[0];
          errMsg = item.message || Object.values(item)[0] || '绑定失败';
        }
        // 兼容大写 messageList
        if (result.messageList && result.messageList.length > 0) {
          const item = result.messageList[0];
          errMsg = item.message || Object.values(item)[0] || '绑定失败';
        }

        // 3. 真正的成功判断：必须 success=true 并且 pagedata 有值
        const realSuccess = result.success === true && result.pagedata && result.pagedata.length > 0;
        console.log('this.avatarUrl',this.avatarUrl)

        if (realSuccess) {
          const loginRes = {
            token: 'reader-token-' + Date.now(),
            user: {
              nickName: this.nickName || '小图',
              avatarUrl: this.avatarUrl,
              cardNo: this.queryvalue
            }
          };

          uni.setStorageSync(TOKEN_KEY, loginRes.token);
          uni.setStorageSync(USER_KEY, loginRes.user);

          uni.hideLoading();
          uni.showToast({ title: '绑定成功', icon: 'success' });

          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.hideLoading();
          uni.showToast({
            title: errMsg || '读者证或密码错误',
            icon: 'none'
          });
        }
      } catch (err) {
        uni.hideLoading();
        uni.showToast({ title: '网络异常', icon: 'none' });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.user-info-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 0 0 0;

  .avatar-btn {
    background: transparent;
    
    display: flex;
    flex-direction: column;
    align-items: center;
    &::after{
      border: none !important;
    }

    .avatar-img {
      width: 60px;
      height: 60px;
      border-radius: 50%;
    }

    .tip-text {
      font-size: 12px;
      color: #999;
    }
  }

  // .nickname-box {
  //   width: 80%;
  //   margin-top: 10px;

  //   .nickname-input {
  //     width: 100%;
  //     padding: 10px 0;
  //     border-bottom: 1px solid #eee;
  //     text-align: center;
  //     font-size: 14px;
  //   }
  // }
}

.form-box {
  padding: 20px 15px;

  .item {
    width: 100%;
    min-height: 40px;
    border-radius: 20px;
    background-color: #f7f7f7;
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    .input {
      flex: 1;
      padding: 10px;
      font-size: 14px;
    }
  }


  .uni-input-wrapper{
    flex: 1;
    display: flex;
    align-items: center;
    .input {
      flex: 1;
    }
    .clear-icon{
      padding: 0 10px;
    }
  }

}

.login-btn {
  margin-top: 10px;
  background-color: #01a4fe !important;
  border-radius: 20px;
  font-size: 16px;
}

.tips {
  margin: 30px 20px;
  font-size: 12px;
  color: #333;
  line-height: 20px;
}

.form-icon {
  ::v-deep .uni-icons {
    margin-left: 10px;
    color: #01a4fe !important;
  }
}

.form-right-icon {
  ::v-deep .uni-icons {
    margin-right: 10px;
  }
}
</style>