<template>
    <div :class="bem('wrapper')">
        <header :class="bem()">
            <div :class="bem('nav')">
                <div :class="bem('content')">
                    <GdLink url="/" :class="bem('gd-logo')" title="返回首页">
                        <div :class="bem('logo')"><Icon name="logo"/></div>
                    </GdLink>
                    <div :class="bem('channel')" v-if="scenes.findIndex(s => $route.path === s.value) > -1">
                        <template>
                            <div :class="bem('divider')" />
                            <h3>{{scenes.find(s => $route.path === s.value).label}}</h3>
                        </template>
                        <!-- <Select
                            :value="$route.path"
                            trigger="hover"
                            :border="false"
                            disabled
                            :options="scenes"
                            @change="v => $router.push(v)"
                            style="width: auto;"
                        /> -->
                    </div>
                    <div
                        :class="bem('nav-list')"
                    >
                        <!-- <GdLink url="/discover" :class="bem('nav-item')">
                            发现
                        </GdLink> -->
                        <span
                            @click="$router.push('/')"
                            :class="bem('nav-item', {'routeActive': $route.path === '/'})"
                        >首页</span>
                        <TemplatesPopover :class="bem('nav-item')">
                            <GdLink url="/templates">
                                模板中心
                            </GdLink>
                        </TemplatesPopover>
                        <Popover
                            :class="bem('nav-item')"
                            :visible.sync="visible"
                            :delayonMouseLeave="100"
                            :appendBody="false"
                            @click="visible = false"
                            :modifiers="{
                                offset: { offset: '0 10px' },
                            }">
                            <GdLink
                                url="/xinmeiti"
                                :class="{'routeActive': isPindao}"
                            >
                                特色频道
                            </GdLink>
                            <div slot="content" style="width: 120px; padding: 8px 0;">
                                <div
                                    v-for="{value, label} in scenes"
                                    :key="value"
                                    @click="() => {visible = false;}"
                                    :class="['gd-select-option', {'gd-select-option--is-active': value === $route.path}]"
                                >

                                    <GdLink
                                        :url="value"
                                        :class="'gd-select-option__content'"
                                    >
                                        {{label}}
                                    </GdLink>
                                </div>
                            </div>
                        </Popover>
                        <GdLink url="/topics" :class="bem('nav-item')">
                            专题/套装
                        </GdLink>
                        <!-- <GdLink url="/school" :class="bem('nav-item')">
                            稿定学院
                        </GdLink> -->
                        <GdLink url="/download" :class="bem('nav-item')">
                            手机版
                        </GdLink>
                        <div :class="bem('divider')"/>
                        <GdLink
                            url="/koutu"
                            key="智能拼图"
                            :class="bem('nav-item')"
                        >

                            智能抠图
                        </GdLink>
                    </div>
                    <div :class="bem('right')">
                        <div style="flex: 1 1 auto"/>
                        <Search
                            v-if="isShowSarch"
                            v-model="query"
                            @search="search"
                            :options="suggestions"
                            @input="fetchSuggest"
                            :searchHistory="searchHistory.list || []"
                            @del-history="delHistory"
                            @clear-history="clearHistory"
                            :hots="hots"
                        />
                        <img
                            :class="bem('novice')"
                            src="./assets/video.png"
                            @click="createVideo({
                                url: 'https://st-gdx.dancf.com/gaodingx/8/configs/system/20190430-220520-f572.mp4',
                                autoplay: true
                            })"
                            srcset="./assets/video2x.png 2x"
                            alt="新手教程">
                        <User
                            :isLogined="isLogined"
                            :logout="logout"
                            :login="login"
                            :user="user"
                        >
                            <!-- 登录时的用户名 -->
                            <slot name="nick"/>
                        </User>
                    </div>
                </div>
            </div>
        </header>
    </div>
</template>

<script>
import throttle from 'lodash/throttle';
import { REQUEST_URL } from '../_utils/constant.js';
import Icon from '../Icon';
import request from '../request';
import globalConfig from '../config';
import Popover from '../Popover';
import '../Select';
import { createComponentName, componentMixin } from '../_utils/component';
import User from './User';
import Search from './Search';
import GdLink from './Link';
import TemplatesPopover from './templates-popover';
import { toRelativePath } from '../_utils/url';
import searchHistory from './search-history';
import createVideo from '../createVideo';


