<template>
	<view class="reader-card">
    <image class="card-top-bg" src="@/static/images/card-img1.png" mode="widthFix" />
    
    <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>
        </view>
        <radio :value="item.bindValue" :checked="selectedValue === item.bindValue"/>
      </view>
    </view>

    <button 
      class="unbind-btn" 
      :disabled="!selectedValue"
      :class="{disabled: !selectedValue}"
      @click="handleUnbind"
    >
      确认解绑
    </button>
	</view>
</template>

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

const READLIST = 'reader-card-list';

export default {
	data() {
		return {
      selectedValue: '',
      cardList: [],
		}
	},
  onShow() {
    this.getBindReaderCardList();
  },
	methods: {
    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) {
          this.cardList = res.data;
          uni.setStorageSync(READLIST, res.data);
        } else {
          this.cardList = [];
          uni.setStorageSync(READLIST, []);
        }
      } catch (err) {
        this.cardList = uni.getStorageSync(READLIST) || [];
      }
    },

    handleSelectItem(value) {
      if (this.selectedValue === value) {
        this.selectedValue = '';
      } else {
        this.selectedValue = value;
      }
    },

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

      const openId = uni.getStorageSync('wx_login_code');
      if (!openId) return;

      // 判断：当前解绑的是不是【默认证】
      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 {
            // 1. 执行解绑
            const result = await FetchUnbindReadCard({
              bindType: "rdid",
              bindValue: this.selectedValue,
              libcode: "1201",
              openid: openId
            });

            if (result.code !== 200) {
              uni.showToast({ title: result.msg || '解绑失败', icon: 'none' });
              return;
            }

            uni.showToast({ title: '解绑成功', icon: 'success' });
            this.selectedValue = '';

            // 刷新列表
            await this.getBindReaderCardList();

            if (isUnbindDefault && this.cardList.length > 0) {
              const newDefaultCard = this.cardList[0];
              const newValue = newDefaultCard.bindValue;

              const setResult = await FetchSetDefaultReadCard({
                bindType: 'rdid',
                bindValue: newValue,
                libcode: '1201',
                openid: openId
              });

              if (setResult.code === 200) {
                uni.setStorageSync('currentReaderCard', newValue);
                // 刷新列表，让界面显示新默认
                await this.getBindReaderCardList();
                uni.showToast({ title: '已自动设置默认证', icon: 'success' });
              }
            }

            if (this.cardList.length === 0) {
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            }

          } catch (err) {
            uni.showToast({ title: '解绑失败', icon: 'none' });
          }
        }
      });
    },
	}
}
</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%;
    display: block;
  }

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