<template>
    <view class="turnover-container">
        <view class="tc-tab" v-if="storeList.length > 1">
            <view :class="[tabID == 4?'active':'']" @click="tabChange(4)">品牌统计</view>
            <view :class="[tabID == 3?'active':'']" @click="tabChange(3)">门店统计</view>
        </view>
        <view class="tc-total-section">
            <!-- 品牌 -->
            <view class="tts-address" v-if="tabID == 4&&storeList.length > 1"> 
                <image class="ta-logo" :src="totalData.logo" mode="aspectFit"></image>
                <view>{{totalData.brand_or_stadium_name || '-'}}</view>
            </view>
            <!-- 仅有一家店铺情况下，没有品牌查看权限 -->
            <view class="tts-address" v-else-if="tabID == 3&&storeList.length ==1">
                <image class="ta-logo" :src="totalData.logo" mode="aspectFit"></image>
                <view>{{curSelectStore.name || '-'}}</view>
                <!-- <image mode="aspectFit" src="/static/images/icon/arrow_b2.png"></image> -->
            </view>
            <picker v-else-if="tabID == 3" :range="storeList" range-key="name" @change="storeChange">
                <view class="tts-address">
                    <image class="ta-logo" :src="totalData.logo" mode="aspectFit"></image>
                    <view>{{curSelectStore.name || '-'}}</view>
                    <image mode="aspectFit" src="/static/images/icon/toggle.png"></image>
                </view>
            </picker>

            <!-- 20230707 pm:商家助手品牌统计跟门店统计这块隐藏掉 -->
            <block v-if="false">
                <view class="tts-money">
                    <view>{{totalData.brand_or_stadium_duration || '-'}}</view>
                    <view>
                        <text>总收入</text>
                        <image mode="aspectFit" src="/static/images/icon/question_mark.png" @click="showQuestionModal"></image>
                    </view>
                    <view><text>¥</text>{{totalData.count_type_actual_income_amount || '0'}}</view>
                </view>
                <view class="tts-preview-ls">
                    <view class="tpl-item">
                        <view class="ti-name">
                            <text>线上</text>
                            <image mode="aspectFit" @click="incomeQusModal(totalData.online_tips)" src="/static/images/icon/question_mark.png"></image>
                        </view>
                        <view class="ti-price">¥{{totalData.online_actual_income_amount || '0'}}</view>
                    </view>
                    <view class="tpl-item">
                        <view class="ti-name">
                            <text>线下</text>
                            <image mode="aspectFit" @click="incomeQusModal(totalData.offline_tips)" src="/static/images/icon/question_mark.png"></image>
                        </view>
                        <view class="ti-price">¥{{totalData.offline_actual_income_amount || '0'}}</view>
                    </view>
                    <view class="tpl-item">
                        <view class="ti-name">
                            <text>联营</text>
                            <image mode="aspectFit" @click="incomeQusModal(totalData.joint_tips)" src="/static/images/icon/question_mark.png"></image>
                        </view>
                        <view class="ti-price">¥{{totalData.joint_actual_income_amount || '0'}}</view>
                    </view>
                </view>
            </block>
            
            
        </view>
        <view class="tc-info-section">
            <view class="tis-tab">
                <view :class="[timeTabIdx == 0?'active':'']" @click="timeTabChange(0)">日报</view>
                <view :class="[timeTabIdx == 1?'active':'']" @click="timeTabChange(1)">近7天</view>
                <view :class="[timeTabIdx == 2?'active':'']" @click="timeTabChange(2)">月报</view>
                <view :class="[timeTabIdx == 3?'active':'']" @click="timeTabChange(3)">年报</view>
            </view>
            <view class="tis-data">
                <view class="td-date" v-if="timeTabIdx == 0 || timeTabIdx == 2 || timeTabIdx == 3" @click="toTimeSelect(timeTabIdx)">
                    <text>{{dataTime}}</text>
                    <view></view>
                    <image mode="aspectFit" src="/static/images/icon/calendar.png"></image>
                </view>
                <view class="td-date" v-else>
                    <text>{{beforeSevenDay}}</text>
                    <!-- <view></view> -->
                    <!-- <image mode="aspectFit" src="/static/images/icon/calendar.png"></image> -->
                </view>
                
                <view class="td-tip">总收入</view>
                <view class="td-price"><text>¥</text>{{botData.count_type_actual_income_amount || 0}}</view>
                <view class="td-check-btn">
                    <text @click="toDetailsRecord">查看收款明细</text>
                    <image mode="aspectFit" src="/static/images/icon/triangle_c33.png"></image>
                </view>
                <view class="td-income-info">
                    <view class="tii-line">
                        <view class="tl-tit">线上  ¥{{ botData.online_actual_income_amount || '0' }}</view>
                        <view class="tl-detail">
                            <view class="td-item">收款{{ botData.online_income_num || '0' }}笔（￥{{ botData.online_income_amount || '0' }}）</view>
                            <view class="td-item">退款{{ botData.online_refund_num || '0' }}笔（<text>￥{{ botData.online_refund_amount || '0' }}</text>）</view>
                        </view>
                    </view>
                    <view class="tii-line">
                        <view class="tl-tit">线下  ¥{{ botData.offline_actual_income_amount || '0' }}</view>
                        <view class="tl-detail">
                            <view class="td-item">收款{{ botData.offline_income_num || '0' }}笔（￥{{ botData.offline_income_amount || '0' }}）</view>
                            <view class="td-item">退款{{ botData.offline_refund_num || '0' }}笔（<text>￥{{ botData.offline_refund_amount || '0' }}</text>）</view>
                        </view>
                    </view>
                    <view class="tii-line">
                        <view class="tl-tit">联营  ¥{{ botData.joint_actual_income_amount || '0' }}</view>
                        <view class="tl-detail">
                            <view class="td-item">收款{{ botData.joint_income_num || '0' }}笔（￥{{ botData.joint_income_amount || '0' }}）</view>
                            <view class="td-item">退款{{ botData.joint_refund_num || '0' }}笔（<text>￥{{ botData.joint_refund_amount || '0' }}</text>）</view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { API } from '../../js/api';