const scenes = [
    { label: '新媒体频道', value: '/xinmeiti' },
    { label: '电商频道', value: '/dianshang' },
    { label: '人力行政频道', value: '/qiye' },
];


export default {
    name: createComponentName('header'),
    components: {
        Icon,
        Popover,
        User,
        Search,
        GdLink,
        TemplatesPopover,
    },
    mixins: [componentMixin],
    props: {
        // 当前页面的域名, 会将相同域名的地址转换为相对路径
        host: {
            type: String,
            default: globalConfig.host,
        },
        // 半透明 用于专题页
        translucent: {
            type: Boolean,
            default: false,
        },
        // 是否登录
        isLogined: {
            type: Boolean,
            default: false,
        },
        // 处理导航数据
        handleNavigations: {
            // (navs: object[]) => object[]
            type: Function,
            default() {},
        },
        // 触发退出
        logout: {
            type: Function,
            required: true,
        },
        // 触发登录
        login: {
            type: Function,
            required: true,
        },
        user: {
            type: Object,
            required: true,
        }
    },
    data() {
        return {
            scenes,
            visible: false,
            query: '',
            scrollTop: 0,
            mounted: false,
            suggestions: [],
            searchHistory: {},
            hots: []
        };
    },
    computed: {
        isPindao() {
            return this.$route.path === '/xinmeiti' || this.$route.path === '/dianshang' || this.$route.path === '/qiye';
        },
        isShowSarch() {
            if (this.$route.path.indexOf('templates') > -1) {
                if (this.scrollTop > 328) {
                    return true;
                }
                return false;
            }
            return true;
        }
    },
    created() {
        // this.resetData(false);
        this.fetchHots();
        this.initHistory();
        this.fetchSuggest = throttle(this.fetchSuggest, 300);
    },
    mounted() {
        this.mounted = true;
        window.addEventListener('scroll', this.listenerScroll, false);
        this.listenerScroll();
    },
    beforeDestroy() {
        window.removeEventListener('scroll', this.listenerScroll, false);
    },
    methods: {
        createVideo,
        listenerScroll() {
            this.scrollTop = document.documentElement.scrollTop;
        },
        async cogradientHistory() {
            let postData = [];
            const data = searchHistory(10, 'search_history');
            if (data.list.length !== 0) {
                postData = data.list
                    .sort((a, b) => {
                        return (a.timestamp || 0) - (b.timestamp || 0);
                    })
                    .map(item => {
                        return {
                            result_num: item.result_num ? item.result_num.toString() : '0',
                            search_word: item.search_word,
                            roles: item.roles ? item.roles.toString() : '0',
                            colors: item.colors || '0',
                            categories: item.categories || '0',
                            is_corrected: 0
                        };
                    });
                await request.post('/api/search-records', postData)
                    .then(res => {
                        this.searchHistory.list = res.data.sort((a, b) => {
                            return b.id - a.id;
                        });
                    });
            }
        },
        delHistory(item) {
            if (this.isLogined) {
                return request.put(`/api/search-records/${item.id || 0}`, {
                    is_all: 0 // 清除当前id
                })
                    .then(() => {
                    // this.searchHistory.list = this.searchHistory.list.filter(item => item.id !== res.data.id);
                        this.getSearchRecordsList(true);
                    })
                    .catch(err => console.log(err));
            }
            else {
                this.searchHistory.remove(item);
            }
        },
        clearHistory() {
            if (this.isLogined) {
                return request.put('/api/search-records/0', {
                    is_all: 1
                })
                    .then(() => {
                        this.searchHistory.list = [];
                    // this.searchHistory.clear();
                    // this.searchHistory.save();
                    })
                    .catch(err => console.log(err));
            }
            else {
                this.searchHistory.clear();
                this.searchHistory.save();
                this.initHistory();
            }
        },

        initHistory(noCogradient = true) {
            const SEARCH_HISTORY = 'search_history';
            const MAX_HISTORY_LENGTH = 10;
            this.searchHistory = searchHistory(MAX_HISTORY_LENGTH, SEARCH_HISTORY);
            if (this.isLogined) {
                this.getSearchRecordsList(noCogradient);
            }
        },

        getSearchRecordsList(noCogradient = false) {
            return request.get('/api/search-records', {}).then(async res => {
                if (res.data && res.data.length !== 0) {
                    this.searchHistory.list = res.data;
                }
                else {
                    this.searchHistory.list = [];
                    if (!noCogradient) await this.cogradientHistory();
                }
            }).catch(err => console.log(err));
        },
        // @vuese
        // 重置导航数据， 登录后需要使用，获取不同的灰度数据
        resetData(noInit = true) {
            // request.get('/api/navigations').then(res => {
            //     cache.localCache.set('navigations', res.data);
            //     if (this.handleNavigations) {
            //         res.data = this.handleNavigations(res.data) || res.data;
            //     };
            //     this.navs = res.data;
            // });
            this.initHistory(!noInit);
        },
        fetchHots() {
            return request.get('/api/search-hot-words', {}).then(async res => {
                const hotsData = res.data;
                this.hots = hotsData;
            }).catch(err => {
                this.hots = [];
                throw err;
            });
        },

        fetchSuggest() {
            if (!this.query) {
                this.suggestions = [];
                return;
            };

            request.get('/api/suggest', { params: { q: this.query } }).then(res => {
                this.suggestions = res.data.filter(k => k !== this.query).slice(0, 5);
            });
        },
        onClick(nav) {
            // 点击导航触发
            // @arg nav: object
            this.$emit('select', nav);
        },
        transformUrl(url) {
            return toRelativePath(url, this.host);
        },
        search() {
            let href = `${REQUEST_URL}/templates?q=${this.query}`;
            location.href = href;
        },
    }
};
</script>

