<!-- 切换医院 -->
<template>
    <view>
        <nav-bar
            :navbar-data="navbarData"
            id="nav-bar"
            @handleReRender="initPage($event, { tagId: 'nav-bar' })"
            @checkForNewMessage="checkForNewMessage($event, { tagId: 'nav-bar' })"
            @handleChangeHosp="handleChangeHosp($event, { tagId: 'nav-bar' })"
        ></nav-bar>
        <view class="page-bg"></view>
        <view class="switch-hospital" :style="'padding-top: ' + navHeight + 'px;'">
            <!-- <view class="search-box">
			  <van-search clearable value="{{ searchValue }}" input-align="center" placeholder="请输入医院搜索关键词" bind:search="searchHospital" bind:change="searchHospital" bind:clear="searchHospital" />
			</view> -->
            <view class="switch-hospital-wrapper" v-if="searchStatus">
                <view class="province">
                    <view class="hospital-list">
                        <template v-if="searchList.length > 0" v-for="(item, index) in searchList" :key="index">
                            <view class="hospital-card" @tap="switchHospital" :data-hosp="item" data-type="other">
                                <view class="hospital-logo">
                                    <image :src="imgHost + '/images/' + (item.logoUrl ? item.logoUrl : 'logo/logo1.png')" mode="scaleToFill" />
                                </view>
                                <view class="hospital-info">
                                    <view class="hosp-info-name">
                                        <view class="name">{{ item.hospDesc }}</view>
                                        <van-icon class="arrow-right" name="arrow" size="24rpx" color="#666666" />
                                    </view>
                                    <view class="hosp-info-btm">
                                        <view class="time">接诊时间：{{ item.businessHoursInfo }}</view>
                                        <view class="addr">医院地址：{{ item.hospAddress }}</view>
                                        <view class="distance" v-if="item.distance">
                                            <image :src="imgHost + '/images/icon/icon-location.png'" mode="scaleToFill" />
                                            <text>{{ item.distance }}km</text>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </template>
                        <template v-if="searchList.length == 0">
                            <view class="hospital-card no-data" v-if="!loading && currentProvinceHospList.length == 0">
                                <text>未搜索医院</text>
                            </view>
                        </template>
                    </view>
                </view>
            </view>
            <view class="switch-hospital-wrapper" v-if="!searchStatus">
                <view class="current-hospital">
                    <view class="current-hospital-header">当前医院</view>
                    <view class="hospital-name">{{ userData && userData.hospDesc }}</view>
                </view>
                <view class="province">
                    <view class="province-hospital-header">
                        <view class="current-province-title">当前省份</view>
                        <!-- <region-picker level="province" :value="provinceName" @change="provinceChange">
                            <view class="choose-province">
                                <view class="province-name">{{ provinceName }}</view>
                                <van-icon name="arrow" size="26rpx" color="#007FCC" />
                            </view>
                        </region-picker> -->
						<view class="choose-province" @tap="handleAddressSelectFocus">
						    <view class="province-name">{{ provinceName[0] ? provinceName[0]:'请选择省份' }}</view>
						    <van-icon name="arrow" size="26rpx" color="#007FCC" />
						</view>
                    </view>
                    <view class="hospital-list">
                        <template v-for="(item, index) in currentProvinceHospList" :key="index">
                            <view class="hospital-card" @tap="switchHospital" :data-hosp="item" data-type="current">
                                <view class="hospital-logo">
                                    <image :src="imgHost + '/images/' + (item.logoUrl ? item.logoUrl : 'logo/logo1.png')" mode="scaleToFill" />
                                </view>
                                <view class="hospital-info">
                                    <view class="hosp-info-name">
                                        <view class="name">{{ item.hospDesc }}</view>
                                        <van-icon class="arrow-right" name="arrow" size="24rpx" color="#666666" />
                                    </view>
                                    <view class="hosp-info-btm">
                                        <view class="time">接诊时间：{{ item.businessHoursInfo }}</view>
                                        <view class="addr">医院地址：{{ item.hospAddress }}</view>
                                        <view class="distance" v-if="item.distance">
                                            <image :src="imgHost + '/images/icon/icon-location.png'" mode="scaleToFill" />
                                            <text>{{ item.distance }}km</text>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </template>
                        <view class="hospital-card no-data" v-if="currentProvinceHospList.length == 0">
                            <text>本省/市内暂无医院</text>
                        </view>
                    </view>
                </view>
                <!-- <view class="province">
        <view class="current-hospital-header">
          <text>选择{{ showOtherText? '其他省市':'' }}医院</text>
        </view>
        <view class="hospital-list">
          <template wx:for="{{ allHospData && allHospData.otherProvinceHospList }}" wx:key="hospitalCard">
            <view class="hospital-card" bind:tap="switchHospital" data-hosp="{{ item }}" data-type="other">
              <view class="hospital-logo">
                <image src="{{ imgHost +'/images/'+(item.logoUrl ? item.logoUrl : 'logo/logo1.png') }}" mode="scaleToFill" />
              </view>
              <view class="hospital-info">
                <view class="hosp-info-name">
                  <view class="name">{{ item.hospDesc }}</view>
                  <van-icon name="arrow" size="24rpx" color="#666666" />
                </view>
                <view class="hosp-info-btm">
                  <view class="time">接诊时间：{{ item.businessHoursInfo }}</view>
                  <view class="addr">医院地址：{{ item.hospAddress }}</view>
                  <view class="distance" wx:if="{{ item.distance }}">
                    <image src="{{ imgHost +'/images/icon/icon-location.png' }}" mode="scaleToFill" />
                    <text>{{ item.distance }}km</text>
                  </view>
                </view>
              </view>
            </view>
          </template>
        </view>
      </view> -->
            </view>
        </view>
		<addressSelectionControl ref="addressSelectionControl" :selected-stop="1" @addressBoxAssignment="addressBoxAssignment" />
    </view>
