// package_A/pages/goods-detail/index.js
import {storeInfo, exchange} from '../../../api/goods.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 商品详情信息
        detail: {},
        // 轮播图列表
        coverList: [],
        // 详情图片列表
        detailImages: [],
        // 商铺信息
        storeDetail: {},
        // 商品数量
        numbers: 1
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.data) {
            let detail = this.data.detail
            let coverList = []
            let detailImages = []
            detail = JSON.parse(decodeURIComponent(options.data))
            this.getStoreInfo({merchantId: detail.merchantId})
            if(detail.goodsImage) {
                coverList = detail.goodsImage.split(',')
            }
            if(detail.goodsDetailImage) {
                detailImages = detail.goodsDetailImage.split(',')
            }
            this.setData({detail, coverList, detailImages})
        }
    },

    // 获取商铺信息
    async getStoreInfo(params) {
        const res = await storeInfo(params)
        if(res.code === 0) {
            let storeDetail = this.data.storeDetail
            storeDetail = res.data
            this.setData({
                storeDetail
            })
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },
    // 加数量
    addNum() {
        let numbers = this.data.numbers
        this.setData({
            numbers: numbers + 1
        })
    },
    // 减数量
    reduceNum() {
        let numbers = this.data.numbers
        if(numbers !== 1) {
            this.setData({
                numbers: numbers - 1
            })
        } else {
            wx.showToast({
                icon: "none",
                title: '请至少选择一件商品！',
            })
        }
    },
    // 兑换
    exchangeGoods() {
        let params = {}
        params.goodsId = this.data.detail.id
        params.goodsCount = this.data.numbers
        params.openid = wx.getStorageSync('openid')
        exchange(params).then(res=> {
            if(res.code === 0) {
                // 成功跳转页面
                wx.navigateTo({
                    url: '/package_A/pages/exchange-success/index?data=' + encodeURIComponent(JSON.stringify(this.data.storeDetail))
                })
            } else {
                wx.showToast({
                    icon: 'error',
                    title: res.msg,
                    duration: 2000
                })
            }
        }).catch((e)=> {
            wx.showToast({
                icon: 'error',
                title: e.msg,
                duration: 2000
            })
        })
    }

})