<style lang="less">
@import '../_styles/base.less';

@b: @header;

@time: .3s;

.@{b}__wrapper {
    height: 70px;

    will-change: height;
}

.@{b} {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background-color: #fff;
    width: 100%;
    width: 100vw;
    transition: all @time;
    // box-shadow: 0 2px 6px 0 rgba(0, 0, 0, .04);

    * {
        box-sizing: border-box;
    }


    & &__nav-item {
        font-size: @font-size-base;
        font-weight: 500;
        margin-right: 30px;
        cursor: pointer;
        display: flex;
        align-items: center;
        color: #000;
        line-height: 30px;

        &--active {
            font-weight: 500;
        }

        &--routeActive,
        .routeActive,
        .router-link-active {
            font-weight: bold;
            color: @color-primary;
        }
        .gd-link {
            &:hover {
                color: @color-primary;
            }
        }
        &:hover {
            color: @color-primary;
        }

        &--new {
            padding-right: @margin-sm + 6;
        }

        .@{badge}__content {
            font-size: 12px;
            top: 0;
            right: 1px;
            transform: scale(0.8) translateY(-50%) translateX(100%);
        }
    }

    & &__nav-item.router-link-active {
        font-weight: bold;
        color: @color-primary;
    }

    &__channel {
        min-width: 59px;
        display: flex;
        align-items: center;

        .@{b}__divider {
            margin-right: 10px;
        }

        h3 {
            font-size: @font-size-lg;
            width: 100px;
            font-weight: 500;
            margin-right: 20px;
            color: #333333;
            cursor: default;
        }

    }

    &__nav {
        min-width: 1280px;
        margin: auto;
        height: 70px;
    }


    &__nav-list {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        margin-left: 40px;
        flex: 0 0 auto;
        transition: all @time;
    }

    &__content {
        margin: auto 30px;
        height: 70px;
        min-width: 1280px;
        display: flex;
        align-items: center;
    }


    &__divider {
        height: 14px;
        width: 1px;
        margin: 0;
        margin-right: 30px;
        background: #D9DDE1;
    }
    &__gd-logo {
        &:hover {
            color: inherit;
        }
    }
    &__logo {
        display: flex;
        width: 125px;
        align-items: center;
        height: 66px;
        font-size: 18px;
        font-weight: 400;
        flex: 0 0 182px;

        .@{b}__divider {
            margin-bottom: 0;
            height: 12px;
            background: #999;
        }

        svg {
            width: 110px;
            height: 66px;
        }

        img {
            height: 23px;
        }
    }

    &__right {
        display: flex;
        height: 66px;
        flex: 1 1 auto;
        margin-left: 12px;
        align-items: center;
    }

    &__novice {
        margin: 0 12px;
        cursor: pointer;
    }

    .@{b}-search {
        margin-right: 12px;
    }
}

</style>
