<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { reactive, ref, watch, onMounted, getCurrentInstance } from "vue";
import searchBar from "../components/search_bar.vue";
import { countCity, stadiumFind } from "../api";
import { routeTo, showModal } from '@/utils/polish';
import { debounce } from '@/utils';
const cityLs = ref([]);
const cityName = ref(''); // 当前城市
const stadiumKey = ref(''); // 搜索门店
const stadiumLs = ref([]);
const appid = tt.getEnvInfoSync()?.microapp?.appId ?? '';

let ticketInfo = null; // 票券信息

watch(cityName, val=>{
    stadiumLs.value = [];
    stadiumFind({
        data: {
            appid: appid,
            city: val ?? '',
            key: stadiumKey.value ?? '',
        },
    })
    .then(sRes=> {
        if(val !== cityName.value) return; // 值在多次变化时候直接丢掉
        let _ls = sRes?.data?.list || [];
        if(!_ls?.length) return showModal({ content: '暂无门店' });
        stadiumLs.value = _ls;
    })
});

onLoad(opts => {
    console.log('opts--->', opts);
    countCity({ data: {} })
    .then(res=>{
        console.log('城市列表--->', res);
        return cityLs.value = res.data?.list || [];
    })
    .then(cityLs => {
        if(!cityLs?.length) return showModal({ content: '暂无城市' });
        cityName.value = cityLs[0]?.city ?? '';
    })
});

onMounted(() =>{
    const instance = getCurrentInstance().proxy
    const eventChannel = instance.getOpenerEventChannel();
    eventChannel.on('dataForGrouponStadiums', data => {
        ticketInfo = data?.ticket ?? null;
    })
})
// 获取营业时间
function getBusinessTime(stadiumInfo){
    let _businessTime = stadiumInfo?.business_times || [];
    let _str = ''
    if(_businessTime?.length){
        _businessTime.forEach(el =>{
            let _wStr = '', _tStr = '';
            if(el?.weeks?.length){
                _wStr = el.weeks.join('、') || '';
            }
            if(el?.stimes?.length){
                el.stimes.forEach((sRes, sIdx) =>{
                    _tStr += `${sRes.start || ''}-${sRes.end || ''}`;
                    _tStr += sIdx === el.stimes.length -1 ? '；' : '，'
                })
            }
            _str += `${_wStr || ''} ${_tStr || ''}`;
        })
    }
    return _str || '-';
}
// 拨打电话
function phoneCall(phone) {
    if(!phone) return showModal({ content: '暂无联系电话' });
    uni.makePhoneCall({ phoneNumber: phone, 
        success: () => {
            console.log('拨打电话成功');
        },
        fail: (err) => {
            showModal({ content: err?.errMsg || '拨打电话失败' });
            console.error('拨打电话失败', err);
        }
    });
}
// 打开地图
function openMap(res){
    uni.openLocation({
        latitude: +(res?.lat || 0),
        longitude: +(res?.lng || 0),
        name: res?.name || '',
        address: res?.address || '',
        success: () => {
            console.log('打开地图成功');
        },
        fail: (err) => {
            showModal({ content: err?.errMsg || '打开地图失败' });
            console.error('打开地图失败', err);
        }
    });
}
// 搜索门店
function searchKeyConfrim(val){
    stadiumLs.value = [];
    stadiumFind({
        data: { 
            appid: appid, 
            city: cityName.value, 
            key: val,
        },
    })
    .then(stadiumRes => {
        let _ls = stadiumRes?.data?.list || [];
        stadiumLs.value = _ls;
    })
}
// 跳转到下一个步骤
function toNextStep(stadiumInfo){
    showModal({
        content: `是否确认选择${stadiumInfo?.name ?? '-'}作为核销门店？`,
        confirmText: '确认',
        cancelText: '取消',
        showCancel: true,
        success: res=>{
            if(!res.confirm) return;
            let _mt = ticketInfo?.merchandise_type;
            let _url = _mt === 0 ? '/subpackage/groupon/pages/confirm_order/ticket'
                     : _mt === 1 ? '/subpackage/groupon/pages/site_select' : '';

            uni.navigateTo({
                url: _url,
                success: res => {
                    res.eventChannel.emit('dataFromGrouponStadiums', {
                        stadium: {
                            id: stadiumInfo?.id || '',
                            name: stadiumInfo?.name || '',
                            address: stadiumInfo?.address || '',
                            logo: stadiumInfo?.logo || '',
                        },
                        ticket: ticketInfo
                    })
                }
            });
        }
    })
}
</script>

