<template>
    <view class="good-coupon-list-search">
        <!-- 搜索 -->
        <view class="search">
            <sui-search
                placeholder="请输入商品关键词"
                :radius="30"
                :focus="true"
                class="sui-search"
                :value="inputValue"
                @search="searchBlur"
                @onFocus="searchFocus"
                @clear="searchClear"
            ></sui-search>
            <view class="search-btn" @click="handleSearch">搜索</view>
        </view>
        <!-- 历史关键词 -->
        <template v-if="serachRecordList.length > 0">
            <view class="history-keywords" v-show="resetType">
                <view class="line"></view>
                <view class="row history-title">
                    <view class="title">搜索历史</view>
                    <view class="iconfont icon-shanchu delete" @click="handleDetele"></view>
                </view>
                <view class="row keyword-list">
                    <view
                        class="keyword"
                        v-for="(keyword, index) in serachRecordList"
                        :key="index"
                        @click="keywordsClick(keyword)"
                        >{{ keyword }}
                    </view>
                </view>
            </view>
        </template>
        <!-- 列表为空 -->
        <cm-empty
            v-if="productList.length <= 0 && !resetType"
            message="暂无搜索结果~"
            :image="baseUrl + 'icon-empty-search.png'"
            :offset="90"
        ></cm-empty>
        <!-- 商品列表 -->
        <view class="product-list" v-show="!resetType">
            <view class="product" v-for="(product, index) in productList" :key="index">
                <image class="product-image" :src="product.mainImage"></image>
                <view class="product-info">
                    <view class="name tui-ellipsis-2">{{ product.name }}</view>
                    <view class="unit">规格：{{ product.unit }}</view>
                    <view class="tags">
                        <text class="tag type2" v-if="product.activeStatus === 1">活动价</text>
                        <text class="tag type2" v-if="product.couponsLogo">优惠券</text>
                    </view>
                    <view class="footer">
                        <view class="price">￥{{ product.price | priceFormat }}</view>
                        <text class="carts-add iconfont icon-gouwuche" @click.stop="handAddCarts(product)"></text>
                    </view>
                </view>
            </view>
            <!-- 加载更多 -->
            <template v-if="productList.length > 6">
                <tui-loadmore :index="2" :visible="isRequest"></tui-loadmore>
                <tui-nomore :text="loadingText" :visible="!isRequest" backgroundColor="#fff"></tui-nomore>
            </template>
        </view>
        <!-- 侧边 -->
        <scroll-top :isScrollTop="isScrollTop" :bottom="160"></scroll-top>
        <!-- 可拖动悬浮按钮 -->
        <cm-drag :cartNum="kindCount" :isDock="true" :existTabBar="true" @btnClick="btnClick"> </cm-drag>
        <!-- 操作弹窗 -->
        <tui-modal
            :show="showModal"
            @click="handleConfirm"
            @cancel="showModal = false"
            :content="contentModalText"
            color="#333"
            :size="32"
            shape="circle"
            :maskClosable="false"
        ></tui-modal>
    </view>
</template>

