<template>
    <view>
        <cps-wrap :title="data.title" :sub-title="data.subTitle">
            <view>
                <view class="nav-wrap">
                    <!-- nav -->
                    <view v-if="data.nav && data.nav.list && data.nav.list.length" class="skulist-nav">
                        <c-navs
                            :options="data.nav.list"
                            selected-color="#FF6050"
                            :selected-index="parseInt(data.nav.selectedIndex, 10)"
                            :is-left="true"
                            padding-left="10px"
                            padding-right="10px"
                            scroll
                            @itemtap="navItemTap"
                        /></view>
                    <view class="search-wrap">
                        <view class="search" @tap.stop="onCityTap">
                            <c-icon
                                :name="'location'"
                                font-size="15px"
                                class="location-icon"
                            />
                            <view class="c-font-13 c-inline-block c-line-clamp1 location-text">{{ params.city }}</view>
                        </view>
                    </view>
                </view>
                <!-- tag -->
                <view class="skulist-tag c-gap-top-large c-gap-bottom-large">
                    <m-tabs
                        v-if="filter.tag && filter.tag.list && filter.tag.list.length"
                        :tabs="filter.tag.list"
                        label-color="#f6f6f6"
                        label-font-color="#555555"
                        selected-color="#feefec"
                        selected-font-color="#FF6050"
                        :first-tag-left="0"
                        :topic="'cps-skulist'"
                        :show-border="false"
                        @onTap="onTabTap"
                    />
                    <view v-if="showCascader" class="city-cascader">
                        <c-cascader
                            primary-color="#FF6050"
                            :default-value="filter.city.defaultValue"
                            :column="2"
                            :options="filter.city.options"
                            :style="{
                                margin: '0 10px',
                                position: 'absolute',
                                width: 'calc(100% - 20px)',
                                top: '-16px',
                            }"
                            @lastcolumnitemtap="filterChange"
                        />
                        <view class="city-cascader-mask" @tap.stop="onCityClose"/>
                    </view>
                </view>
                <view class="skulist-wrap">
                    <view v-if="packageList && packageList.length">
                        <!-- eslint-disable max-len -->
                        <cps-package
                            v-for="(pack, i) in packageList"
                            :key="'pack' + i"
                            :data="pack"
                            :index="i"
                            :bottom-gap="packageList.length % 2 ? (i < packageList.length - 1 ? true : false) : (i < packageList.length - 2 ? true : false)"
                            :log="params.level1 || level1"
                            @share="toShare"
                        />
                        <!-- eslint-enable max-len -->
                    </view>
                    <!-- list loading -->
                    <list-loading
                        v-show="status === 'loading'"
                        class="list-loading"
                        bg-color="transparent"
                        color="#999"
                        :status="status"
                    />
                    <!-- empty text -->
                    <view v-if="packageList.length === 0 && status === 'complete'" class="order-list-empty">
                        <b-list-empty :info="data.emptyTip || []"/>
                    </view>
                </view>
                <!-- 底部按钮 -->
                <view
                    v-if="data.nav && data.nav.list && data.nav.list.length"
                    class="cps-btn c-gap-top"
                >
                    <view class="cps-btn-wrap">
                        <view
                            v-for="(o, i) in data.nav.list"
                            v-show="status === 'complete' && i === curNavIdx && o.btn && o.btn.length"
                            :key="i"
                            class="cps-btn-wrap-row"
                        >
                            <view
                                v-for="(b, j) in o.btn"
                                :key="j"
                                class="cps-btn-item font-medium c-font-normal c-line-clamp1"
                                :class="[
                                    'cps-btn-' + b.type, j % 2 && 'c-gap-left-middle',
                                    'c-span' + (12 / o.btn.length),
                                ]"
                                @tap="toShare(b.url, o.name)"
                            >{{ b.text }}</view>
                        </view>
                    </view>
                </view>
            </view>
        </cps-wrap>
        <!-- list loading -->
        <list-loading
            v-show="status === 'complete' && packageList.length !== 0"
            class="list-loading-bottom"
            bg-color="transparent"
            color="#999"
            :status="status"
        />
        <c-dialog
            :show="dialogCont.show"
            title=""
            :content="dialogCont.content"
            content-text-align="center"
            :btn-opts="dialogCont.btnOpts"
            @confirm="dialogConfirm"
        />
        <share-img
            v-if="showImg && materialUrl"
            disable-compress
            :src="materialUrl"
            :btn-opts="[{
                text: '保存海报',
                type: 'save',
                color: '#FF6050',
                borderColor: '#FF6050',
            }, {
                text: '立即分享',
                type: 'share',
                bgColor: 'linear-gradient(125deg, #FF754F 0%, #FB4556 100%)',
                color: '#fff',
            }]"
            @close="onCloseShare"
        />
    </view>
