<template>
    <view class="search-container">
        <view class="search-main">
            <view class="gosearch-btn">
                <text class="iconfont icon-sousuo"></text>
                <input
                    class="input"
                    maxlength="20"
                    :focus="isFocus"
                    type="text"
                    value=""
                    confirm-type="search"
                    @focus="onFocus"
                    @input="onShowClose"
                    @confirm="SubMitSearch()"
                    placeholder="请输入搜索关键字"
                    v-model.trim="listQuery.name"
                />
                <text class="iconfont icon-quxiao" v-if="isShowClose" @click.stop="delInputText()"></text>
            </view>
            <view class="search-btn" @click="SubMitSearch()">搜索</view>
        </view>
        <view class="search-container-history clearfix" v-if="!isShowWrapper">
            <view :class="'s-' + themeClass" v-if="serachRecordList.length > 0">
                <view class="header">搜索历史<text class="iconfont icon-shanchu" @click="confirmDetele"></text></view>
                <view class="list">
                    <view class="list-main">
                        <view v-for="(item, index) in serachRecordList" :key="index" @click="keywordsClick(item)">{{
                            item
                        }}</view>
                    </view>
                </view>
            </view>
        </view>
        <view
            v-else
            class="commodity-list-wrapper"
            :style="{ overflow: 'auto', height: productList.length > 4 ? windowHeight + 'px' : 'auto' }"
        >
            <scroll-view
                :style="{ height: productList.length > 4 ? scrollHeight + 'px' : 'auto' }"
                @scrolltolower="scrolltolower"
                scroll-y
                v-if="!showEmpty"
                class="scroll-view"
            >
                <view
                    v-for="(pro, index) in productList"
                    :key="index"
                    :id="pro.id"
                    class="product-list-type commodity-list"
                    @click.stop="navToDetailPage(pro.productId)"
                >
                    <view class="product-list-image">
                        <image class="product-image" :src="pro.mainImage" mode=""></image>
                    </view>
                    <view class="product-list-msgs">
                        <view class="product-name tui-ellipsis-2">{{ pro.name }}</view>
                        <view class="product-unit">规格：{{ pro.unit }}</view>
                        <view class="product-tags">
                            <text class="tag type2" v-if="pro.activeStatus === 1">活动价</text>
                            <text class="tag type2" v-if="pro.couponsLogo">优惠券</text>
                        </view>
                        <view class="product-price">
                            <view class="price">￥{{ pro.price | PriceFormat }}</view>
                            <text class="carts-add iconfont icon-gouwuche" @click.stop="handAddCarts(pro)"></text>
                        </view>
                    </view>
                </view>
                <view v-if="showLoading && productList.length > 5">
                    <view class="loading-wrapper loading-wrapper-now" v-if="loadingNow">
                        <template>{{ loadingText }}</template>
                        <text v-if="loadingText === '已至底部'">‧ ‧ ‧</text>
                    </view>
                    <view class="loading-wrapper loading-wrapper-btm" v-else>
                        <text class="btm-text">———已至底部———</text>
                    </view>
                </view>
            </scroll-view>
            <view class="empty-container" v-if="showEmpty">
                <image class="empty-container-image" :src="StaticUrl + 'icon-empty-search.png'"></image>
                <text class="error-text">暂无搜索结果~</text>
            </view>
        </view>
        <!-- 操作弹窗 -->
        <tui-modal
            :show="modal"
            @click="handleClick"
            @cancel="hideMobel"
            :content="contentModalText"
            color="#333"
            :size="32"
            shape="circle"
            :maskClosable="false"
        ></tui-modal>
        <!-- 透明模态层 -->
        <modal-layer v-if="isModallayer"></modal-layer>
    </view>
</template>

<script>
import { mapGetters, mapActions, mapMutations } from 'vuex'
import modalLayer from '@/components/cm-module/modal-layer/modal-layer'
import authorize from '@/common/authorize.js'
import wxLogin from '@/services/wxLogin.js'