<template>
    <view class="stadium-select">
        <view class="ss-search">
            <search-bar
                :cityLs="cityLs"
                v-model:city="cityName"
                v-model:iptkey="stadiumKey"
                @input:confirm="searchKeyConfrim"
            ></search-bar>
        </view>
        <view class="stadium-ls">
            <view class="sl-item" v-for="(e, i) in stadiumLs" :key="i" @click="toNextStep(e)">
                <view class="si-info">
                    <view class="si-top">
                        <image class="st-logo" v-if="e.logo" mode="aspectFit" :src="e.logo"></image>
                        <view class="st-name">{{ e?.name || '-' }}</view>
                    </view>
                    <view class="si-line">
                        <view class="sl-icon">&#xe60f;</view>
                        <view class="sl-txt">{{ getBusinessTime(e) }}</view>
                    </view>
                    <view class="si-line">
                        <view class="sl-icon">&#xe600;</view>
                        <view class="sl-txt">{{ e.address || '-' }}</view>
                    </view>
                </view>
                <view class="si-right">
                    <view class="sr-txt">去核销</view>
                    <view class="sr-icons">
                        <view class="si-item" @click.stop="phoneCall(e.contact_mobile)">&#xe605;</view>
                        <view class="si-item" @click.stop="openMap(e)">&#xe672;</view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<style lang="scss" scoped>
.stadium-select{
    .ss-search{
        position: sticky;
        left: 0;
        top: 0;
    }
    .stadium-ls{
        padding: 24upx;
        @include isPd(24upx);
        .sl-item{
            padding: 24upx;
            border-radius: 20upx;
            background: #fff;
            @include ctf;
            &+.sl-item{
                margin-top: 24upx;
            }
            .si-info{
                flex-grow: 1;
                padding-right: 32upx;
                border-right: 1px solid #EAEAEA;
                .si-top{
                    margin-bottom: 22upx;
                    @include ctf;
                    .st-logo{
                        flex-shrink: 0;
                        margin-right: 20upx;
                        width: 36upx;
                        height: 36upx;
                    }
                    .st-name{
                        flex-grow: 1;
                        @include flcw(32upx, 44upx, #333, 500);
                        @include tHide;
                    }
                }
                .si-line{
                    display: flex;
                    &+ .si-line{
                        margin-top: 16upx;
                    }
                    @include locationIcon;
                    @include clockIcon;
                    .sl-icon{
                        margin-right: 12upx;
                        flex-shrink: 0;
                        flex-grow: 0;
                        width: 34upx;
                        height: 34upx;
                        font-family: locationIcon, clockIcon;
                        font-size: 28upx;
                        color: #9A9A9D;
                    }
                    .sl-txt{
                        @include flcw(24upx, 34upx, #9A9A9D);
                    }

                }
            }
            .si-right{
                flex-shrink: 0;
                padding-left: 30upx;
                padding-right: 12upx;
                .sr-icons{
                    margin-top: 12upx;
                    @include ctf(center);
                    @include phoneIcon;
                    @include navigationIcon;
                    .si-item{
                        margin: 0 12upx;
                        width: 36upx;
                        height: 36upx;
                        text-align: center;
                        line-height: 36upx;
                        border-radius: 50%;
                        font-family: phoneIcon, navigationIcon;
                        font-size: 24upx;
                        background-color: rgba($color: #FE2B54, $alpha: .05);
                        color: #FE2B54;
                    }
                }
                .sr-txt{
                    text-align: center;
                    @include flcw(24upx, 34upx, #666);
                }
            }
            
        }
    }
}
</style>
