<template>
	<view class="reader-card">
    <image class="card-top-bg" src="@/static/images/card-img1.png" mode="widthFix" />

    <view class="edit-btn" @click="toggleEditMode">
      {{ isEditMode ? '完成' : '解绑' }}
    </view>

    <view class="card-list">
      <view 
        class="card-list-item" 
        v-for="(item, index) in cardList" 
        :key="item.id"
        @click="handleSelectItem(item.bindValue)"
        :class="{ active: selectedValue === item.bindValue }"
      >
        <image class="card-left-img" src="@/static/images/card-img2.png" mode="widthFix" />
        <view class="card-right-info">
            <text class="info-title">读者证号</text>
            <text class="info-num">{{ item.bindValue }}</text>
            <text class="default-tag" v-if="item.bindDefault">默认证</text>
        </view>

        <radio v-if="isEditMode" :value="item.bindValue" :checked="selectedValue === item.bindValue"/>
      </view>

      <view class="add-card-btn" @click="toAddReaderCard" v-if="!isEditMode">
        <uni-icons type="plus" size="20" color="#01a4fe"></uni-icons>
        <text>新增读者证</text>
      </view>
    </view>

    <!-- 编辑模式显示底部解绑按钮 -->
    <button 
      v-if="isEditMode"
      class="unbind-btn" 
      :disabled="!selectedValue"
      :class="{disabled: !selectedValue}"
      @click="handleUnbind"
    >
      确认解绑
    </button>
	</view>
</template>

<script>
import { 
  FetchFindAllReaderBindByOpenId, 
  FetchSetDefaultReadCard,
  FetchUnbindReadCard 
} from '@/api/user';

const READLIST = 'reader-card-list';

export default {
	data() {
		return {
      isEditMode: false,
      selectedValue: '',
      cardList: [],
		}
	},
  onShow() {
    this.getBindReaderCardList();
  },
	methods: {
    // 切换编辑模式 + 清空选中
    toggleEditMode() {
      this.isEditMode = !this.isEditMode;
      this.selectedValue = '';
    },

    // 获取列表
    async getBindReaderCardList() {
      try {
        const openId = uni.getStorageSync('wx_login_code');
        if (!openId) return;

        const res = await FetchFindAllReaderBindByOpenId({
          libcode: '1201',
          openId: openId
        });

        if (res.code === 200 && res.data.length > 0) {
          this.cardList = res.data;
          uni.setStorageSync(READLIST, res.data);
        } else {
          this.cardList = [];
          this.selectedValue = '';
          uni.setStorageSync(READLIST, []);
        }
      } catch (err) {
        this.cardList = uni.getStorageSync(READLIST) || [];
      }
    },

    // 点击卡片
    handleSelectItem(value) {
      // 编辑模式：只做选择
      if (this.isEditMode) {
        this.selectedValue = this.selectedValue === value ? '' : value;
        return;
      }

      // 正常模式：切换默认
      const currentDefault = this.cardList.find(item => item.bindDefault === true);
      if (currentDefault && currentDefault.bindValue === value) {
        uni.showToast({
          title: '当前已是默认证，请勿重复操作',
          icon: 'none'
        });
        return;
      }

      const openId = uni.getStorageSync('wx_login_code');
      uni.showModal({
        title: '提示',
        content: '确定切换默认读者证吗？',
        success: async (res) => {
          if (!res.confirm) return;

          try {
            const result = await FetchSetDefaultReadCard({
              bindType: 'rdid',
              bindValue: value,
              libcode: '1201',
              openid: openId
            });

            if (result.code === 200) {
              uni.setStorageSync('currentReaderCard', value);
              await this.getBindReaderCardList();
              uni.showToast({ title: '默认证切换成功', icon: 'success' });
            }
          } catch (err) {
            uni.showToast({ title: '切换失败', icon: 'none' });
          }
        }
      });
    },

    // 解绑（核心逻辑）
    async handleUnbind() {
      if (!this.selectedValue) {
        uni.showToast({ title: '请选择要解绑的读者证', icon: 'none' });
        return;
      }

      const openId = uni.getStorageSync('wx_login_code');
      const unbindItem = this.cardList.find(item => item.bindValue === this.selectedValue);
      const isUnbindDefault = unbindItem?.bindDefault === true;

      uni.showModal({
        title: '提示',
        content: `确定要解绑读者证【${this.selectedValue}】吗？`,
        success: async (res) => {
          if (!res.confirm) return;

          try {
            const result = await FetchUnbindReadCard({
              bindType: "rdid",
              bindValue: this.selectedValue,
              libcode: "1201",
              openid: openId
            });

            if (result.code === 200) {
              uni.showToast({ title: '解绑成功', icon: 'success' });
              
              // 清空选中（不解绑模式自动选中第一个）
              this.selectedValue = '';
              await this.getBindReaderCardList();

              // ==============================================
              // ✅ 解绑的是默认 → 自动设置第一个为新默认（接口+缓存）
              // ✅ 但不解绑模式选中它
              // ==============================================
              if (isUnbindDefault && this.cardList.length > 0) {
                const newValue = this.cardList[0].bindValue;
                await FetchSetDefaultReadCard({
                  bindType: 'rdid',
                  bindValue: newValue,
                  libcode: '1201',
                  openid: openId
                });
                uni.setStorageSync('currentReaderCard', newValue);
                await this.getBindReaderCardList();
              }

              // 全部解绑 → 返回
              if (this.cardList.length === 0) {
                setTimeout(() => uni.navigateBack(), 1500);
              }
            }
          } catch (err) {
            uni.showToast({ title: '解绑失败', icon: 'none' });
          }
        }
      });
    },

    toAddReaderCard() {
      uni.navigateTo({ url: "/pages/login/login" });
    },
  }
}
</script>

