<template>
	<view class="container">
	  <view class="content">
	
	    <view class="member_list">
	      <view class="member_item" v-for="(item, index) in memberList" :key="index">
	        <view class="member_name">
	          <view class="name">{{item.memberName}}</view>
	          <view class="tip child">{{item.isChildren==1?'儿童':'成人'}}</view>
	          <view class="tip real">{{item.IsRealNameAuth==1?'已实名':'未实名'}}</view>
	          <view class="tip bind">{{item.Data_1.length>0?'已绑卡':'未绑卡'}}</view>
	        </view>
	
	        <view class="card_info">
	          <view class="wrap" @click="btnClick($event)" data-type="1" :data-item="item">
	            <view class="card-face-container">
	              <image class="card-bg" src="@/static/images/healthCard/cardnewbg.png" alt="" />
	              <view class="card-top-info">
	                <view class="card-top-org">福建省卫生健康委员会</view>
	                <view class="card-top-title">
	                  <image src="@/static/images/healthCard/icon2.png" alt="" />
	                  <text>{{(item.healthCard&&item.base64Code)||(item.healthCard)?'电子健康卡':'院内就诊卡'}}</text>
	                </view>
	              </view>
	
	              <view class="card-detail-info">
	                <view class="card-user-info">
	                  <text class="card-user-name">{{item.MemberName}}</text>
	                  <text class="card-user-id">{{item.CertNum}}</text>
	                </view>
	                <view :class="['card-qrcode', item.healthCard ? 'bg_fff' : '']" v-if="item.healthCard">
	                  <view v-if="item.cardTypeDiy==16" class="image_box">
	                    <!-- <image class="card-qrcode-logo" src="../../../static/images/healthCard/logo_.png" alt="" /> -->
	                    <cover-image class="card-qrcode-logo" src="@/static/images/healthCard/logo_.png"></cover-image>
	                    <!-- 健康卡code图片-->
	                    <!-- <image :style="{width:codeWidth+'px', height:codeWidth+'px'}" :src="'data:image/png;base64,'+item.base64Code" alt="" /> -->
	                    <canvas class='baseCode' :canvas-id="'canvas'+index" style="width: 154upx; height: 154upx;"></canvas>
	                  </view>
	                  <view v-else>
	                  <!-- canvas -->
	                    <canvas class='baseCode' :canvas-id="'canvas'+index" style="width: 154upx; height: 154upx;"></canvas>
	                  </view>
	                </view>
	                <!-- 升级健康卡图片 -->
	                <view class="card-qrcode noHealthCard" v-if="!item.healthCard" @click.stop="btnClick($event)" data-type="4" :data-item="item">
	                  <image src="@/static/images/healthCard/ksj.png" alt="" />
	                </view> 
	              </view>
	
	              <view class="card-footer">
	                中华人民共和国国家卫生健康委员会监制
	              </view>
	            </view>
	          </view>
	        </view>
	
	
	        <view class="member_default" v-if="false">
          <view class="relieve" @click="unbind" :data-item="item">解除绑定</view>
        </view>
	
	      </view>
	    </view>
	
	    <view class="btns">
	      <view class="btn add" @click="btnClick($event)" data-type="2">添加</view>
	      <view class="btn" @click="btnClick($event)" data-type="3">已有健康卡一键关联</view>
	      <!-- <view class="btn" @click="clearAuth" >清除授权</view> -->
	    </view>
	
	
	    <view class="dialogContiner mask" v-if="showBtn">
	      <view class="dialog">
	        <!-- <view class="title">微信授权</view> -->
	        <view class="info">获取你的公开信息（昵称，头像，地区，及性别）</view>
            <!-- #ifdef MP-WEIXIN -->
	        <healthCardLogin :encrypt="true" :authLogin="false" @authFail="authFail" @authSucess="authSuccess" :wechatcode="true" :healthcode="true">
	          <view @click="auth" class="btn-agree">前往授权</view>
	        </healthCardLogin>
            <!-- #endif -->
            <!-- #ifndef MP-WEIXIN -->
             <view @click="auth" class="btn-agree">前往授权(模拟)</view>
            <!-- #endif -->
	      </view>
	    </view>
	  </view>
	</view>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance } from 'vue';
import { useSmallProgramLogin } from '@/hook';
import { onShow } from '@dcloudio/uni-app';
import { common, QRCode } from '@/utils';
import { 
  queryMemberCardListByDb_V3, 
  updateToHealthCard_V2,
  delMemberInfo_V3
} from '@/pagesPersonal/service/patientManagement';

const { proxy } = getCurrentInstance() as any;
const app = getApp();

const memberList = ref<any[]>([]);
const number = ref(0);
const codeWidth = ref<string>('0');
const showBtn = ref(false);

