<template>
    <view class="search-library" :class="{ unScorll: showLibaray }">
        <!-- 搜索框区域 -->
        <view class="sticky-container">
            <search-header
                :menuList="menuItemList"
                :currentMenu="currentMenu"
                v-model="keyword"
                @clear="
                    onClear()
                    hideLibrary()
                "
                @search="
                    onSearch()
                    hideLibrary()
                "
                @input="onInput"
                @menuClick="onMenuItemClick"
            ></search-header>
            <!-- 搜索分类区域 -->
            <view class="search-category">
                <tui-tabs
                    :tabs="tabs"
                    :currentTab="currentTab"
                    :sliderWidth="40"
                    :bold="true"
                    :unlined="true"
                    :height="60"
                    sliderBgColor="#F3B574"
                    selectedColor="#F3B574"
                    @change="onTabChange"
                ></tui-tabs>
            </view>
        </view>

        <!-- 搜索结果区域 -->
        <view class="search-wrapper">
            <!-- 产品列表 -->
            <product-list v-if="currentTab === 0" :list="productList" @change="onProductFilterItemChange" />
            <!-- 相关文章 -->
            <article-list v-if="currentTab === 1" :list="articleList" @change="onArticleFilterItemChange" />
            <!-- 相关资料 -->
            <material-list v-if="currentTab === 2" :list="materialList" />
            <!-- 相关百科 -->
            <encyclopedia-list v-if="currentTab === 3" :list="encyclopediaList" />
        </view>
        <!-- 列表为空 -->
        <view class="empty-box" v-if="!isLoading && isListEmpty">
            <image
                class="empty-image"
                src="https://img.caimei365.com/group1/M00/03/8D/Cmis215XHXWAHCoqAAELHadZ9Xg365.png"
            ></image>
            <text class="empty-text">抱歉，没有{{ currentTabItem.name }}！</text>
        </view>
        <!-- 加载 loading -->
        <template v-if="!isListEmpty">
            <tui-loadmore :index="2" :visible="isLoading"></tui-loadmore>
            <tui-nomore
                :text="hasMore ? '上拉加载更多' : '没有更多了'"
                :visible="!isLoading"
                backgroundColor="#f5f5f5"
            ></tui-nomore>
        </template>

        <!-- 搜索关键词库提示 -->
        <view class="search-library-container" v-show="showLibaray">
            <scroll-view scroll-y="true" class="search-library-scroll">
                <div class="search-library-wrapper">
                    <view
                        class="keyword-item"
                        v-for="item in libraryWordList"
                        :key="item"
                        @click="
                            onLibraryClick(item)
                            hideLibrary()
                        "
                    >
                        <text class="iconfont icon-sousuo"></text>
                        <view class="content" v-html="item.text"></view>
                    </view>
                </div>
            </scroll-view>
        </view>

        <!-- 商品筛选框 -->
        <tui-drawer mode="right" :visible="showDrawer" @close="showDrawer = false">
            <product-filter :brandList="brandList" @confirm="onDrawerConfirm" @reset="onDrawerConfirm"></product-filter>
        </tui-drawer>
    </view>
</template>

<script>
import ProductList from './components/product-list.vue'
import ArticleList from './components/article-list.vue'
import MaterialList from './components/material-list.vue'
import EncyclopediaList from './components/encyclopedia-list.vue'
import ProductFilter from './components/product-filter.vue'
import SearchHeader from './components/search-header.vue'
import { debounce } from '@/common/config/common'
import { mapGetters } from 'vuex'
const myDebounce = fn => debounce(fn, 200, false)