<style lang="scss" scoped>
.reader-card{
  position: relative;
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .card-top-bg{ 
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
  }

  .edit-btn{
    position: absolute;
    right: 20px;
    top: 20px;
    z-index: 100;
    font-size: 15px;
  }
  
  // 读者证列表
  .card-list{
    position: absolute;
    left: 0;
    top: 60px;
    width: calc(100% - 24px);
    height: calc(100vh - 195px);
    overflow-y: auto;
    padding: 12px;
    z-index: 999;
    
    .card-list-item{
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      margin-bottom: 12px;
      border: 2px solid #C6C6E2;
      border-radius: 8px;
      background: rgba(241,241,249,0.4);
      cursor: pointer;
      transition: all 0.2s;
      
      &.active{
        border-color: #01a4fe;
        background: rgba(1, 164, 254, 0.1);
      }
      
      .card-left-img{
        width: 80px;
        margin-right: 12px;
        display: block;
      }
      
      .card-right-info{
        flex: 1;
        display: flex;
        flex-direction: column;
        
        .info-title{
          font-size: 16px;
          color: #333;
          font-weight: bold;
          padding-bottom: 4px;
        }
        
        .info-num{
          font-size: 14px;
          color: #999;
        }
        .default-tag{
          width: 46px;
          font-size: 12px;
          color: #01a4fe;
          border: 1px solid #01a4fe;
          border-radius: 4px;
          padding: 2px 0;
          text-align: center;
          display: inline-block;
          margin-top: 4px;
        }
      }
    }
  }


  .add-card-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 15px;
    height: 44px;
    border: 1px dashed #01a4fe;
    border-radius: 8px;
    color: #01a4fe;
    font-size: 15px;

    uni-icons {
      margin-right: 6px;
    }
  }
  
  .unbind-btn{
    position: fixed;
    bottom: 40px;
    left: 0;
    right: 0;
    width: calc(100% - 40px);
    margin: 0 auto;
    padding: 4px 0;
    color: #fff;
    background-color: #01a4fe;
    border-radius: 23px;
    font-size: 16px;
		&.disabled{
			background-color: #ccc;
		}
  }
}
</style>