let type_pub = "";
let memberInfo_pub: any = {};

onShow(() => {
  main();
});

const main = async () => {
  common.showLoading('加载中');
  codeWidth.value = common.rpxtopx(154).toFixed(0);
  let resp = await queryMemberList();
  if (!common.isEmpty(resp)) {
    // 延迟一点时间确保canvas节点存在
    setTimeout(() => {
        for (let i = 0; i < resp.length; i++) {
            new QRCode(`canvas${i}`, {
                text: resp[i].healthCard || resp[i].idCardNo,
                width: Number(codeWidth.value) || 144, // Use calculated width
                height: Number(codeWidth.value) || 144,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H,
            });
        }
    }, 200);
  }
  common.hideLoading();
  memberList.value = resp;
  number.value = resp.length;
};

const getWechatCode = () => {
  return new Promise((resolve) => {
    // #ifdef MP-WEIXIN
    uni.login({
      provider: 'weixin',
      success: (res) => {
        resolve(res.code);
      },
      fail: () => {
        resolve('');
      }
    });
    // #endif
    // #ifndef MP-WEIXIN
    resolve('');
    // #endif
  });
};

const btnClick = async (e: any) => {
  let type = e.currentTarget.dataset.type;
  let memberInfo = e.currentTarget.dataset.item;
  type_pub = type;
  memberInfo_pub = memberInfo;
  
  if (type == 2 || type == 3 || type == 4) {
    common.showLoading('加载中');
    // let wechatCode = await common.getAuthorize((show: boolean) => {
    //     if(show) {
    //         showBtn.value = true;
    //     }
    // });
    let wechatCode = await getWechatCode();
    
    // 如果没有code，或者需要显式授权（此处根据业务逻辑，如果需要弹窗，则弹窗）
    // 假设如果获取不到code或者特定条件下显示弹窗。
    // 这里保留原逻辑的意图：如果有code则直接处理，否则显示弹窗让用户点击授权
    if (common.isEmpty(wechatCode)) {
        showBtn.value = true;
    }

    common.hideLoading();
    
    if (!common.isEmpty(wechatCode)) {
      app.globalData.wechatCode = wechatCode;
      if (type == 2 || type == 3) {
        handleType(type);
      } else if (type == 4) {
        let resp = await updateToHealthCard(memberInfo, wechatCode);
        common.hideLoading();
        if (!common.isEmpty(resp)) {
          common.showToast('升级成功', () => {
            main();
          });
        }
      }
    }
  } else if (type == 1) {
    app.globalData.cardInfo_x = memberInfo;
    uni.navigateTo({
      url: '../healthCardQrcode/healthCardQrcode'
    });
  }
};

const authSuccess = async (data: any) => {
  var res = data.detail;
  if (!res.result.code) {
    return;
  }
  var wechatCode = res.result.wechatCode;
  app.globalData.wechatCode = wechatCode;
  showBtn.value = false;
  
  if (type_pub == '2' || type_pub == '3') {
    handleType(type_pub);
  } else if (type_pub == '4') {
    common.showLoading('加载中');
    let resp = await updateToHealthCard(memberInfo_pub, app.globalData.wechatCode);
    common.hideLoading();
    if (!common.isEmpty(resp)) {
      common.showToast('升级成功', () => {
        main();
      });
    }
  }
};

const authFail = (e: any) => {
    console.log('Auth failed', e);
};

const handleType = (type: string) => {
  switch (type) {
    case "2":
      if (number.value >= 5) {
        common.showModal('暂时只允许添加5个就诊人，谢谢您的合作。', () => {}, { showCancel: false, confirmColor: '#0099cc' });
        return;
      }
      uni.navigateTo({
        url: '../addMember/addMember?pageType=addHealthCard',
      });
      break;
    case "3":
      uni.navigateTo({
        url: '../healthCardList/healthCardList'
      });
      break;
  }
};