<script>
import SuiSearch from '@/components/sui-search/sui-search.vue'
import CmEmpty from '@/components/cm-module/cm-empty/cm-empty.vue'
import CmDrag from '@/components/cm-module/cm-drag/cm-drag'
import { mapGetters, mapActions } from 'vuex'
export default {
    components: {
        SuiSearch,
        CmEmpty,
        CmDrag
    },
    data() {
        return {
            baseUrl: this.$Static,
            showModal: false,
            productList: [], //商品列表
            serachRecordList: [],
            listQuery: {
                userId: '',
                couponId: 48,
                pageNum: 1,
                pageSize: 10,
                productName: ''
            },
            inputValue: '',
            hasNextPage: false,
            isScrollTop: false,
            isRequest: true,
            timer: null,
            isSticky: false,
            isFocus: true,
            resetType: true, // true 重新搜索  false 上拉加载
            contentModalText: '确定删除历史记录？'
        }
    },
    filters: {
        priceFormat: function(price) {
            //处理金额
            return Number(price).toFixed(2)
        }
    },
    computed: {
        ...mapGetters(['hasLogin', 'userInfo', 'userId', 'kindCount']),
        loadingText() {
            return this.hasNextPage ? '上拉加载' : '没有更多了'
        }
    },
    // 监听页面滚动事件
    onPageScroll(e) {
        this.isSticky = e.scrollTop > 0
        this.isScrollTop = e.scrollTop > 400
    },
    onReachBottom() {
        if (!this.hasNextPage) return
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
            console.log('触底了')
            this.fetchProductList()
        }, 200)
    },
    onReady() {
        this.getetSerachRecord()
    },
    methods: {
        ...mapActions('cart', ['addToCart']),
        // 获取商品列表
        fetchProductList() {
            this.listQuery.userId = this.userId
            this.CouponService.ProductInfoByCoupon(this.listQuery)
                .then(response => {
                    let data = response.data
                    if (this.resetType) {
                        this.productList = data.list
                    } else {
                        this.productList = [...this.productList, ...data.list]
                    }
                    this.hasNextPage = data.hasNextPage
                    this.listQuery.pageNum++
                    this.resetType = false
                    this.isRequest = false
                })
                .catch(error => {
                    this.$util.msg(error.msg, 2000)
                })
        },
        //查询搜索历史记录
        getetSerachRecord() {
            this.ProductService.GetProductSearchHistory({ userId: this.userId }).then(response => {
                if (response.code == 0) {
                    this.serachRecordList = response.data
                }
            })
        },
        // 搜索按钮事件
        handleSearch() {
            if (!this.listQuery.productName) return this.$util.msg('商品名称不能为空', 2000)
            this.listQuery.pageNum = 1
            this.productList = []
            this.fetchProductList()
        },
        // 点击关键词
        keywordsClick(keyword) {
            this.listQuery.productName = keyword
            this.inputValue = keyword
            this.handleSearch()
        },
        // 加入购物车
        handAddCarts(product) {
            this.addToCart({ productId: product.productId })
        },
        // 跳转购物车
        btnClick() {
            this.$api.navigateTo('/pages/goods/cart')
        },
        // 搜索框失去焦点
        searchBlur(val) {
            console.log('失去焦点')
            this.listQuery.productName = val
            this.isFocus = false
        },
        // 搜索框获取焦点
        searchFocus() {
            console.log('获取焦点')
            this.getetSerachRecord()
            this.resetType = true // 重新搜索
            this.isFocus = true
        },
        // 清空搜索
        searchClear() {
            this.inputValue = ''
            this.resetType = true // 重新搜索
            this.isFocus = true
            this.getetSerachRecord()
        },
        //清空历史记录
        handleDetele() {
            this.showModal = true
        },
        // 确认事件
        handleConfirm(e) {
            if (e.index === 1) this.removeAllKeywords()
            this.showModal = false
        },
        // 清空关键词
        removeAllKeywords() {
            this.ProductService.GetDeleteProductSearchHistory({ userId: this.userId })
                .then(response => {
                    this.$util.msg('删除成功', 2000, true, 'success')
                    this.serachRecordList = []
                })
                .catch(error => {
                    this.$util.msg(error.msg, 2000)
                })
        }
    }
}
</script>

<style lang="scss" scoped>
.good-coupon-list-search {
    min-height: 100vh;
    padding-top: 124rpx;
    background: #f7f7f7;
    overflow: hidden;
    box-sizing: border-box;
}
.search {
    display: flex;
    position: fixed;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    top: 0;
    left: 0;
    z-index: 999;
    padding-right: 24rpx;
    box-sizing: border-box;
    background: #fff;
    // &.fixed {
    //     position: fixed;
    // }
    .sui-search {
        flex: 1;
    }
    .search-btn {
        font-size: 26rpx;
        color: #666;
    }
}
.history-keywords {
    background: #fff;
    // padding: 0 24rpx;
    .line {
        height: 1rpx;
        margin: 0 24rpx;
        background: #e1e1e1;
    }
    .history-title {
        margin: 48rpx 24rpx 24rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .title {
            height: 42rpx;
            line-height: 42rpx;
            font-size: 30rpx;
            font-weight: bold;
            color: #333333;
        }
        .delete {
            width: 32rpx;
            height: 32rpx;
            font-size: 32rpx;
            color: #999999;
        }
    }
    .keyword-list {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        padding: 0 12rpx;
        .keyword {
            height: 44rpx;
            padding: 0 12rpx;
            margin: 24rpx 12rpx;
            font-size: 26rpx;
            line-height: 44rpx;
            border-radius: 22rpx;
            color: #999999;
            text-align: center;
            background: #f7f7f7;
        }
    }
}
.product-list {
    padding: 0 24rpx;
    background: #fff;
    overflow: hidden;
    .product {
        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-image {
            display: block;
            width: 180rpx;
            height: 180rpx;
            border-radius: 8rpx;
            border: 1px solid #e1e1e1;
            border-radius: 8rpx;
            box-sizing: border-box;
        }
        .product-info {
            width: 495rpx;
            .name {
                height: 72rpx;
                line-height: 36rpx;
                font-size: $font-size-26;
                color: #333333;
                text-align: justify;
            }
            .unit,
            .tags,
            .footer {
                margin-top: 8rpx;
            }
            .unit {
                width: 100%;
                height: 28rpx;
                text-align: left;
                line-height: 28rpx;
                font-size: $font-size-20;
                color: #999999;
            }
            .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;
                    }
                }
            }
            .footer {
                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>