import { servers } from '../../js/server';
import util from '../../utils/util';
import { mapState } from 'vuex';
export default {
    computed: {
        ...mapState([ 'brandInfo' ]),
        dataTime(){
            let { curTime, timeTabIdx } = this;
            if(timeTabIdx == 0)return util.formatDate({ date: curTime.date || '', partition: 'zh' });
            if(timeTabIdx == 2)return util.formatDate({ date: `${curTime.month}-01`, partition: 'zh' }).substr(0,8);
            if(timeTabIdx == 3)return `${curTime.year}年`;
        },
        // 最近7天
        beforeSevenDay(){
            let _date = new Date();
            let _beforeSeven = _date.getTime() - (7*24*60*60*1000);
            return `${util.formatDate({date: _beforeSeven, partition: 'zh'}).substr(5)}-${util.formatDate({date: _date, partition: 'zh'}).substr(5)}`
        }
    },
    data(){
        return {
            tabID: 4, // 4 品牌， 3 门店
            timeTabIdx: 0,
            
            totalData: {},
            botData: {},

            pageInfo: {
                calc: {}
            },

            storeList: [],  // 店铺列表

            curSelectStore: {},  // 当前展示数据门店

            curTime: {
                date: '',
                month: '',
                year: '',
            },

        }
    },
    async onLoad(){
        try{
            let { timeTabIdx } = this;
            let _timeObj = this.getTime();

            this.curTime = _timeObj;
            let _storeList = await this.getStoreList();
            if(_storeList.length == 1)this.tabID = 3;

            this.$nextTick(this.refreshPageInfo);
        }catch(err){
            console.log(err);
            util.hideLoad();
        }

    },
    methods: {
        toDetailsRecord(){
            let { curSelectStore, brandInfo, tabID } = this;
            util.$_emit('turnoverToDetailsRecord', {
                stadiumInfo: (tabID == 3&&curSelectStore&&curSelectStore.id) ? curSelectStore : null,
                brandInfo: brandInfo&&brandInfo.brand ? brandInfo.brand : null,
            });
            util.routeTo(`/subpackage/income/pages/details_record/details_record`, 'nT');
        },  
        /*
            count_type

            3   门店总的统计
            4   品牌总的统计

            0   统计门店的某一天  (近7天)
            1   统计门店的某一月
            2   统计门店的某一年
            5   统计品牌的某一天  (近7天)
            6   统计品牌的某一月
            7   统计品牌的某一年
        */ 
        getCountType({ tab_id = -1,  time_tab_idx = -1 }){
            if(time_tab_idx == -1)return tab_id;

            let _type = getType(time_tab_idx)

            if(tab_id == 3&&_type != -1)return _type;

            if(tab_id == 4&&_type != -1)return _type += 5;
        
            function getType(idx){
                switch(+idx){
                    case 0:
                        return 0
                    case 1:
                        return 0
                    case 2:
                        return 1
                    case 3:
                        return 2
                    default:
                        return -1
                }
            }
        },
        incomeQusModal(data){
            util.showModal({
                title: '提示',
                content: data || '-',
            })
        },
        showQuestionModal(){
            let { totalData } = this
            util.showModal({
                title: totalData.income_record_name|| '提示',
                content: totalData.income_record_tips || '-',
                showCancel: true,
                success: mRes => {
                    
                }
            })
        },
        // 时间切换
        toTimeSelect(type){
            let { curTime, tabID, curSelectStore } = this;
            let storeID = '';
            if(tabID == 3)storeID = curSelectStore.id;
            if(type == 0)util.routeTo(`/pages/time_select/date/date?date=${curTime.date || ''}&store_id=${storeID}`,'nT');
            if(type == 2)util.routeTo(`/pages/time_select/month/month?date=${curTime.month || ''}&store_id=${storeID}`,'nT');
            if(type == 3)util.routeTo(`/pages/time_select/year/year?date=${curTime.year || ''}&store_id=${storeID}`,'nT');
        },
        // 刷新页面
        refreshPageInfo(){
            let { tabID, timeTabIdx, curSelectStore, curTime } = this;
            let _date;
            if(timeTabIdx == 0)_date = curTime.date || ''
            // if(timeTabIdx == 1)_date = util.formatDate({}).substr(0,10);
            // if(timeTabIdx == 2)_date = `${curTime.month}-01` || ''  // 统一格式
            if(timeTabIdx == 2)_date = curTime.month || ''  // 统一格式
            // if(timeTabIdx == 3)_date = `${curTime.year}-01-01` || ''// 统一格式
            if(timeTabIdx == 3)_date = curTime.year || ''// 统一格式
            
            let _type = this.getCountType({ tab_id: tabID, time_tab_idx: timeTabIdx });

            let _query = {
                stadium_id: curSelectStore.id || '',
                count_type: _type,
                time_str: _date || '',
            }

            if(timeTabIdx == 1&&(_type == 0 || _type == 5)){
                _query['time_str_min'] = util.formatDate({ date: new Date().getTime() - (7*24*60*60*1000) })
                _query['time_str_max'] = util.formatDate({  })
            }
            // 汇总
            this.getCountData({
                stadium_id: curSelectStore.id || '',
                count_type: this.getCountType({ tab_id: tabID })
            })

            
            this.getCountData(_query);

            // this.getBrandInfo(_query);
        },
        // 店铺切换
        storeChange(e){
            let { storeList } = this;
            let { value } = e.detail;
            this.curSelectStore = storeList[value];
            this.refreshPageInfo();
        },
        // 时间切换
        timeChange(date){
            let { timeTabIdx } = this;

            if(timeTabIdx == 0) this.curTime.date = date;
            if(timeTabIdx == 2) this.curTime.month = date;
            if(timeTabIdx == 3) this.curTime.year = date;

            this.refreshPageInfo();
        },
        // 获取初始时间
        getTime(){
            let _date = new Date();
            let _year = _date.getFullYear();
            let _month = util.formatNumber(_date.getMonth()+1);
            let _day = util.formatNumber(_date.getDate());
            return  {
                date: `${_year}-${_month}-${_day}`,
                month: `${_year}-${_month}`,
                year: _year
            }
            
        },
        
        tabChange: util.debounce(function(type){
            this.tabID = type;
            this.refreshPageInfo();
        },300,300),

        timeTabChange: util.debounce(function(type){
            this.timeTabIdx = type;
            this.refreshPageInfo();
        },300,300),

        // 获取品牌店铺列表
        getStoreList(){
            let { brandInfo } = this;
            util.showLoad();
            return servers.get({
                url: API.stadiumList,
                data: {
                    brand_id: brandInfo.brand.id,
                },
                failMsg: '加载店铺列表失败！',
            })
            .then(res=>{
                util.hideLoad();
                // let _list = [res.list[0]] || [];
                let _list = res.list || [];
                this.storeList = _list;
                this.curSelectStore = _list[0] || {};
                return _list || [];
            })
        },
            

        /*
            count_type

            3   门店总的统计
            4   品牌总的统计
            0   统计门店的某一天
            1   统计门店的某一月
            2   统计门店的某一年
            5   统计品牌的某一天 
            6   统计品牌的某一月
            7   统计品牌的某一年
        */ 
        getCountData({
            stadium_id,
            count_type,
            time_str = '',           // 筛选=某个时间  y-m-d某一天/y-m某月/y某年
            time_str_max = '',  // 筛选 >=某个时间  y-m-d
            time_str_min = '',  // 筛选 <=某个时间  y-m-d
        }){
            let { brandInfo } = this;
            util.showLoad();
            servers.get({
                url: API.consumeCountGet,
                data: {
                    brand_id: brandInfo.brand.id,
                    'filter[brand_id:eq]': brandInfo.brand.id,
                    'filter[stadium_id:eq]': stadium_id,
                    'filter[count_type:eq]': count_type,
                    'filter[time_str:eq]': time_str,      
                    'filter[time_str:egt]': time_str_min, 
                    'filter[time_str:elt]': time_str_max, 
                },
                failMsg: '加载失败！'
            })
            .then(res=>{
                util.hideLoad();
                let _data = res || {};
                if(count_type == 3 || count_type == 4)return this.totalData = _data;
                this.botData = _data
            })
            .catch(util.hideLoad)
        },

        getBrandInfo({
            date,
            type,
            stadium_id='',
        }){
            let { brandInfo } = this;
            util.showLoad();
            servers.get({
                url: API.turnoverBrand,
                data: {
                    brand_id: brandInfo.brand.id,
                    date,
                    type,// type=1, 2,3,4 代表日报， 周报， 月报， 年报
                    stadium_id
                },
                failMsg: '加载失败！'
            })
            .then(res=>{
                util.hideLoad();
                this.pageInfo = res;
            })
            .catch(util.hideLoad)
        }

    }
}
</script>