</template>

<script>
/**
* @file 热门商品
* @author zhangqian51
* @categories 业务组件
* @tags [component]
*/
import CIcon from '@baidu/med-ui/components/Icon/Icon';
import CNavs from '@baidu/med-ui/components/Navs/Navs';
import CDialog from '@baidu/med-ui/components/Dialog/Dialog';
import CCascader from '@baidu/med-ui/components/Cascader/Cascader';
import MTabs from '../marketing/tabs';
import CpsWrap from './cps-wrap';
import CpsPackage from './cps-package';
import ListLoading from '@commonComponents/list-loading';
import BListEmpty from '@commonComponents/list-empty';
import ShareImg from '@commonComponents/share-img';
import {send} from '@utils/log';
import {request} from '@utils/request';
import * as conf from '@utils/conf';
import {getQueryObject} from '@utils/core';

let scrollLock = false;
export default {
    config: {
        component: true
    },
    options: {
        addGlobalClass: true
    },
    components: {
        CIcon,
        CpsWrap,
        CDialog,
        CCascader,
        CNavs,
        MTabs,
        CpsPackage,
        ListLoading,
        BListEmpty,
        ShareImg
    },
    props: {
        /**
        * 业务数据
        */
        data: {
            type: Object,
            default: () => {}
        },
        /**
        * 城市
        */
        city: {
            type: Object,
            default: () => {}
        },
        /**
        * 疫苗一级品类
        */
        level1: {
            type: String,
            default: 'hpv'
        }
    },
    data() {
        const isSwan = process.env.MARS_ENV === 'swan';
        return {
            isSwan,
            /* eslint-disable max-len */
            location: {
                city: '北京',
                code: '110100',
                unifiUrl: '/pages/brand/citylist/index?title=选择城市&toPage=%2Fpages%2Fact%2Fcps%2Findex%3F'
            },
            filter: {
                nav: null,
                tag: null,
                city: null
            },
            params: {
                city: '',
                lat: '',
                lng: ''
            },
            packageNextUrl: '',
            // 更多加载态
            status: 'init',
            isPageLoaded: false,
            page: 0,
            pageSize: 10,
            emptyTip: [],
            packageList: [],
            showCascader: false,
            flag: '',
            materialUrl: '',
            url: '',
            // 弹窗
            dialogCont: {
                show: false,
                content: '分享链接已复制，赶快分享给好友吧',
                btnOpts: [{
                    event: 'confirm',
                    text: '我知道了',
                    color: '#FF6050'
                }]
            },
            showImg: false,
            navOffset: 0,
            curNavIdx: 0
        };
    },
    created() {
        Object.assign(this, {
            packageNextUrl: this.data.packageNextUrl,
            packageList: this.data.packageList
        }),
        this.filter.city = this.data.filter && this.data.filter && this.data.filter.length && this.formatCity(this.data.filter);
        this.filter.tag = this.data.tag || [];
        this.params = Object.assign(this.params,
                                    {city: this.city.name, lat: this.city.lat, lng: this.city.lng}
        );
        if (!this.packageList || this.packageList.length < 5) {
            this.status = 'complete';
        }
        this.curNavIdx = Number(this.data.nav && this.data.nav.selectedIndex) || 0;
    },
    mounted() {
        this.onSetNavHeight();
    },
    methods: {
        navItemTap(e) {
            this.curNavIdx = e.index;
            send({extra: {type: 'nav-click', title: e.item.text}});
            let selectTag = '';
            e && e.item && e.item.tag && e.item.tag.forEach(tagItem => {
                tagItem.isSelect === '1' && (selectTag = tagItem.text);
            });
            Object.assign(this, {
                params: Object.assign(this.params, {level1: e.item.name, level2: selectTag, topic: e.item.name}),
                filter: Object.assign(this.filter, {tag: {list: e.item.tag, value: 'type'}})
            });
            this.getList(0);
        },
        onTabTap(e) {
            this.params.level2 = e.text;
            this.getList(0);
        },
        reachBottom() {
            if (this.status === 'complete') {
                return;
            }
            this.getList(this.page + 1);
        },
        getList(page, type) {
            if (scrollLock) {
                return;
            }
            if (page === 0) {
                this.packageList = [];
            }
            scrollLock = true;
            this.status = 'loading';
            if (type === 'city') {
                Object.assign(this.params, {level2: ''});
            }
            request({
                url: conf.apiHost + this.packageNextUrl,
                data: {...this.params, page},
                isNeedLogin: false,
                isFirstScreen: false
            }).then(async res => {
                const {packageList, packageNextUrl, filter, nav} = res.data;
                let tag = null;
                if (type === 'city') {
                    nav && nav.list && nav.list.forEach(itm => {
                        /* eslint-disable */
                        if (itm.isSelect == 1) {
                            this.params.level1 = itm.name;
                            tag = itm.tag;
                            tag && tag.forEach(tagItem => {
                                tagItem.isSelect === '1' && (this.params.level2 = tagItem.text);
                            });
                        }
                        this.params.level2 = '';
                    });
                }
                if (page === 0) {
                    this.packageList = packageList || [];
                } else {
                    this.packageList = this.packageList.concat(packageList || []);
                }
                Object.assign(this, {
                    page: page,
                    filter: Object.assign(this.filter, tag && {tag: {list: tag, value: 'type'}} || {}, {city: filter && filter.city && this.formatCity(filter.city) || this.filter.city}),
                    packageNextUrl: packageNextUrl || this.packageNextUrl
                });
                this.$mpUpdated(() => {
                    if (page === 0) {
                        // this.$api.pageScrollTo({
                        //     scrollTop: this.navOffset,
                        //     duration: 300
                        // });
                    }
                })
                if (!packageList || packageList.length < 5) {
                    this.status = 'complete';
                }
                scrollLock = false;
            })
            .catch(res => {
                scrollLock = false;
            });
        },
        onCityTap() {
            this.showCascader = !this.showCascader;
            console.log(this.showCascader);
        },
        onCityClose() {
            this.showCascader = false;
        },
        formatCity(city) {
            let result = {
                column: 2,
                defaultValue: '',
                text: '地区',
                type: 'list',
                key: 'provnice',
                options: []
            };
            city.forEach((item, index) => {
                const options = item.city.map((cityItem, cityIndex) => {
                    if (this.params.city && cityItem.indexOf(this.params.city) > -1) {
                        result.defaultValue = item.province + ',' + cityItem;
                    }
                    return {
                        text: cityItem,
                        value: cityItem
                    };
                });
                let data = {
                    key: 'city',
                    text: item.province,
                    value: item.province,
                    options
                };
                result.options.push(data);
            });
            return result;
        },
        filterChange(e) {
            send({type: 'city-click', title: e.option.text});
            this.params.city = e.option.text;
            this.filter.city.defaultValue = e.defaultValue;
            this.onCityTap();
            this.getList(0, 'city');
        },
        toShare(url, type) {
            this.flag = decodeURIComponent(getQueryObject(url).flag) || '';
            if (this.flag === 'img') {
                 this.$api.showToast({
                    icon: 'loading',
                    title: '正在加载中……'
                });
            }
            request({
                url: conf.apiHost + url,
                isNeedLogin: false,
                isFirstScreen: false
            }).then(async res => {
                let { material_url = '', url = '' } = res.data;
                Object.assign(this, {
                    materialUrl: material_url,
                    url
                });
                setTimeout(() => {
                    if (this.flag === 'url') {
                        this.urlCopy(url, ()=> {
                            this.$api.showToast({
                                title: '分享链接已复制，赶快分享给好友吧~',
                                icon: 'none'
                            });
                        }, () => {
                            this.$api.showToast({
                                title: '复制失败',
                                icon: 'none'
                            });
                        });
                        send({
                            extra: {
                                action: 'share',
                                type: 'url' + (type ? '_' + type : '')
                            }
                        });
                        return;
                    }
                    if (this.flag === 'img') {
                        this.$api.hideToast();
                        send({
                            extra: {
                                action: 'share',
                                type: 'img' + (type ? '_' + type : '')
                            }
                        });
                        this.showImg = true;
                    }
                }, 200);
            });
        },
        // 复制
        urlCopy(data, succClb, failClb) {
            this.$api.setClipboardData({
                data: data,
                success: succClb,
                fail: failClb
            });
        },
        dialogConfirm() {
            this.dialogCont.show = false;
        },
        onCloseShare() {
            this.showImg = false;
        },
        onSetNavHeight() {
            const navQuery = this.$api.createSelectorQuery().select('.cps-cont-wrap');
            navQuery.boundingClientRect(rect => {
                const {top} = rect || {};
                if (!top) {
                    return this.onSetNavHeight();
                }
                else {
                    this.navOffset = this.isSwan ? top : top - 30;
                }
            }).exec();
        },
    }
};
</script>

