<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/avatar.png" mode="aspectFill"></image>
        <view class="library-name">葛店经济技术开发区图书馆</view>
      </view>
    </view>

    <view class="form-box">
      <view class="item">
        <uni-icons class="form-icon" type="person" size="24"></uni-icons>
        <input class="input" placeholder="请输入读者证号" v-model="queryvalue" />
      </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: {}
    };
  },

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

  methods: {
    // 切换密码显隐
    togglePwd() {
      this.showPwd = !this.showPwd;
    },
    // 1: 页面加载时先获取大屏配置
    async getScreenSetting() {
      try {
        const res = await FetchInitScreenSetting({ libcode: '1201' });
        const data = res.data;

        // 自动取出 4 个必须参数
        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 || ''
        };

        console.log('已获取第三方配置：', this.screenConfig);
      } catch (err) {
        console.error('获取配置失败：', err);
      }
    },

    // {"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}
        
    // 2：点击绑定 → 调用读者登录接口
    async submit() {
      if (!this.queryvalue || !this.rdpasswd) {
        uni.showToast({ title: '请输入读者证号和密码', icon: 'none' });
        return;
      }

      if (!this.screenConfig.thirdUrl) {
        uni.showToast({ title: '图书馆配置加载中，请稍候重试', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '绑定中...' });

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

        const res = await FetchReaderList(params);

        // 1. 解析返回的JSON字符串
        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;

        if (realSuccess) {
          const wxUser = uni.getStorageSync('wxUserInfo') || {};
          const loginRes = {
            token: 'reader-token-' + Date.now(),
            user: {
              nickName: wxUser.nickName || '读者',
              avatarUrl: wxUser.avatarUrl || '',
              cardNo: this.queryvalue
            }
          };

          uni.setStorageSync('token', loginRes.token);
          uni.setStorageSync('user-info', 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();
        console.error('绑定异常：', err);
        uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.top-bar {
  position: relative;
  width: 100%;
  height: 220rpx;

  .top-bar-bg {
    position: absolute;
    width: 100%;
    height: 100%;
  }

  .library-info {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 30rpx;

    .avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
    }

    .library-name {
      margin-top: 10rpx;
      color: #fff;
      font-size: 30rpx;
    }
  }
}

.form-box {
  padding: 40rpx 30rpx;

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

    .input {
      flex: 1;
      padding: 20rpx 20rpx;
      font-size: 28rpx;
    }
  }
}

.login-btn {
  margin-top: 20rpx;
  background-color: #01a4fe !important;
  border-radius: 40rpx;
  font-size: 30rpx;
}

.tips {
  margin: 60rpx 40rpx;
  font-size: 24rpx;
  color: #333;
  line-height: 40rpx;
}

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

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