<template>
	<!--pages2/st1/merge/business/patientManagement/choosePatient/choosePatient.wxml-->
	<view class="container" v-if="showCon">
	  <view class="content">
	    <view class="patientBox">
	      <view v-if="patientInfoList.length == 0" class="noData">
	        <noData :value="noDataValue"></noData>
	      </view>
	      <template v-if="patientInfoList.length > 0">
            <view class="patient_list" v-for="(item, index) in patientInfoList" :key="index">
                <view class="patientInfoBox displayFlexLeft" @click="optionClick(item, index, 'member')">
                    <view class="patient_info displayFlexCol">
                        <view class="name_tel">
                            <text>{{item.memberName}}</text>
                            <text>{{item.mobile}}</text>
                        </view>
                        <text class="idCard" v-if="item.isChildren == 0">{{item.certTypeName}}：{{item.certNum}}</text>
                        <text class="idCard" v-if="item.isChildren == 1">监护人身份证：{{item.guardianCertNum}}</text>
                    </view>
                    <text class="defaultText" v-if="item.userMemberList && item.userMemberList[0] && item.userMemberList[0].isDefaultMember == 1">默认</text>
                    <image class="public_right_img public_right_img30" :class="{ 'transform90': patientInfoIndex === index }" :src="iconUrl.icon_right"></image>
                </view>
                
                <!-- 等于人本时展示授权与信用管理 -->
                <template v-if="item.memberType == 1">
                    <view class="personallyBox" :class="{ 'noPersonallyBox': !(type != 'member' && item.data_1 && patientInfoIndex == index) }">
                        <view class="moduleBox displayFlexBetween" @click.stop="forWard('authorizeIndex', item)">
                            <view class="bg backgroundCustom_F08"></view>
                            <view class="moduleInfo">
                                <view class="moduleInfo_txt">已授权他人使用</view>
                                <view class="colorCustom_F08">授权{{item.authQuantity || 0}}人</view>
                            </view>
                            <view class="moduleBox_btn backgroundCustom_F08">去管理</view>
                        </view> 
                        <view class="moduleBox displayFlexBetween" @click.stop="forWard('creditIndex', item)">
                            <view class="bg backgroundCustom"></view>
                            <view class="moduleInfo">
                                <view class="moduleInfo_txt">信用权益</view>
                                <view class="colorCustom">您的诊疗信用良好，可享受先诊后付费权益</view>
                            </view>
                            <view class="moduleBox_btn backgroundCustom">去管理</view>
                        </view> 
                    </view>
                </template>

                <image :src="iconUrl.icon_memDivision" class="icon_memDivision" mode="widthFix" v-if="item.memberType == 1 && type != 'member' && item.data_1 && patientInfoIndex == index"></image> 
                
                <view class="patientCardBox" v-if="type != 'member' && item.data_1 && patientInfoIndex == index">
                    <template v-for="(childItem, childIndex) in item.data_1" :key="childIndex">
                        <view class="patientCardBox_list displayFlexBetween" :class="{ 'colorCustom': childItem.isDefault == 1 }" 
                              @click.stop="optionClick(item, index, 'card', childItem)" v-if="cardTypeName == childItem.cardTypeName">
                            <view>{{childItem.cardTypeName}}：{{childItem.cardNo}}</view>
                            <image class="public_right_img" :src="iconUrl.icon_right"></image>
                        </view>
                    </template>
                </view>
            </view>

            <view class="relativesBox displayFlexLeft" v-if="patientInfoList.some(i => i.memberType == 1)">
                <image :src="iconUrl.icon_relatives" class="icon_relatives"></image>
                <view>亲友成员（{{patientInfoList.length - 1}}人）</view>
            </view>
	      </template>
	    </view>
	  </view>
	  <view class="public_btn backgroundCustom_F08" @click="jumpAddPatient">添加就诊人</view>
	</view>
</template>