export default {
    components: {
        modalLayer
    },
    data() {
        return {
            StaticUrl: this.$Static,
            themeClass: 'block',
            show: false,
            isShowClose: false, //是否显示清空输入框图标
            serachRecordList: [
                { searchWord: '奥术大师大所打' },
                { searchWord: '奥术大师大所打' },
                { searchWord: '奥术大师大所打' },
                { searchWord: '奥术大师大所打' },
                { searchWord: '奥术大师大所打' },
                { searchWord: '奥术大师大所打' }
            ], //历史搜索记录
            isShowWrapper: true,
            isModallayer: false,
            isFocus: false,
            windowHeight: '',
            showEmpty: false,
            scrollHeight: '',
            productList: [], //商品列表				productIds:'',//查询价格的商品ID
            showLoading: false,
            loadingNow: true,
            loadingText: '上拉加载更多',
            hasNextPage: false,
            pullFlag: true,
            listQuery: {
                userId: 0,
                name: '',
                pageNum: 1,
                pageSize: 20
            },
            modal: false,
            contentModalText: '确定删除历史记录？'
        }
    },
    onLoad(option) {
        this.listQuery.userId = this.userId
        if (option.keyWord) {
            this.listQuery.name = option.keyWord
            this.getListFromServer()
            this.isFocus = false
        } else {
            this.isFocus = true
            this.InitGetSerachRecord()
        }
    },
    filters: {
        PriceFormat: function(text) {
            //处理金额
            return Number(text).toFixed(2)
        }
    },
    computed: {
        ...mapGetters(['hasLogin', 'userId', 'userIdentity'])
    },
    methods: {
        ...mapActions('cart', ['addToCart']),
        //查询搜索历史记录
        InitGetSerachRecord() {
            this.ProductService.GetProductSearchHistory({ userId: this.listQuery.userId }).then(response => {
                if (response.code == 0) {
                    this.serachRecordList = response.data
                }
            })
        },
        //搜索
        SubMitSearch() {
            if (this.listQuery.name == '') {
                this.$util.msg('请输入搜索关键词', 2000)
            } else {
                this.productList = []
                this.getListFromServer()
                this.isFocus = false
            }
        },
        scrolltolower() {
            if (this.total > this.productList.length && this.pullFlag) {
                this.getListFromServer(true)
            }
        },
        //搜索商品
        getListFromServer(loadMore) {
            this.showLoading = true
            this.loadingNow = true
            this.loadingText = '加载中'
            this.showEmpty = false
            if (loadMore) {
                this.listQuery.pageNum += 1
            }
            this.ProductService.GetProductList(this.listQuery)
                .then(response => {
                    this.isShowWrapper = true
                    const data = response.data
                    const dataList = data.list
                    if (dataList && dataList.length > 0) {
                        this.hasNextPage = data.hasNextPage
                        this.showEmpty = false
                        if (loadMore) {
                            this.productList = [...this.productList, ...dataList]
                        } else {
                            this.productList = [...dataList]
                        }
                        // 防上拉暴滑
                        this.pullFlag = false
                        setTimeout(() => {
                            this.pullFlag = true
                        }, 500)
                        // 底部提示文案
                        if (this.hasNextPage) {
                            this.loadingText = '上拉加载更多'
                        } else {
                            this.showLoading = true
                            this.loadingNow = false
                        }
                    } else {
                        if (!loadMore) {
                            this.showEmpty = true
                        }
                    }
                })
                .catch(error => {
                    this.$util.msg(error.msg, 2000)
                })
        },
        handAddCarts(pro) {
            this.addToCart({ productId: pro.productId })
        },
        //输入框输入时触发
        onShowClose() {
            this.inputEmpty(this.listQuery.name)
        },
        //输入框获取焦点时触发
        onFocus() {
            this.inputEmpty(this.listQuery.name)
            this.InitGetSerachRecord()
        },
        //清除输入框内容
        delInputText() {
            this.listQuery.name = ''
            this.isShowClose = false
            this.isShowWrapper = false
            this.inputEmpty(this.listQuery.name)
            this.InitGetSerachRecord()
        },
        //关键词搜索与历史搜索
        keywordsClick(item) {
            this.listQuery.name = item
            this.isShowClose = true
            this.isFocus = false
            this.SubMitSearch()
        },
        //清空历史记录
        confirmDetele() {
            this.modal = true
        },
        //用户操作订单
        handleClick(e) {
            let index = e.index
            if (index == 1) {
                this.ProductService.GetDeleteProductSearchHistory({ userId: this.listQuery.userId })
                    .then(response => {
                        this.$util.msg('删除成功', 2000, true, 'success')
                        this.serachRecordList = []
                    })
                    .catch(error => {
                        this.$util.msg(error.msg, 2000)
                    })
            }
            this.modal = false
        },
        hideMobel() {
            this.modal = false
        },
        inputEmpty(val) {
            this.isShowWrapper = false
            if (val != '') {
                this.isShowClose = true
                this.isFocus = true
            } else {
                this.isShowClose = false
                this.isFocus = true
            }
        },
        isInterceptHtmlFn(text) {
            let name = this.$reg.interceptHtmlFn(text)
            return name
        },
        navToDetailPage(id) {
            this.isModallayer = true
            this.$api.navigateTo(`/pages/goods/product?productId=${id}`)
            this.isModallayer = false
        },
        setScrollHeight() {
            const { windowHeight, pixelRatio } = wx.getSystemInfoSync()
            this.windowHeight = windowHeight - 1
            this.scrollHeight = windowHeight - 1
        },
        toLoginPage() {
            let searchLoginType = 'search'
            uni.navigateTo({
                url: `/pages/login/login?type=${searchLoginType}`
            })
        },
        topBubble() {
            //显隐搜索项
            this.show = !this.show
        }
    },
    //分享转发
    onShareAppMessage(res) {
        // 加密参数
        const shareData = {
            type: 2,
            keyWord: this.listQuery.name,
            inviteUserId: this.userId
        }
        // 加密
        const state_str = encodeURIComponent(this.$crypto.encrypt(shareData))
        return {
            title: `点击查看“${this.listQuery.name}”相关的商品`,
            path: `/pages/tabBar/index/index?state_str=${state_str}`
        }
    },
    onShow() {
        this.setScrollHeight()
    }
}
</script>