<style lang="scss">
    @import "../../style/public.scss";
    page{
        background-color: #fff;
    }
    .turnover-container{
        padding-bottom: 40upx;
        padding-bottom: calc( 40upx + constant(safe-area-inset-bottom)); /* 兼容 iOS < 11.2 */
        padding-bottom: calc( 40upx + env(safe-area-inset-bottom)); /* 兼容 iOS >= 11.2 */
    }
    .tc-tab{
        height: 134upx;
        border-bottom: 22upx solid #f2f2f7;
        @include centerFlex(center);
        >view{
            margin: 0 70upx;
            width: 228upx;
            height: 72upx;
            line-height: 72upx;
            text-align: center;
            border-radius: 36upx;
            font-size: 36upx;
            font-weight: 500;
            color: #1a1a1a;
        }
        .active{
            background-color: $themeColor;
            color: #fff;
        }
    }
    .tc-total-section{
        border-bottom: 24upx solid #f2f2f7;
        >picker{
            width: 100%;
        }
        .tts-address{
            padding-left: 48upx;
            padding-right: 44upx;
            height: 108upx;
            border-bottom: 2upx solid #D8D8D8;
            @include centerFlex(space-between);
            
            >view{
                flex-grow: 1;
                font-size: 28upx;
                color: #1a1a1a;
                @include textHide(1);
            }
            >image{
                margin-left: 20upx;
                flex-shrink: 0;
                width: 28upx;
                height: 28upx;
            }
            .ta-logo{
                justify-self: flex-start;
                flex-shrink: 0;
                flex-grow: 0;
                margin-right: 20upx;
                margin-left: 0;
                width: 52upx;
                height: 52upx;
            }
        }
        .tts-money{
            padding-top: 48upx;
            >view{
                margin-bottom: 34upx;
                text-align: center;
                padding: 0 24upx;
                @include textHide(1);
                &:first-child{
                    margin-bottom: 22upx;
                    line-height: 34upx;
                    font-size: 24upx;
                    color: #9c9c9f;
                }
                &:nth-child(2){
                    margin-bottom: 12upx;
                    line-height: 40upx;
                    font-size: 28upx;
                    color: #9c9c9f;
                    >image{
                        display: inline-block;
                        vertical-align: middle;
                        width: 28upx;
                        height: 28upx;
                        margin-left: 8upx;
                    }
                }
                &:nth-child(3){
                    line-height: 90upx;
                    font-size: 64upx;
                    color: #1a1a1a;
                    font-weight: 600;
                    >text{
                        font-size: 52upx;
                    }
                }
            }
        }
        .tts-preview-ls{
            padding-top: 50upx;
            padding-bottom: 36upx;
            @include centerFlex(space-between);
            .tpl-item{
                padding: 0 10upx;
                flex-shrink: 0;
                flex-grow: 1;
                width: 33.33%;
                .ti-name{
                    @include centerFlex(center);
                    margin-bottom: 6upx;
                    line-height: 34upx;
                    font-weight: 500;
                    font-size: 24upx;
                    color: #1A1A1A;
                    >image{
                        margin-left: 10upx;
                        flex-shrink: 0;
                        width: 28upx;
                        height: 28upx;
                    }
                }
                .ti-price{
                    text-align: center;
                    line-height: 34upx;
                    font-size: 24upx;
                    font-weight: 500;
                    color: #1A1A1A;
                    @include textHide(1);
                }


            }
        }
    }
    .tc-info-section{
        .tis-tab{
            padding: 0 34upx;
            height: 108upx;
            border-bottom: 2upx solid #D8D8D8;
            @include centerFlex(space-between);
            >view{
                flex-grow: 0;
                flex-shrink: 0;
                width: 120upx;
                height: 106upx;
                line-height: 106upx;
                text-align: center;
                font-size: 32upx;
                color: #9c9c9f;
            }
            .active{
                position: relative;
                color: $themeColor;
                &::after{
                    content: '';
                    display: block;
                    position: absolute;
                    left: 50%;
                    bottom: -2upx;
                    transform: translateX(-50%);
                    width: 100%;
                    height: 8upx;
                    border-radius: 4upx;
                    background-color: $themeColor;
                }
            }
        }
        .tis-data{
            padding-top: 60upx;
            display: flex;
            flex-direction: column;
            align-items: center;
            .td-date{
                margin-bottom: 62upx;
                height: 72upx;
                padding: 0 24upx;
                border-radius: 10upx;
                background-color: #f2f2f7;
                @include centerFlex(center);
                >view{
                    font-size: 28upx;
                    color: #1a1a1a;
                }
                >view{
                    margin: 0 18upx;
                    width: 2upx;
                    height: 40upx;
                    background-color: #D8D8D8;
                }
                >image{
                    width: 40upx;
                    height: 40upx;
                }
            }
            .td-tip{
                margin-bottom: 6upx;
                text-align: center;
                line-height: 40upx;
                font-size: 28upx;
                color: #9c9c9f;
            }
            .td-price{
                margin-bottom: 50upx;
                padding: 0 24upx;
                line-height: 90upx;
                font-size: 76upx;
                color: #1a1a1a;
                >text{
                    font-size: 52upx;
                }
                @include textHide(1);
            }
            .td-check-btn{
                padding-bottom: 12upx;
                width: 642upx;
                line-height: 40upx;
                font-size: 28upx;
                border-bottom: 2upx solid #D8D8D8;
                color: #9C9C9F;
                @include centerFlex(flex-end);
                >image{
                    margin-left: 6upx;
                    width: 22upx;
                    height: 22upx;
                }

            }
            .td-income-info{
                padding: 40upx 0 0;
                width: 642upx;
                .tii-line{
                    margin-bottom: 50upx;
                    .tl-tit{
                        margin-bottom: 24upx;
                        line-height: 40upx;
                        font-size: 28upx;
                        font-weight: 500;
                        color: #1A1A1A;
                        @include textHide(1);
                    }
                    .tl-detail{
                        @include centerFlex(space-between);
                        flex-wrap: nowrap;
                        .td-item{
                            width: 50%;
                            flex-grow: 0;
                            flex-shrink: 0;
                            font-size: 24upx;
                            color: #9C9C9F;
                            >text{
                                color: #F6843E;
                            }
                        }
                    }
                }
            }
        }
    }
</style>