<script lang="ts" setup>
import { queryMemberHeaderInfo } from '@/pages/st1/service/base';
import { setDefaultMemberV3, setDefaultClinicCard_V3 } from '@/pagesPersonal/service/patientManagement';
import { common } from '@/utils';
import icon from '@/utils/icon';
import { usePreserMember, queryMemberCardList_V3 } from '@/hook';
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import { ref } from 'vue';
import noData from "@/pages/st1/components/noData/noData.vue";

const app = getApp();
const iconUrl = ref(icon);
const noDataValue = ref("暂无就诊人");
const patientInfoList = ref<any[]>([]);
const patientInfoIndex = ref<any>('');
const pageType = ref('');
const type = ref("member");
const cardType = ref("1");
const cardTypeName = ref('就诊卡');
const fromComponent = ref(false);
const showCon = ref(false);
const currentUser = ref<any>({});

onLoad((options: any) => {
    pageType.value = options.pageType || '';
    type.value = options.type || 'member';
    cardType.value = options.type == 'hospital' ? '14' : '1';
    cardTypeName.value = options.type == 'hospital' ? '住院号' : '就诊卡';
    fromComponent.value = options.fromComponent || false;
    currentUser.value = app.globalData.currentUser || {};
    
    uni.setNavigationBarTitle({
        title: options.type == 'hospital' ? '选择住院号' : options.type == 'card' ? '选择就诊卡' : '选择就诊人'
    });
});

onShow(() => {
    if (app.globalData.logSuccess) {
        main();
    } else {
        app.loginReadyCallBack = () => main();
    }
});

onUnload(() => {
    if (app.globalData.cardDeleted) {
        let pages = getCurrentPages();
        if (pages.length >= 2) {
            let goPage = pages[pages.length - 2];
            // Try to call refresh if available on the page instance
            // @ts-ignore
            if (typeof goPage.$vm?.refresh == 'function') {
                // @ts-ignore
                goPage.$vm.refresh();
            } else if (typeof (goPage as any).refresh == 'function') {
                 (goPage as any).refresh();
            }
        }
    }
});

const main = async () => {
    let _patientInfoIndex = '';
    let _type = type.value;
    
    // Use usePreserMember hook instead of publicFn.getMember
    // Assuming usePreserMember returns the member list directly
    let resp: any = await usePreserMember();
    
    if (!common.isEmpty(resp)) {
        if (_type != 'member') {
            resp.forEach((item: any, index: number) => {
                if (item.userMemberList && item.userMemberList[0] && item.userMemberList[0].isDefaultMember == 1) {
                    _patientInfoIndex = index as any;
                }
                if (!common.isEmpty(item.data_1)) {
                    item.data_1.forEach((childItem: any) => {
                        //健康卡位数太长转换下
                        if (childItem.cardType == 16 && childItem.cardNo.length > 9) {
                            childItem.cardNo = childItem.cardNo.replace(/\*{3,}/g, '***');
                        }
                    });
                }
            });
        }
    }
    
    // 就诊人排序
    resp = resp.sort(function (a: any, b: any) {
        if (a.memberType !== b.memberType) {
            return a.memberType < b.memberType ? -1 : 1; // 如果类型不同，则按照字母顺序返回
        } else {
            return a.memberType == 1 ? -1 : b.userMemberList[0].isDefaultMember - a.userMemberList[0].isDefaultMember; // 如果类型相同，则比较名称
        }
    });
    
    const asyncRequests = resp.map(async (item: any) => getQueryMemberHeaderInfoFunc(item));
    await Promise.all(asyncRequests);
    
    patientInfoIndex.value = _patientInfoIndex;
    patientInfoList.value = resp || [];
    showCon.value = true;
};

// 获取信用授权数据
const getQueryMemberHeaderInfoFunc = async (item: any) => {
    if (item.memberType == 1) {
        let { resData } = await queryMemberHeaderInfo({
            memberId: item.memberId,
            accountSn: item.accountSn
        });
        item.authQuantity = resData.RespCode == 10000 && resData.Data && resData.Data[0] ? resData.Data[0].userCount : 0;
    }
    return item;
};