const queryMemberList = async () => {
  let list: any[] = [];
  let data = uni.getStorageSync('memberList');
  if (common.isNotEmpty(data)) {
    list = await Promise.all(
      data.map(async (item: any) => {
        let queryMemberCard = {
          memberId: item.memberId,
          mobileFormatDesensitization: "false",
          memberNameFormatDesensitization: "false",
          certNumFormatDesensitization: "false",
          cardNoFormatDesensitization: "false"
        };
        // 使用 Service 接口调用
        let respcard = await queryMemberCardListByDb_V3(queryMemberCard);
        console.log(respcard);
        // 注意：这里假设 service 返回解构后的 respcard.resData，如果 service 返回原 resp，则保留原逻辑
        // 根据 rules，service 返回值直接处理。假设返回的是 { resData: ... } 或者直接是 data
        // 原代码：respcard.resData.RespCode
        // 建议检查 service 定义。为了安全，保留原字段访问
        if (respcard && respcard.resData && respcard.resData.RespCode == "10000" && common.isNotEmpty(respcard.resData.Data)) {
          let cardDatas = respcard.resData.Data;
          let healthCardData = cardDatas.filter((p: any) => p.cardType == 16);
          if (common.isNotEmpty(healthCardData)) {
            item.cardTypeDiy = '16';
            item.CardType = '16';
            item.healthCard = healthCardData[0].cardNo;
            item.CardNo = healthCardData[0].cardNo;
          } else {
            item.CardType = '1';
            item.CardNo = cardDatas[0].cardNo;
          }
        }
        item.MemberId = item.memberId;
        item.MemberName = item.memberName;
        item.Mobile = item.mobile;
        item.CertNum = item.certNum;
        item.IdCardNo = item.idCardNo;
        return item;
      })
    );
  }
  return list;
};

const updateToHealthCard = async (item: any, code: string) => {
    let param = {
        MemberId: item.memberId,
        WechatCode: code,
        DefaultCardNo: item.CardNo,
        DefaultCardType: item.CardType
    };
    // Service 调用
    let { resData } = await updateToHealthCard_V2(param);
    if (resData && resData.RespCode == 10000) {
        return true;
    } else {
        if (resData) app.toLogin(resData); // 兼容原逻辑
		if(resData.RespCode == "401") {
			useSmallProgramLogin()
		}
        return false;
    }
};

const unbind = (e: any) => {
    let item = e.currentTarget.dataset.item;
    common.showModal(`尊敬的用户，是否确定解除【${item.memberName}】的 绑定？该操作无法回退！`, async() => {
      let queryData = {
        memberId: item.memberId,
        accountSn: item.accountSn,
      }
      let { resData } = await delMemberInfo_V3(queryData)
      if (resData.RespCode == 10000) {
        // 解绑操作时，判断是否等同与本地存储数据
        if (app.globalData.currentUser && item.memberId == app.globalData.currentUser.memberId) {
          app.globalData.currentUser = ""
        }
        common.showModal(`已成功解绑【${item.memberName}】`, async () => {
          // 添加成功并且设置默认完成后 重新查询并保存全局就诊人数据信息
          await usePreserMember()
          main()
        })
      }
    }, {
      title:'温馨提示',
      cancelText: '取消'
    })
}

const auth = () => {
    showBtn.value = false;
    // 模拟授权成功（非微信环境）
    // #ifndef MP-WEIXIN
    authSuccess({ detail: { result: { code: true, wechatCode: 'mock-code' } } });
    // #endif
}
</script>

