<template>
    <view class="goods-search">
        <!-- 搜索区域 -->
        <view class="order-top sticky-top">
            <cm-search
                v-model="listQuery.name"
                placeholder="请输入搜索关键字"
                :keywordVisible="keywordVisible"
                :keywordList="keywordList"
                @focus="keywordVisible = true"
                @clear="keywordVisible = true"
                @remove="removeKeywordModal = true"
                @search="handleSearch"
            ></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">
                        <!-- 拼团价  活动价  限时特价  券后价   -->
                        <!-- 该商品参与了商城活动 -->
                        <template v-if="isActivityProduct(product)">
                            <view class="tag pt" v-if="product.collageStatus > 0">拼团价</view>
                            <view class="tag hd" v-else-if="product.activeStatus > 0">活动价</view>
                            <view class="tag other" v-else-if="product.discountStatus > 0">限时特价</view>
                        </template>
                        <!-- 该商品未参与商城活动 -->
                        <template v-else>
                            <view class="tag other" v-if="product.couponStatus > 1">{{ product.couponInfo }}</view>
                            <view class="tag other" v-else-if="product.couponStatus > 0">券后价</view>
                        </template>
                    </view>
                    <!-- 底部 -->
                    <view class="footer">
                        <!-- 价格 -->
                        <view class="price">
                            <text>￥{{ showPrice(product) | 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>
        <!-- 安全区域 -->
        <cm-safe-area-bottom v-if="visiable"></cm-safe-area-bottom>
    </view>
</template>

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

export default {
    data() {
        return {
            isLoading: true,
            // 搜索框
            keywordVisible: true,
            removeKeywordModal: false,
            keywordList: [],
            listQuery: makeQuery(),
            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: {
        isActivityProduct(product) {
            return product.collageStatus > 0 || product.activeStatus > 0 || product.discountStatus > 0
        },

        showPrice(product) {
            return product.couponStatus === 1 && !this.isActivityProduct(product) ? product.couponPrice : product.price
        },

        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 { data } = await fetchProductList(this.listQuery)
                this.total = data.pageInfo.totalRecord
                this.hasNextPage = data.pageInfo.hasNextPage
                this.list = [...this.list, ...data.pageInfo.results]
                this.listQuery.pageNum++
                this.isLoading = false
            } catch (e) {
                console.log(e)
            }
        }),
        // 关键词历史记录
        async fetchHistoryList() {
            try {
                const res = await fetchProductSearchHistory({ userId: this.userId })
                this.keywordList = res.data.map(item => item.searchWord)
                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>
