<template>
    <view class="goods-search">
        <!-- 搜索区域 -->
        <view class="order-top sticky-top">
            <cm-search
                v-model="listQuery.name"
                @search="handleSearch"
                placeholder="请输入搜索关键字"
                :keywordVisible="keywordVisible"
                :keywordList="keywordList"
                @focus="keywordVisible = true"
                @clear="keywordVisible = true"
                @remove="removeKeywordModal = true"
            ></cm-search>
        </view>
        <!-- 订单列表为空 -->
        <template v-if="list.length <= 0 && !isLoading">
            <tui-no-data :imgUrl="emptyInfo.image" :imgHeight="230" :imgWidth="290">
                <view class="empty-tip" v-text="emptyInfo.message"></view>
            </tui-no-data>
        </template>
        <view class="list">
            <view class="product" v-for="product in list" :key="product.productId" @click="toDetail(product)">
                <image :src="product.mainImage" mode="widthFix" class="cover"></image>
                <view class="info">
                    <view class="title">{{ product.name }}</view>
                    <view class="unit">规格：{{ product.unit }}</view>
                    <view class="tags">
                        <view class="tag pt" v-if="product.collageStatus === 1">拼团价</view>
                        <view class="tag hd" v-if="product.activeStatus == 1 && product.collageStatus === 0">
                            活动价
                        </view>
                        <view class="tag hd" v-if="product.couponsLogo">优惠券</view>
                    </view>
                    <!-- 底部 -->
                    <view class="footer">
                        <!-- 价格 -->
                        <view class="price">
                            <text>￥{{ product.price | priceFormat }}</text>
                            <text class="deleted" v-if="product.normalPrice">
                                ￥{{ product.normalPrice | priceFormat }}
                            </text>
                        </view>
                        <!-- 加入购物车 -->
                        <view
                            class="add-cart iconfont icon-gouwuche"
                            @click.stop="addCart(product)"
                            v-if="product.collageStatus !== 1"
                        ></view>
                    </view>
                </view>
            </view>
            <!-- 没有更多了 -->
            <cm-loadmore
                :hasMore="hasNextPage"
                :isLoading="isLoading"
                :visiable="visiable"
                backgroundColor="#fff"
            ></cm-loadmore>
        </view>
        <!-- 操作弹窗 -->
        <tui-modal :show="removeKeywordModal" content="确认清空搜索历史记录？" @click="clearAllHistory"></tui-modal>
    </view>
</template>

<script>
import { fetchProductList, fetchProductSearchHistory, clearProductSearchHistory } from '@/services/api/goods.js'
import { debounce } from '@/common/utils.js'
import { mapGetters } from 'vuex'

export default {
    data() {
        return {
            isLoading: true,
            // 搜索框
            keywordVisible: true,
            removeKeywordModal: false,
            keywordList: [],
            listQuery: {
                name: '',
                userId: '',
                pageNum: 1,
                pageSize: 10
            },
            list: [],
            total: 0,
            hasNextPage: true
        }
    },
    computed: {
        ...mapGetters(['userId']),
        emptyInfo() {
            const info = {}
            info.image = `${this.staticUrl}icon-empty-address.png`
            info.message = '未找到相关商品~_~'

            if (this.keywordList.length <= 0) {
                info.message = '暂无任何搜索历史记录~_~'
            }

            return info
        },
        visiable() {
            return this.list.length > this.listQuery.pageSize
        }
    },
    watch: {
        keywordVisible(nVal) {
            if (!nVal) return
            this.fetchHistoryList()
            this.list = []
        }
    },
    onLoad() {
        this.fetchHistoryList()
    },
    onReachBottom() {
        if (this.hasNextPage) {
            this.fetchList()
        }
    },
    methods: {
        toDetail(row) {
            this.$router.navigateTo(`goods/goods-detail?jumpState=1?productId=${row.productId}`)
        },
        // 加入购物车
        addCart(row) {
            this.$store.dispatch('cart/addToCart', { productId: row.productId })
        },
        handleSearch() {
            this.list = []
            this.listQuery.pageNum = 1
            this.keywordVisible = false
            if (!this.listQuery.name) {
                this.$toast('搜索内容不能为空')
                return
            }
            this.fetchList()
        },
        fetchList: debounce(async function() {
            this.listQuery.userId = this.userId
            try {
                const res = await fetchProductList(this.listQuery)
                this.total = res.data.total
                this.hasNextPage = res.data.hasNextPage
                this.list = [...this.list, ...res.data.list]
                this.listQuery.pageNum++
            } catch (e) {
                console.log(e)
            }
        }),
        // 关键词历史记录
        async fetchHistoryList() {
            try {
                const res = await fetchProductSearchHistory({ userId: this.userId })
                this.keywordList = res.data
                this.isLoading = false
            } catch (e) {
                console.log(e)
            }
        },
        // 清空关键词历史记录
        async clearAllHistory(e) {
            if (!e.index) return (this.removeKeywordModal = false)
            try {
                await clearProductSearchHistory({ userId: this.userId })
                await this.fetchHistoryList()
                this.removeKeywordModal = false
                this.$toast('已清空搜索历史记录')
            } catch (e) {
                console.log(e)
            }
        }
    }
}
</script>

<style lang="scss" scoped>
$radius: 16rpx;
$grid: 16rpx;

.goods-search {
    padding-bottom: 44rpx;
    background-color: #fff;

    .list {
        padding: 0 24rpx;

        .product {
            @extend .cm-flex-between;
            align-items: flex-start;
            overflow: hidden;
            padding: 24rpx 0;
            border-bottom: 1rpx solid #f1f1f1;
            .cover {
                width: 180rpx;
                height: 180rpx;
                box-sizing: border-box;
                border-radius: 8rpx;
                box-sizing: border-box;
                background-color: #f7f7f7;
            }
            .info {
                width: 496rpx;
                margin-left: 24rpx;
            }
            .tags,
            .unit,
            .footer {
                margin-top: 18rpx;
            }
            .title {
                height: 35rpx;
                font-size: 26rpx;
                line-height: 35rpx;
                text-align: justify;
                color: #333333;
                @include ellipsis(1);
            }
            .unit {
                font-size: 20rpx;
                color: #999999;
            }
            .tags {
                @extend .cm-flex-center;
                justify-content: flex-start;
                height: 24rpx;
            }
            .footer {
                position: relative;

                .add-cart {
                    position: absolute;
                    bottom: 0;
                    right: 16rpx;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    width: 44rpx;
                    height: 44rpx;
                    background: #ff457b;
                    color: #fff;
                    border-radius: 50%;
                }
                .price {
                    box-sizing: border-box;
                    padding-right: 16rpx;
                    font-size: 26rpx;
                    font-weight: 600;
                    color: #f83c6c;
                    .deleted {
                        font-size: 20rpx;
                        color: #999999;
                        text-decoration: line-through;
                        font-weight: normal;
                    }
                }
            }
        }
    }
}
</style>