/**
 * 列表点击
 */
const optionClick = async (item: any, index: number, tag: string, childItem?: any) => {
    let _type = type.value;
    
    if (tag == 'member') {
        if (_type == 'member') {
            app.globalData.currentUser = item;
        } else {
            let resp = item.data_1 || [];
            if (common.isEmpty(item.data_1)) {
                // Fetch cards
                let { resData } = await queryMemberCardList_V3({ memberId: item.memberId });
                if (resData.RespCode == 10000) {
                    resp = resData.Data || [];
                }
            }
            
            if (common.isEmpty(resp) || (common.isNotEmpty(resp) && resp.filter((ele: any) => ele.cardType == cardType.value).length == 0)) {
                // 首页进入切换就诊人，设置最好操作人
                if (pageType.value == 'home') {
                    await setDefaultMember(item);
                    common.navigateBack(1, 'currentUser', item);
                } else {
                    common.showModal(`查无${cardType.value == '14' ? '住院号' : '就诊卡'}`);
                }
                return;
            }
            
            resp.forEach((cItem: any) => {
                //健康卡位数太长转换下
                if (cItem.cardType == 16 && cItem.cardNo.length > 9) {
                    cItem.cardNo = cItem.cardNo.replace(/\*{3,}/g, '***');
                }
            });
            
            patientInfoList.value[index].data_1 = resp;
            patientInfoIndex.value = index;
            // Force update if needed, but Vue 3 proxy should handle it
            return;
        }
    }
    
    // 卡点击
    if (tag == 'card' && childItem) {
        item = common.mergeObject(item, childItem);
        app.globalData.currentUser = item;
        
        if (pageType.value == 'home') {
            await setDefaultMember(item);
        }
        // 跳转CRM
        else if (pageType.value == 'crm') {
            await setDefaultMember(item);
            common.goToUrl("/pagesCrm/st1/business/myFollowUp/home/home", {
                skipWay: "redirectTo"
            });
            return;
        }
    }
    
    if (fromComponent.value) {
        /**如果从组件进入页面 重新选择就诊人后直接返回 */
        common.navigateBack(1, 'currentUser', item);
    } else {
        if (app.globalData.toUrl) {
            common.goToUrl(app.globalData.toUrl, {
                skipWay: "redirectTo"
            });
            return;
        }
        if (pageType.value == "pennant") {
            item.Check = true;
        }
        common.navigateBack(1, 'currentUser', item);
    }
};

// 设置默认就诊人 默认就诊卡
const setDefaultMember = async (item: any) => {
    let querData = {
        accountSn: item.accountSn,
        memberId: item.memberId
    };
    // 设置默认就诊人
    let { resData } = await setDefaultMemberV3(querData);
    if (resData.RespCode == "10000") {
        if (item.cardNo) {
            let data = {
                memberId: item.memberId,
                cardNo: item.cardNo,
                cardType: item.cardType,
                encryptionStore: item.encryptionStore,
            };
            await setDefaultClinicCard_V3(data);
        }
        // 设置完默认就诊人 重新查询并保存全局就诊人数据信息
        await usePreserMember();
        app.globalData.currentUser = item;
    }
};

const jumpAddPatient = () => {
    app.globalData.isSelectAdd = true;
    common.goToUrl(`/pagesPersonal/st1/business/patientManagement/selecteBindCardMode/selecteBindCardMode`);
};

/**
 * 点击本人 去管理
 */
const forWard = (router: string, memberInfo: any) => {
    // 存储本人数据
    app.globalData.myInfo = memberInfo;
    let url: string | null = null;
    if (router == 'creditIndex') {
        url = `/pagesPersonal/st1/business/creditManagement/${router}/${router}`;
    } else if (router == 'authorizeIndex') {
        url = `/pagesPersonal/st1/business/authorizeMangement/${router}/${router}`;
    }
    if (url) common.goToUrl(url);
};
</script>