<style lang="scss">
@import '@/uni.scss';
page {
    background-color: #f7f7f7 !important;
}
.search-main {
    width: 100%;
    height: 88rpx;
    position: fixed;
    top: 0;
    left: 0;
    background: #ffffff;
    z-index: 1001;
    box-sizing: border-box;
    padding: 9rpx 24rpx;
    .gosearch-btn {
        width: 604rpx;
        height: 100%;
        float: left;
        border-radius: 40rpx;
        background: #f0f0f0;
        margin: 0 auto;
        padding: 0 20rpx;
        font-size: 28rpx;
        line-height: 66rpx;
        padding-left: 66rpx;
        color: #8a8a8a;
        background: #f7f7f7;
        position: relative;
        box-sizing: border-box;
        .icon-sousuo {
            width: 66rpx;
            height: 66rpx;
            line-height: 66rpx;
            text-align: center;
            display: block;
            position: absolute;
            left: 0;
            top: 0;
            font-size: 34rpx;
            color: #8a8a8a;
            z-index: 10;
        }
        .icon-quxiao {
            width: 66rpx;
            height: 66rpx;
            display: block;
            line-height: 66rpx;
            font-size: 36rpx;
            text-align: center;
            color: #8a8a8a;
            position: absolute;
            right: 10rpx;
            top: 0;
            padding: 0 10rpx;
            z-index: 100;
        }
        .input {
            width: 530rpx;
            height: 100%;
            float: left;
            font-size: $font-size-24;
            box-sizing: border-box;
            padding-right: 66rpx;
        }
    }
    .search-btn {
        width: 90rpx;
        height: 66rpx;
        line-height: 66rpx;
        float: right;
        text-align: center;
        color: #666666;
        font-size: $font-size-24;
    }
}
.search-container {
    padding-top: 91rpx;
}
.search-container-history {
    width: 100%;
    height: auto;
    background-color: #ffffff;
}
.s-block {
    background: #ffffff;
    &.hot {
        border-top: 20rpx solid #f7f7f7;
    }
    .header {
        font-size: 32rpx;
        padding: 40rpx 24rpx 22rpx 24rpx;
        line-height: 42rpx;
        font-size: 30rpx;
        font-weight: bold;
        position: relative;
        width: 100%;
        float: left;
        box-sizing: border-box;
        .icon-shanchu {
            font-size: 36rpx;
            color: #333333;
            float: right;
            padding: 0 10rpx;
            z-index: 10;
            font-weight: normal;
        }
    }
    .list {
        width: 100%;
        height: auot;
        float: left;
        padding: 0 24rpx 30rpx 24rpx;
        box-sizing: border-box;
        .list-main {
            width: 100%;
            float: left;
            display: flex;
            flex-wrap: wrap;
            view {
                color: #8a8a8a;
                font-size: 24rpx;
                box-sizing: border-box;
                text-align: center;
                height: 48rpx;
                line-height: 48rpx;
                border-radius: 24rpx;
                margin: 12rpx 12rpx 12rpx 0;
                padding: 0 20rpx;
                white-space: nowrap;
                text-overflow: ellipsis;
                background-color: #f3f3f3;
                .iconfont {
                    font-size: $font-size-30;
                    color: #e15616;
                    margin-left: 12rpx;
                }
                &.list-active {
                    background-color: #fef6f3;
                    color: #e15616;
                }
            }
        }
    }
}
.commodity-list-wrapper {
    box-sizing: border-box;
    padding: 0 24rpx;
    background: #ffffff;
    .scroll-view {
        height: 100%;
        overflow: scroll;
    }
    .empty-container-image {
        margin-top: -300rpx;
    }
}
.product-list-type {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx 0;
    border-bottom: 1px solid #e1e1e1;
    overflow: hidden;
    &:last-child {
        border-bottom: 0;
    }
    .product-list-image {
        width: 182rpx;
        height: 182rpx;
        box-sizing: border-box;
        border-radius: 8rpx;
        border: 1px solid #e1e1e1;
        .product-image {
            width: 180rpx;
            height: 180rpx;
            display: block;
            border-radius: 8rpx;
        }
    }
    .product-list-msgs {
        width: 495rpx;
        height: 100%;
        .product-name {
            width: 100%;
            height: 72rpx;
            line-height: 36rpx;
            font-size: $font-size-26;
            color: #333333;
            text-align: justify;
        }
        .product-unit,
        .product-tags,
        .product-price {
            margin-top: 8rpx;
        }
        .product-unit {
            width: 100%;
            height: 28rpx;
            text-align: left;
            line-height: 28rpx;
            font-size: $font-size-20;
            color: #999999;
        }
        .product-tags {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            width: 100%;
            height: 30rpx;
            .tag {
                margin-right: 8rpx;
                font-size: 22rpx;
                height: 30rpx;
                line-height: 30rpx;
                text-align: center;
                &.type2 {
                    width: 80rpx;
                    color: #f83c6c;
                    background: url(https://static.caimei365.com/app/mini-hehe/icon/icon-active.png) top center
                        no-repeat;
                    background-size: contain;
                }
            }
        }
        .product-price {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            height: $font-size-26;
            .price {
                font-size: $font-size-26;
                color: #f83c6c;
                font-weight: bold;
                line-height: $font-size-26;
            }
            .carts-add {
                width: 44rpx;
                height: 44rpx;
                line-height: 44rpx;
                border-radius: 50%;
                text-align: center;
                font-size: 32rpx;
                color: #ffffff;
                background-color: #ff457b;
            }
        }
    }
}
</style>