</template>

<script>
import { mapGetters } from 'vuex';
import NavBar from '@/components/navBar/index';
import addressSelectionControl from '@/components/addressSelectionControl/index';
import VanIcon from '@/components/icon/index';
import Utils from '@/utils/utils';
import httpConfig from '@/utils/httpConfig';
import { dealHospData, getHospList } from '@/utils/common';
const app = getApp();
export default {
    components: {
        'nav-bar': NavBar,
		'addressSelectionControl': addressSelectionControl,
		'van-icon': VanIcon
    },
    data() {
        return {
            pageLoading: true,
            navHeight: app.globalData.navHeight,
            spaceHeight: app.globalData.spaceHeight,
            navTitleHeight: app.globalData.navTitleHeight,
            statusBarHeight: app.globalData.statusBarHeight,
            navbarData: {
                isGoHome: true,
                isGoBack: true,
                title: '选择医院',
                background: 'none'
            },
            imgHost: httpConfig.imgHost,
            userData: {
                hospDesc: ''
            },
            cacheHospData: undefined,
            showOtherText: true,
            searchValue: '',

            // 搜索输入的关键词
            searchStatus: false,

            // 搜索状态
            searchList: [],

            // 搜索结果数据
            provinceName: [''],

            // 省份名称
            currentProvinceHospList: [],

            // 当前省份医院列表
            loading: true,

            allHospitalData: '',
            refresh: 0,
			cardDetails: {},
			addressDesc: "",
        };
    },
    onLoad() {
        const self = this;
        uni.showLoading({
            title: '请稍后...'
        });
    },
    onShow() {
        const _this = this;
        const userData = _this.$cache.get('userData');
        if (userData) {
            _this.setData({
                userData
            });
        }
        _this.initHospData().then(() => {
            uni.hideLoading();
            _this.setData({
                pageLoading: false
            });
        });
    },
    onPageScroll(e) {
        const { navbarData } = this;
        if (e.scrollTop > 30) {
            navbarData.background = '#007FCC';
        } else {
            navbarData.background = 'none';
        }
        this.setData({
            navbarData
        });
    },
    methods: {
        initHospData() {
            return new Promise(async (resolve) => {
                let currentLocationData = this.$cache.get('currentLocationData');
                let isDistance = false;
                if (!currentLocationData) {
                    isDistance = true;
					//#ifdef MP
                    await Utils.getPositionLocation().then(res => {
						this.initDeal(isDistance)
					});
					//#endif
					
					//#ifdef H5
					await Utils.getLocation()
						.then(res => {
							this.initDeal(isDistance)
						})
						.catch(error => {
							this.initDeal(isDistance)
							uni.hideLoading();
						})
					//#endif
                } else {
					this.initDeal(isDistance)
				}
                resolve();
            });
        },
		
		async initDeal(isDistance) {
			const _this = this;
			let allHospitalData = _this.$cache.get('allHospitalData');
			let currentLocationData = _this.$cache.get('currentLocationData');
			if(currentLocationData) {
				const { currentLatlng, province, adcode } = currentLocationData.currentLocation;
				let currentProvinceHospList = [];
				console.log(currentLatlng, province);
				if (!allHospitalData) {
				    await getHospList(app).then(() => {
						this.initDeal(true)
					});
				} else if ((allHospitalData && !allHospitalData[0]?.distance) || isDistance) {
				    await dealHospData(allHospitalData, currentLatlng, province).then(() => {
				        allHospitalData = _this.$cache.get('allHospitalData');
				        currentProvinceHospList = allHospitalData.filter((item) => item.province.includes(province));
				    });
				} else{
				    currentProvinceHospList = allHospitalData.filter((item) => item.province.includes(province));
				}
				_this.setData({
				    loading: false,
				    allHospitalData,
				    currentProvinceHospList,
				    provinceName: [province]
				});
			} else {
				if(!allHospitalData) {
					await dealHospData(allHospitalData, '', '').then(() => {
					    allHospitalData = _this.$cache.get('allHospitalData');
						if(province) {
							currentProvinceHospList = allHospitalData.filter((item) => item.province.includes(province));	
						}
					});
				} else {
					_this.setData({
					    loading: false,
					    allHospitalData,
					    currentProvinceHospList,
					    provinceName: ['']
					});
				}
			}
		},

        searchHospital: Utils.debounce(function (e) {
            let searchValue = e.detail;
            const cacheHospData = this.$cache.get('cacheHospData');
            let concatHospData = [].concat(cacheHospData.currentHospList, cacheHospData.currentProvinceHospList, cacheHospData.otherProvinceHospList);
            let resHospData = [];
            if (searchValue) {
                resHospData = concatHospData.filter(
                    (item) => item.hospDesc.indexOf(searchValue) > -1 || item.province.indexOf(searchValue) > -1 || item.city.indexOf(searchValue) > -1
                );
                this.setData({
                    searchValue,
                    searchStatus: true,
                    searchList: resHospData
                });
            } else if (!searchValue) {
                this.setData({
                    searchValue,
                    searchStatus: false,
                    searchList: []
                });
            }
        }, 500),

        switchHospital(e) {
            const hospData = e.currentTarget.dataset.hosp;
            const userData = this.$cache.get('userData');
            const allHospitalData = this.$cache.get('allHospitalData');
            // 根据距离进行排序
            allHospitalData.sort((a, b) => {
                return parseFloat(a.distance) - parseFloat(b.distance);
            });
            this.$cache.set('allHospitalData', allHospitalData);
            this.$cache.set('userData', {
                ...(userData || {}),
                province: hospData.province,
                latitude: hospData.latitude,
                longitude: hospData.longitude,
                businessHoursInfo: hospData.businessHoursInfo,
                emergBusTimeInfo: hospData.emergBusTimeInfo,
                nightBusTimeInfo: hospData.nightBusTimeInfo,
                hospID: hospData.hospID,
                hospDesc: hospData.hospDesc,
                hisHospID: hospData.hisHospID,
                hospAddress: hospData.hospAddress,
                telephone: hospData.telephone,
                menuMode: hospData.menuMode,
                serviceCallTips: hospData.serviceCallTips,
                serviceCall: hospData.serviceCall,
                upLoadUrl: hospData.upLoadUrl,
                downLoadUrl: hospData.downLoadUrl,
                pubAccountDate: hospData?.pubAccountDate || {},
                ifHLWConsultation: hospData.ifHLWConsultation,
                logoUrl: hospData?.logoUrl,
				guideHospConfig: hospData?.guideHospConfig
            });
            Utils.setInsuStorage(hospData); // 设置医保配置数据
			app.globalData.guideHospConfig = hospData.guideHospConfig;
            app.globalData.SDKAPPID = +hospData.imAppID;
            app.globalData.SECRETKEY = hospData.imSecret;
			
			console.log('切换医院执行完成===')
			
			// #ifdef MP
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];
            if (prevPage) {
                prevPage.setData({
                    refresh: 1
                });
            }
			uni.navigateBack({
			    delta: -2
			});
			// #endif
			
			// #ifdef H5
			uni.navigateBack({
			    delta: 1
			});
			this.$cache.set('refresh', 1)
			console.log('refresh === ', this.$cache.get('refresh'))
			// #endif
        },

        getChooseCurrentProvinceHosp(province) {
            const allHospitalData = this.$cache.get('allHospitalData');
            const resChooseCurrentProvinceHospArr = allHospitalData.filter((item) => item.province.includes(province));
            this.setData({
                currentProvinceHospList: resChooseCurrentProvinceHospArr
            });
        },

        provinceChange(e) {
            this.setData({
                provinceName: [e.detail.value[0]]
            }, () => {
                this.getChooseCurrentProvinceHosp(e.detail.value[0]);
            });
        },
		
		handleAddressSelectFocus() {
		    this.$refs.addressSelectionControl.onClickShow()
		},
		  
		// 给地址选框赋值
		addressBoxAssignment() {
		    // 获取城市描述
		    let cityData = this.$refs.addressSelectionControl.exportCitySelectInfo("ID");
		    let { cardDetails } = this;
		    cardDetails.location = cityData && cityData.addressDesc ? cityData.addressDesc : "";
		    console.log('addressBoxAssignment === ', cardDetails, cityData)
		    this.setData({
				cardDetails: { ...cardDetails, ...cityData }, 
				addressDesc: cardDetails && cardDetails.location ? cardDetails.location : "" 
			}, () => {
		        this.$refs.addressSelectionControl.onClickHide(); // 关闭城市弹窗
				let province = ''
				if(cityData.provDesc && cityData.provDesc.indexOf('省')) {
					province = cityData.provDesc.replace('省','')
				} else if(cityData.provDesc && cityData.provDesc.indexOf('市')){
					province = cityData.provDesc.replace('市','')
				}
				this.setData({
				    provinceName: [province]
				}, () => {
				    this.getChooseCurrentProvinceHosp(province)
				});
		    })
		},
		
        initPage(e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            console.log('占位：函数 initPage 未声明');
        },

        checkForNewMessage(e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            console.log('占位：函数 checkForNewMessage 未声明');
        },

        handleChangeHosp(e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            console.log('占位：函数 handleChangeHosp 未声明');
        }
    }
};
</script>
<style lang="scss">
.page-bg {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 0;
    width: 100%;
    height: 580rpx;
    background: linear-gradient(to top, #f7f7f7, #007fcc);
}
.switch-hospital {
    position: relative;
    z-index: 1;
    display: flex;
    flex-direction: column;
	padding-bottom: 40px;
	/* #ifdef MP */
    padding-bottom: calc(80rpx + env(safe-area-inset-bottom));
	/* #endif */
}

.search-box {
    margin-bottom: 20rpx;
}

.switch-hospital-wrapper {
    padding: 0 20rpx;
}

.current-hospital-header,
.province-hospital-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 120rpx;
    line-height: 120rpx;
}