export default {
    components: {
        ProductList,
        ArticleList,
        MaterialList,
        EncyclopediaList,
        ProductFilter,
        SearchHeader
    },
    data() {
        const menuItemList = [{ id: 1, name: '产品' }, { id: 2, name: '供应商' }]
        const tabs = [{ name: '相关产品' }, { name: '相关文章' }, { name: '相关资料' }, { name: '相关百科' }]
        return {
            // 容器相关
            tabs: tabs,
            currentTab: 0,
            menuItemList: menuItemList,
            currentMenu: 0,
            keyword: '',
            showLibaray: false,
            libraryWordList: [],
            isLoading: true,
            searchType: 'library',
            // 用户信息
            userInfo: {
                userId: 0,
                userIdentity: 1,
                vipFlag: 0,
                firstClubType: 0
            },
            // 产品相关
            currentSortItem: {},
            showDrawer: false,
            brandList: [],
            productList: [],
            productTotal: 0,
            productHasMore: true,
            productListQuery: {
                identity: 1,
                keyword: '',
                pageNum: 1,
                pageSize: 10,
                sortField: '',
                sortType: 1,
                newType: 1,
                actiType: 1,
                brandIds: '', // 品牌Id
                newFlag: 0, // 查询新品标记，默认0，新品1
                promotionFlag: 0, // 查询促销标记，默认0，促销1
                productFlag: 1, // 是否统计关键词 1 统计 0 不统计
                linkageFlag: 1 // 关键词来源是否为用户搜索 0 是 1 不是
            },
            brandListQuery: {
                keyword: '',
                id: '',
                idType: '',
                identity: 1
            },
            // 美业资料
            materialList: [],
            materialTotal: 0,
            materialHasMore: true,
            materialListQuery: {
                keyword: '', //查询关键词
                productType: 0, //商品类型 0 全部 1 仪器 2 产品
                pageNum: 1,
                pageSize: 10,
                productFlag: 1, // 是否统计关键词 1 统计 0 不统计
                linkageFlag: 1 // 关键词来源是否为用户搜索 0 是 1 不是
            },
            // 采美文章
            articleList: [],
            articleTotal: 0,
            articleHasMore: true,
            articleListQuery: {
                keyword: '',
                pageSize: 10,
                pageNum: 1,
                status: 1,
                productFlag: 1, // 是否统计关键词 1 统计 0 不统计
                linkageFlag: 1 // 关键词来源是否为用户搜索 0 是 1 不是
            },
            // 采美百科
            encyclopediaList: [],
            encyclopediaTotal: 0,
            encyclopediaHasMore: true,
            encyclopediaListQuery: {
                keyword: '',
                pageSize: 10,
                pageNum: 1,
                productFlag: 1, // 是否统计关键词 1 统计 0 不统计
                linkageFlag: 1 // 关键词来源是否为用户搜索 0 是 1 不是
            }
        }
    },
    computed: {
        ...mapGetters(['identity']),

        // 当前选中tab
        currentTabItem() {
            return this.tabs[this.currentTab]
        },
        // 列表是否为空
        isListEmpty() {
            return (
                (this.currentTab === 0 && this.productList.length === 0) ||
                (this.currentTab === 1 && this.articleList.length === 0) ||
                (this.currentTab === 2 && this.materialList.length === 0) ||
                (this.currentTab === 3 && this.encyclopediaList.length === 0)
            )
        },
        // 是否还有更多
        hasMore() {
            return (
                (this.currentTab === 0 && this.productHasMore) ||
                (this.currentTab === 1 && this.articleHasMore) ||
                (this.currentTab === 2 && this.materialHasMore) ||
                (this.currentTab === 3 && this.encyclopediaHasMore)
            )
        }
    },
    onLoad(option) {
        this.keyword = option.keyword || ''
        this.initStorage()
        this.initList()
    },
    onReachBottom() {
        this.getList()
    },
    methods: {
        // 获取用户信息
        async initStorage(option) {
            const userInfo = await this.$api.getStorage()
            if (!userInfo) return
            this.userInfo = { ...this.userInfo, ...userInfo }
        },

        // 初始化
        initList() {
            const action = {
                0: this.initProductList,
                1: this.initArticleList,
                2: this.initMaterialList,
                3: this.initEncyclopediaList
            }
            this.isLoading = true
            action[this.currentTab] && action[this.currentTab]()
        },

        // 获取列表
        getList() {
            const action = {
                0: this.fetchProductList,
                1: this.fetchArticleList,
                2: this.fetchMaterialList,
                3: this.fetchEncyclopediaList
            }
            if (!this.hasMore) return
            this.isLoading = true
            action[this.currentTab] && action[this.currentTab]()
        },

        // 初始化采美百科文章列表
        initEncyclopediaList() {
            this.encyclopediaList = []
            this.encyclopediaListQuery.keyword = this.keyword
            this.encyclopediaListQuery.pageNum = 1
            this.encyclopediaListQuery.linkageFlag = this.searchType === 'library' ? 1 : 0
            this.fetchEncyclopediaList()
        },

        // 获取采美百科文章列表
        fetchEncyclopediaList: myDebounce(async function() {
            try {
                this.isLoading = true
                const res = await this.LibraryService.GetEncyclopediaList(this.encyclopediaListQuery)
                this.encyclopediaList = [...this.encyclopediaList, ...res.data.results]
                this.encyclopediaHasMore = res.data.hasNextPage
                this.encyclopediaTotal = res.data.totalRecord
                this.encyclopediaListQuery.pageNum++
            } catch (e) {
                console.log(e)
            } finally {
                this.isLoading = false
            }
        }),

        // 初始化采美文章列表
        initArticleList() {
            this.articleList = []
            this.articleListQuery.keyword = this.keyword
            this.articleListQuery.pageNum = 1
            this.articleListQuery.linkageFlag = this.searchType === 'library' ? 1 : 0
            this.fetchArticleList()
        },

        // 获取采美文章列表
        fetchArticleList: myDebounce(async function() {
            try {
                this.isLoading = true
                const res = await this.LibraryService.GetArticleList(this.articleListQuery)
                if (!res.data) return
                const result = JSON.parse(res.data)
                this.articleList = [...this.articleList, ...result.items]
                this.articleTotal = result.articleTotal
                this.articleHasMore = result.articleTotal > this.articleList.length
                this.articleListQuery.pageNum++
            } catch (e) {
                console.log(e)
            } finally {
                this.isLoading = false
            }
        }),

        // 采美文章筛选
        onArticleFilterItemChange(filterData) {
            this.isLoading = true
            this.articleList = []
            this.articleListQuery.keyword = this.keyword
            this.articleListQuery.pageNum = 1
            this.articleListQuery.status = filterData.status
            this.articleListQuery.linkageFlag = this.searchType === 'library' ? 1 : 0
            this.fetchArticleList()
        },

        // 初始化美业资料列表
        initMaterialList() {
            this.materialList = []
            this.materialListQuery.keyword = this.keyword
            this.materialListQuery.pageNum = 1
            this.materialListQuery.productType = 0
            this.fetchMaterialList()
        },

        // 获取美业资料列表
        fetchMaterialList: myDebounce(async function() {
            try {
                this.isLoading = true
                const res = await this.LibraryService.GetProductArchive(this.materialListQuery)
                this.materialList = [...this.materialList, ...res.data.results]
                this.materialHasMore = res.data.hasNextPage
                this.materialTotal = res.data.totalRecord
                this.materialListQuery.pageNum++
            } catch (e) {
                console.log(e)
            } finally {
                this.isLoading = false
            }
        }),

        // 初始化产品列表
        initProductList() {
            this.productList = []
            this.productListQuery.pageNum = 1
            this.productListQuery.keyword = this.keyword
            this.productListQuery.identity = this.userInfo.userIdentity
            this.productListQuery.sortType = 1
            this.productListQuery.sortField = ''
            this.productListQuery.linkageFlag = this.searchType === 'library' ? 1 : 0
            this.fetchProductList()
            this.fetchBrandList()
        },

        // 获取产品列表
        fetchProductList: myDebounce(async function() {
            try {
                this.isLoading = true
                const { data } = await this.ProductService.GetProductSearchList(this.productListQuery)
                if (!data) return
                const result = JSON.parse(data)
                this.productTotal = result.total
                this.fetchProductPrice(result.items)
                this.productListQuery.pageNum++
            } catch (e) {
                this.isLoading = false
            }
        }),

        // 获取产品价格
        async fetchProductPrice(productItems = []) {
            try {
                //获取价格
                const productIds = productItems.map(item => item.productId).join(',')
                const { data } = await this.ProductService.querySearchProductPrice({
                    userId: this.userInfo.userId,
                    productIds: productIds,
                    source: 2 // 来源 1 WWW 2 小程序
                })
                const productList = productItems.map(productItem => {
                    const product = data.find(item => item.productId === productItem.productId)
                    return { ...productItem, ...product }
                })
                this.productList = [...this.productList, ...productList]
                this.productHasMore = this.productTotal > this.productList.length
                console.log(this.productList)
            } catch (e) {
                console.log(e)
            } finally {
                this.isLoading = false
            }
        },

        // 产品筛选
        productFilter() {
            this.isLoading = true
            this.productList = []
            this.productListQuery.pageNum = 1
            const sortType = { asc: 0, desc: 1 }
            const currentSortItem = this.currentSortItem
            switch (currentSortItem.id) {
                case 1:
                    this.productListQuery.sortField = ''
                    this.productListQuery.sortType = 1
                    break
                case 2:
                    this.productListQuery.sortField = 'sales'
                    this.productListQuery.sortType = sortType[currentSortItem.sortType]
                    break
                case 3:
                    this.productListQuery.sortField = 'favorite'
                    this.productListQuery.sortType = sortType[currentSortItem.sortType]
                    break
                case 4:
                    this.productListQuery.sortField = 'price'
                    this.productListQuery.sortType = sortType[currentSortItem.sortType]
                    break
            }
            this.fetchProductList()
        },

        // 获取品牌列表
        async fetchBrandList() {
            try {
                this.brandListQuery.keyword = this.keyword
                const { data } = await this.ProductService.getCommoditySearchQUeryBrand(this.brandListQuery)
                if (!data) return
                this.brandList = data.map(brand => {
                    brand.checked = false
                    return brand
                })
            } catch (e) {
                console.log(e)
            }
        },

        // drawer reset or confirm
        onDrawerConfirm(e) {
            this.showDrawer = false
            this.productListQuery.brandIds = e.brandList.map(brand => brand.id).join(',')
            this.productListQuery.promotionFlag = e.promotionFlag
            this.productListQuery.newFlag = e.newFlag
            this.productFilter()
        },

        // 产品筛选切换
        onProductFilterItemChange(item) {
            if (item.id === 5) {
                this.showDrawer = true
                return
            }
            this.currentSortItem = item
            this.productFilter()
        },

        // 搜素关键词库
        fetchLibraryWordList: myDebounce(async function() {
            try {
                const keyword = this.keyword
                const res = await this.LibraryService.GetSearchKeywordList({ keyword })
                if (!res.data) {
                    this.libraryWordList = []
                }
                this.libraryWordList = res.data.map(item => {
                    item.text = item.keyword.replace(keyword, `<span style="color:#F3B574;">${keyword}</span>`)
                    return item
                })
                if (this.libraryWordList.length <= 0) return
                this.showLibaray = true
            } catch (e) {
                console.log(e)
            }
        }),

        // 关键词点击
        onLibraryClick(item) {
            this.keyword = item.keyword
            this.searchType = 'library'
            this.initList()
        },

        // menu-item 点击事件
        onMenuItemClick(index) {
            this.currentMenu = index
        },

        // tab 切换
        onTabChange(current) {
            this.currentTab = current.index
            this.searchType = 'search'
            this.initList()
        },

        // 搜索
        onSearch: myDebounce(function() {
            if (this.currentMenu === 0) {
                this.searchType = 'keyword'
                return this.initList()
            }
            this.$api.navigateTo(`/pages/search/search-supplier?keyWord=${this.keyword}`)
        }),

        // 清空搜索框
        onClear() {
            this.keyword = ''
        },

        // 用户输入
        onInput() {
            this.fetchLibraryWordList()
        },

        // 隐藏library list
        hideLibrary() {
            this.showLibaray = false
        }
    }
}
</script>