<style lang="less" scoped>
.nav-wrap {
    width: calc(100% + 30px);
    position: relative;
    left: -15px;
    border-bottom: 1px solid #eee;
}

.skulist-wrap {
    min-height: 200px;
}

.skulist-nav {
    width: calc(100% - 100px);
}

.search-wrap {
    position: absolute;
    right: 15px;
    top: 6px;
    width: 80px;
    height: 24px;
    background: #fff;
    box-shadow: -30px -2px 15px 5px rgb(255, 255, 255);
}

.search {
    position: absolute;
    right: 0;
    color: #fff;
    background: #ff6050;
    padding: 0 10px 0 8px;
    border-radius: 14px;
}

.location-icon {
    position: relative;
    top: 1px;
    margin-right: 3px;
}

.location-text {
    max-width: 39px;
    position: relative;
    top: -1px;
}

.skulist-tag {
    position: relative;
}

.order-list-empty {
    position: relative;
    min-height: 200px;
}

.city-cascader {
    position: absolute;
    top: 0;
    width: 100vw;
    z-index: 1;
    left: -25px;

    &-mask {
        background-color: rgba(0, 0, 0, 0.65);
        left: 0;
        right: 0;
        height: 1500px;
    }
}

.list-loading-bottom {
    margin-bottom: -13px;
}

.cps-btn {
    &-wrap {
        &-row {
            display: flex;
        }
    }

    &-item {
        border-radius: 22px;
        text-align: center;
        height: 44px;
        line-height: 44px;
    }

    &-link {
        background: #faf3f0;
        border: 1px solid #ff6050;
        color: #ff6050;
    }

    &-poster {
        color: #fff;
        background: linear-gradient(125deg, #ff754f 0%, #fb4556 100%);
    }
}
</style>