<style lang="scss" scoped>
	.member_item{
	  background-color: #fff;
	  margin-bottom: 30upx;
	}
	.member_name{
	  display: flex;
	  padding: 20upx;
	  align-items: center;
	  border-bottom: 1px solid #ebeaea;
	}
	.name{
	  min-width: 104upx;
	  font-size: 32upx;
	}
	.tip{
	  color: #fff;
	  border-radius: 5px;
	  padding: 2upx 20upx;
	  margin:0 10upx;
	  font-size: 22upx;
	}
	.child{
	  background-color: #189fa4;
	}
	.real{
	  background-color: #f2a000;
	}
	.bind{
	  background-color: #59a4ee;
	}  
	.member_default{
	  padding:15upx 30upx 15upx 70upx;
	  border-top: 1px solid #ebeaea;
	  display: flex;
	  justify-content: flex-end;
	  align-items: center;
	  position: relative;
	} 
	.card_info{
	  padding: 26upx 0;
	}
	.icon{
	  margin-right: 10upx;
	  position: absolute;
	  height: 16px;
	  width: 16upx;
	  line-height: 16px;
	  top: 0;
	  bottom: 0;
	  left: 25upx;
	  margin: auto 0;
	}
	.circular{
	  width: 14px;
	  height: 14px;
	  border: 1px solid #ccc;
	  border-radius: 50%;
	  padding: 0;
	}
	.relieve{
	  color: #4DB371;
	  border: 1px solid ;
	  border-radius: 50px;
	  padding: 8upx 35upx;
	}
	
	.wrap {
	    background: #fff;
	    width: 100%;
	    min-height: 100%; 
	     font-family: PingFangSC-Medium; 
	} 
	.card-face-container {
	    height: 350upx;
	    width: 620upx;
	    margin: 0 auto;
	    position: relative;
	    color: #000000;
	}
	
	.card-face-container .card-bg {
	    height: 100%;
	    width: 100%;
	    position: absolute;
	}
	
	.card-face-container .card-top-info {
	    position: absolute;
	    top: 23upx;
	    width:100%;
	    padding: 0 27upx 0 34upx;
	    display: flex;
	    justify-content: space-between;
	    align-items: center;
	}
	
	.card-face-container .card-top-info .card-top-org {
	    font-size: 18upx;
	    line-height: 25upx;
	}
	
	.card-face-container .card-top-info .card-top-title {
	    display: flex;
	    align-items: center;
	    font-size: 30upx;
	    line-height: 42upx;
	    color: #2B2B2B;
	}
	
	.card-face-container .card-top-info .card-top-title image {
	    height: 55upx;
	    width: 55upx;
	    margin-right: 8upx;
	}
	
	.card-face-container .card-detail-info {
	    position: absolute;
	    top: 124upx;
	    width: 100%;
	    padding: 0 15upx 0 34upx;
	    display: flex;
	    justify-content: space-between;
	    align-items: flex-end;
	}
	
	.card-face-container .card-detail-info .card-user-info {
	    font-size: 36upx;
	    color: #2B2B2B;
	}
	
	.card-face-container .card-detail-info .card-user-info .card-user-name {
	    height: 50upx;
	}
	
	.card-face-container .card-detail-info .card-user-info .card-user-id {
	    font-size: 30upx;
	    line-height: 30upx;
	    display: block;
	    padding-top: 12upx;
	}
	
	.card-face-container .card-detail-info .card-qrcode {
	    
	    padding: 4upx;
	    position: relative;
	    font-size: 0;
	}
	.bg_fff{
	  background: #FFFFFF;
	}
	.card-face-container .card-detail-info .noHealthCard {
	    background: transparent; 
	}
	
	.card-face-container .card-detail-info .card-qrcode .card-qrcode-logo {
	    height: 44upx;
	    width: 44upx;
	    position: absolute;
	    top: 50%;
	    left: 50%;
	    transform: translate(-50%, -50%);
	    z-index: 10;
	}
	
	.card-face-container .card-detail-info .card-qrcode image {
	    height: 154upx;
	    width: 154upx;
	}
	
	.card-face-container .card-footer {
	    position: absolute;
	    font-size: 18upx;
	    bottom: 16upx;
	    left: 50%;
	    transform: translateX(-50%);
	    white-space: nowrap;
	    letter-spacing: 0;
	    line-height: 25upx;
	}
	.btns{
	  padding: 10upx 0 1px;
	}
	.btn{
	  width: 90%;
	  margin: 30upx auto;
	  padding: 20upx;
	  border-radius: 5px;
	  background-color: #fff;
	  color: var(--auxiliaryColor);
	  text-align: center;
	  font-size: 30upx;
	}
	.add{
	  background-color: var(--auxiliaryColor) !important;
	  color: #fff !important;
	}
	
	
	
	/* 健康卡授权 */
	.mask {
	    position: fixed;
	    top: 0;
	    left: 0;
	    width: 100%;
	    height: 100%;
	    z-index: 100000;
	}
	
	.dialogContiner .dialog {
	    position: absolute;
	    top: 50%;
	    left: 50%;
	    width: 450upx;
	    transform: translate(-50%, -50%);
	    background-color: #fff;
	    box-shadow: 0 -2px 25px 0 rgba(0, 0, 0, 0.15), 0 13px 25px 0 rgba(0, 0, 0, 0.3);
	    z-index: 100000;
	    text-align: center;
	    border-radius: 10upx;
	}
	
	.dialogContiner .dialog .btn-agree {
	    position: relative;
	    line-height: 100upx;
	    font-size: 35upx;
	    color: #4DB371;
	}
	
	.dialogContiner .dialog .btn-agree::before {
	    content: '';
	    position: absolute;
	    left: 0;
	    right: 0;
	    top: 0;
	    height: 1px;
	    transform: scaleY(0.5);
	    background-color: rgba(234, 234, 234, 1);
	}
	
	.dialogContiner .dialog .btn-agree:hover {
	    background-color: #fff;
	}
	
	.dialogContiner .dialog view.title {
	    font-size: 40upx;
	    line-height: 100upx;
	    position: relative;
	}
	
	.dialogContiner .dialog view.title::after {
	    content: '';
	    position: absolute;
	    left: 0;
	    right: 0;
	    bottom: 0;
	    height: 1px;
	    transform: scaleY(0.5);
	    background-color: rgba(234, 234, 234, 1);
	}
	
	.dialogContiner .dialog view.info {
	    font-size: 26upx;
	    line-height: 30upx;
	    color: rgba(22, 23, 42, 0.5);
	    padding: 40upx;
	} 
	
	.baseCode{
	  width: 144upx;
	  height: 144upx;
	  z-index: 1;
	}
	.image_box{
	  font-size: 0;
	}
</style>