<style lang="scss" scoped>
.search-library {
    min-height: 100vh;
    background: #f5f5f5;

    &.unScorll {
        height: 100vh;
        overflow: hidden;
    }

    .sticky-container {
        position: sticky;
        width: 100%;
        left: 0;
        top: 0;
        z-index: 99;
        background: #f5f5f5;
    }

    .search-category {
        padding: 20rpx 0;
        background: #fff;
        margin-bottom: 24rpx;
    }

    .search-wrapper {
        background: #fff;
    }

    .empty-box {
        width: 100%;
        display: flex;
        align-items: center;
        flex-direction: column;
        margin-top: 140rpx;

        .empty-image {
            width: 500rpx;
            height: 395rpx;
        }

        .empty-text {
            font-size: 24rpx;
            color: #999;
            margin-top: 32rpx;
        }
    }

    .search-library-container {
        position: fixed;
        top: 86rpx;
        left: 0;
        z-index: 1000;
        width: 100vw;
        height: calc(100vh - 88rpx);
        background: #f5f5f5;

        .search-library-scroll {
            height: 95%;
        }

        .search-library-wrapper {
            background: #fff;
            padding-top: 40rpx;
            box-sizing: border-box;
            max-height: calc(100vh - 88rpx);
            overflow-y: auto;

            .keyword-item {
                width: 100%;
                display: flex;
                justify-content: space-between;
                height: 90rpx;
                line-height: 90rpx;
                box-sizing: border-box;
                padding: 0 48rpx 0 32rpx;
                border-top: 1rpx solid #e1e1e1;

                &:last-child {
                    border-bottom: 1rpx solid #e1e1e1;
                }

                .iconfont {
                    display: block;
                    width: 34rpx;
                    margin-right: 26rpx;
                    flex-shrink: 0;
                    font-size: 34rpx;
                    color: #999;
                }

                .content {
                    flex: 1;
                    flex-shrink: 0;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 1; // 这里控制几行显示省略号
                    -webkit-box-orient: vertical;
                    font-size: 28rpx;
                    color: #333;

                    text {
                        color: #F3B574;
                    }
                }
            }
        }
    }
}
</style>