.province-hospital-header {
    padding: 0 20rpx 0 30rpx;
}

.current-province-title {
    font-weight: bold;
    font-size: 28rpx;
    color: #333333;
}

.choose-province {
    display: flex;
    color: #007fcc;
}

.current-hospital {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100rpx;
    line-height: 100rpx;
    background: #ffffff;
    border-radius: 10rpx;
    padding: 0 30rpx;
    margin-top: 40rpx;
}

.current-hospital-header .btn-search {
    width: 36rpx;
    height: 33rpx;
    background-size: 100%;
    margin-right: 20rpx;
}

.current-hospital .hospital-name {
    color: #007fcc;
}

.hospital-list {
    display: flex;
    flex-direction: column;
}

.hospital-list .hospital-card {
    box-sizing: border-box;
    display: flex;
    height: 220rpx;
    border-radius: 12rpx;
    padding: 25rpx 20rpx;
    margin-bottom: 24rpx;
    background-color: #fff;
}

.hospital-list .hospital-card .hospital-logo {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 170rpx;
    height: 170rpx;
    background: #f7f7f7;
    border-radius: 10rpx;
    margin-right: 20rpx;
}

.hospital-list .hospital-card .hospital-logo image {
    width: 121rpx;
    height: 113rpx;
}

.hospital-list .hospital-card.no-data {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #b4b4b4;
}

.hospital-info {
    position: relative;
    flex: 1;
    width: 454rpx;
}

.hospital-info .hosp-info-name {
    display: flex;
    justify-content: space-between;
    font-weight: bold;
    font-size: 30rpx;
    color: #333333;
    line-height: 32rpx;
    margin-bottom: 15rpx;
}

.hospital-info .hosp-info-name .arrow {
    position: absolute;
    right: 0;
    transform: rotate(0deg);
}

.hospital-info .hosp-info-btm .time {
    font-weight: 400;
    font-size: 20rpx;
    color: #333333;
    line-height: 36rpx;
}
.hospital-info .hosp-info-btm .addr {
    font-weight: 400;
    font-size: 20rpx;
    color: #333333;
    line-height: 36rpx;
}
.hospital-info .hosp-info-btm .distance {
    position: absolute;
    display: flex;
    align-items: center;
    right: 0;
    bottom: 0;
}
.hospital-info .hosp-info-btm .distance image {
    width: 21rpx;
    height: 23rpx;
    margin-right: 6rpx;
}
.hospital-info .hosp-info-btm .distance text {
    font-weight: 400;
    font-size: 20rpx;
    color: #007fcc;
    line-height: 32rpx;
}
</style>
