<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" 
            placeholder="请输入昵称"
            @input="handleInput('nickName')" 
          />
          <uni-icons 
            class="clear-icon" 
            v-if="clearIconStatus.nickName" 
            @click="clearInput('nickName')" 
            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="handleInput('queryvalue')" 
          />
          <uni-icons 
            class="clear-icon" 
            v-if="clearIconStatus.queryvalue" 
            @click="clearInput('queryvalue')" 
            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: '',
      // 清空按钮状态（支持多输入框）
      clearIconStatus: {
        nickName: false,
        queryvalue: false
      }
    };
  },

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

  methods: {
    // 获取微信头像
    onChooseAvatar(e) {
      console.log('获取微信头像',e)
      this.avatarUrl = e.detail.avatarUrl;
    },
    
    // 统一监听输入（自动控制清空按钮显示隐藏）
    handleInput(field) {
      this.clearIconStatus[field] = this[field].trim().length > 0
    },
    
    // 统一清空输入框内容
    clearInput(field) {
      this[field] = ''
      this.clearIconStatus[field] = 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() {
      // 去除首尾空格
      this.nickName = this.nickName.trim()
      this.queryvalue = this.queryvalue.trim()
      
      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,
        };

        // {"code":200,"message":"操作成功","data":"{\"messagelist\":[{\"code\":\"R00138\",\"message\":\"未找到符合条件的读者！\"}],\"success\":false}","timestamp":1778154499544}

        // {"code":200,"message":"操作成功","data":"{\"success\":true,\"pagedata\":[{\"rdClusterCode\":null,\"rdlib\":\"GD\",\"rdid\":\"420105198509200438\",\"rdcfstate\":1}]}","timestamp":1778154647854}

        // {"code":200,"message":"操作成功","data":"{\"messageList\":[{\"R00131\":\"认证失败，系统存在该读者，密码不匹配！\"}],\"success\":true,\"pagedata\":\"\"}","timestamp":1778155520501}
        

        const res = await FetchReaderList(params);

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

        // 统一提取错误信息
        let errMsg = '';
        if (result.messagelist?.length) {
          const item = result.messagelist[0];
          errMsg = item.message || Object.values(item)[0] || '认证失败';
        }
        if (result.messageList?.length) {
          const item = result.messageList[0];
          errMsg = item.message || Object.values(item)[0] || '认证失败';
        }

        // 成功判断
        const realSuccess = result.success === true && result.pagedata?.length > 0;

        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' });
          const openId =  uni.getStorageSync("wx_login_code");

          const bindParams = {
            ...this.screenConfig,
            openid: openId,
            bindValue: this.queryvalue,
            bindType: 'rdid',
            libcode: '1201',
          }
          const bindRes = await FetchBindReadCard(params);

          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;
    }
  }
}

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

  .item {
    width: 100%;
    min-height: 44px;
    border-radius: 22px;
    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;
      padding: 10px;
      font-size: 14px;
    }
    .clear-icon{
      padding: 0 12px;
      color: #ccc;
    }
  }
}

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

.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>