<style lang="scss" scoped>
	
	.noData {
	  margin-top: -180upx;
	}
	
	.container {
	  width: 100%;
	  height: auto;
	  min-height: 100%;
	  background: #f1f1f6;
	  position: relative;
	}
	
	.patient_list {
	  border-radius: 24upx;
	  overflow: hidden;
	  position: relative;
	  margin: 30upx;
	  z-index: 100;
	}
	
	.patient_list:last-child {
	  border-bottom: none;
	}
	
	.patient_info {
	  height: 88upx;
	  justify-content: space-between;
	  align-items: flex-start;
	}
	
	.border-bottom:last-child::after {
	  border-top: 0px !important;
	}
	
	.public_card_img {
	  width: 88upx;
	  height: 88upx;
	  margin-right: 24upx;
	  flex-shrink: 0;
	}
	
	.name_tel text:nth-child(1) {
	  font-size: 32upx;
	  font-weight: bold;
	  color: #222326;
	  margin-right: 30upx;
	}
	
	.name_tel text:nth-child(2) {
	  font-size: 32upx;
	  color: #222326;
	}
	
	.idCard {
	  font-size: 30upx;
	  color: #62626D;
	  margin-top: 10upx;
	  display: inline-block;
	}
	
	.public_btn {
	  margin: 60upx 30upx;
	}
	
	.defaultText{
	  width: 72upx;
	  height: 36upx;
	  line-height: 36upx;
	  text-align: center;
	  background: #F4FAED;
	  border-radius: 4upx;
	  position: absolute;
	  right: 36upx;
	  font-size: 26upx;
	  font-family: PingFang SC;
	  font-weight: 500;
	  color: var(--dominantColor);
	}
	.patientInfoBox{
	  position: relative;
	  background:#fff;
	  padding: 50upx 30upx;
	}
	.patientCardBox{
	  background:#fff;
	  padding: 1upx 30upx;
	}
	.patientCardBox_list{
	  padding: 0upx 30upx;
	  box-sizing: border-box;
	  margin-bottom: 30upx;
	  background: #F8F8FA;
	  border-radius: 10upx;
	  height: 110upx;
	  line-height: 110upx;
	  position: relative;
	}
	.patientCardBox_list .public_right_img{
	 right: 30upx;
	}
	.transform90{
	  transform: rotateZ(90deg);
	}
	.icon_roundHook{
	  width: 30upx;
	  height: 30upx;
	  position: absolute;
	  right: 30upx;
	  top: 0;
	  bottom: 0;
	  margin: auto 0;
	}
	
	
	.relativesBox{
	  margin: 30upx;
	  font-size: 30upx;
	  font-weight: 600;
	}
	.relativesBox .icon_relatives{
	  width: 42upx;
	  height: 39upx;
	  margin-right: 18upx;
	}
	
	
	.personallyBox{
	  background-color: #fff;
	  padding: 1upx 30upx;
	}
	.noPersonallyBox{
	  border-radius: 0 0 24upx 24upx;
	  padding-bottom: 20upx;
	}
	.personallyBox .moduleBox{
	  height: 120upx;
	  position: relative;
	  border-radius: 24upx;
	  overflow: hidden;
	  padding: 0 24upx;
	}
	.personallyBox .bg{
	  position: absolute;
	  width: 100%;
	  height: 100%;
	  opacity: .2;
	  left: 0;
	  top: 0;
	}
	.personallyBox .moduleBox{
	  font-size: 24upx;
	  margin-bottom: 30upx;
	}
	.personallyBox .moduleInfo_txt{
	  font-size: 28upx;
	  font-weight: 600;
	  margin-bottom: 8upx;
	}
	.personallyBox .moduleBox_btn{
	  padding: 12upx 18upx;
	  border-radius: 20upx;
	}
</style>
