// pages/groupmeallist/refund/refund.js
import order from '../../../api/order'
const cache = require('../../../utils/cache.js');
import base from "../../../utils/base";
import Upload from '../../../api/upload'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        orderGoodList: [{}, {}, {}, {}],
        showAllSku: false,
        orderInfo: {},
        orderSn: '',
        chooseViewShowBanner: true,
        orderGoodList: [], //spu-sku商品信息
        isShowPannel: false,
        reasonValue: '请选择退款原因',
        reasonDetailValue: '',
        avatarUrlShow: [],
        t_length: 0,
        avatarUrl: [],
        reasonListChecked: false,
        reasonList: [{
            text: '不想要了/临时有事',
            checked: false
        }, {
            text: '点错了/点多了/点少了',
            checked: false
        }, {
            text: '地址/电话填错了',
            checked: false
        }, {
            text: '忘记用红包/优惠券',
            checked: false
        }, {
            text: '菜品质量问题',
            checked: false
        }, {
            text: '出餐/送餐速度过慢',
            checked: false
        }, {
            text: '没有按承诺的优惠',
            checked: false
        }, {
            text: '其他',
            checked: false
        }, ]




    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.sn) {
            this.reloadPage(options.sn)
        }
    },
    reloadPage(orderSn) {
        this.setData({
            orderSn
        })

        this.getOrderdetail();
    },
    listenInput(e) {
        let value = e.detail.value;
        this.setData({
            reasonDetailValue: value
        })

    },
    callStorePerson() {
        let phone = this.data.orderInfo.store.liaisonPhone;
        wx.makePhoneCall({
            phoneNumber: phone
        })
    },
    /** 图片选择 */
    bindViewTap: function () {
        var that = this;
        if (this.data.avatarUrlShow.length < 4) {
            wx.chooseImage({
                // 设置最多可以选择的图片张数，默认9,如果我们设置了多张,那么接收时//就不在是单个变量了,
                count: 1,
                sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
                sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
                success: function (res) {
                    // 获取成功,将获取到的地址赋值给临时变量
                    console.log(res);
                    if (res.tempFilePaths.count == 0) {
                        return;
                    }
                    //图片上传到金山云
                    var tempFilePaths = res.tempFilePaths

                    wx.uploadFile({
                        url: Upload.uploadPic(),
                        filePath: tempFilePaths[0],
                        name: 'file',
                        formData: {
                            'basePath': 'welfareMall',
                        },
                        success: function (res) {
                            //提交路径
                            var urlImg = JSON.parse(res.data).data.url;
                            //展示路径
                            var destPath = JSON.parse(res.data).data.destPath;

                            var imgArrNow = that.data.avatarUrl;
                            var imgArrNowShow = that.data.avatarUrlShow;
                            imgArrNow.push(urlImg);
                            imgArrNowShow.push(destPath);
                            if (that.data.avatarUrlShow.length > 4) {
                                wx.showToast({
                                    title: '最多添加4张图片',
                                    icon: 'none',
                                    duration: 1500
                                })
                                return
                            }
                            that.setData({
                                //将临时变量赋值给已经在data中定义好的变量
                                avatarUrl: imgArrNow,
                                avatarUrlShow: imgArrNowShow
                            })
                            that.chooseViewShowBanner();
                        },
                        fail: function (err) {
                            console.log(err);
                        },
                    })

                },
                fail: function (res) {
                    // fail
                },
                complete: function (res) {
                    // complete
                }
            })
        } else {
            wx.showToast({
                title: '最多添加4张图片',
                icon: 'none',
                duration: 1500
            })
        }
    },
    /** 删除图片Banner */
    deleteImvBanner: function (e) {
        var avatarUrlShow = this.data.avatarUrlShow;
        var avatarUrl = this.data.avatarUrl;
        var itemIndex = e.currentTarget.dataset.id;
        avatarUrlShow.splice(itemIndex, 1);
        avatarUrl.splice(itemIndex, 1);
        this.setData({
            avatarUrlShow: avatarUrlShow
        })
        //判断是否隐藏选择图片
        this.chooseViewShowBanner();
    },
    /** 是否隐藏图片选择Banner*/
    chooseViewShowBanner: function () {
        if (this.data.avatarUrlShow.length > 3) {
            this.setData({
                chooseViewShowBanner: false
            })
        } else {
            this.setData({
                chooseViewShowBanner: true
            })
        }
    },
    // 选中改变
    changeChecked(e) {
        let index = e.currentTarget.dataset.id;
        let value = '';
        this.data.reasonList.forEach((item, id) => {
            if (id == index) {
                item.checked = true
                value = item.text
            } else {
                item.checked = false
            }
        })
        this.setData({
            reasonList: this.data.reasonList,
            reasonValue: value,
            reasonListChecked: true
            // isShowPannel: false

        })


    },
    /**
     * 获取订单详情
     */
    async getOrderdetail() {
        let _self = this;
        try {
            let orderRes = await order.getOrderDetail({
                orderSn: _self.data.orderSn,
                mobile: cache.getMobile()
            });
            if (orderRes.code == 200 && orderRes.msg == "success") {
                let orderInfo = orderRes.data;
                orderInfo.originPrice = (parseFloat(orderInfo.payPrice) / 100).toFixed(2)
                _self.setData({
                    orderInfo: orderInfo,
                })
                //组建spu sku
                _self.createOrderGoodList(orderInfo.orderGoodsList)
            }
        } catch (error) {
            console.log(error);
        }
    },
    closeCartPannel: function () {
        this.setData({
            isShowPannel: false
        })
    },
    //显示对话框
    showCartPannel: function () {
        // 显示遮罩层
        var animation = wx.createAnimation({
            duration: 100,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
            isShowPannel: true
        })
        setTimeout(function () {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export()
            })
        }.bind(this), 100)
    },

    submit() {
        if (this.data.reasonListChecked) {
            order.refund({
                mobile: cache.getMobile(),
                orderSn: this.data.orderSn,
                reason: this.data.reasonValue + this.data.reasonDetailValue,
                photoList: this.data.avatarUrl
            }).then(res => {
                wx.redirectTo({
                  url: '../../welfareMall/historical/historical',
                })


            })
        }else{
            wx.showToast({
                title: '请选择退款理由',
                icon: 'none',
                duration: 1000
              })
        }



    },
    /**
     * 组建spu sku
     * @param {*} list 
     */
    createOrderGoodList(list) {

        console.log("进入详情")
        console.log(list)
        let _self = this;
        if (list.length == 0) {
            return;
        }
        let orderGoodList = [];
        for (let a = 0; a < list.length; a++) { //最外层
            //某一个商品种类
            let goodList = list[a];
            //sku-list
            let orderGoodsSkuList = goodList.orderGoodsSkuList;
            let fullFigure = list[a].fullFigure;
            for (let b = 0; b < orderGoodsSkuList.length; b++) {
                let orderGood = {};
                orderGood.productName = goodList.productName;
                let orderGoodsSku = orderGoodsSkuList[b];
                let text = '';
                if (orderGoodsSku.comboSkuList != null && orderGoodsSku.comboSkuList.length > 0) {
                    console.log("进入套餐拼接")
                    text = "套餐:"
                    let productName = ''
                    let specValue = []
                    let num = ''
                    orderGoodsSku.comboSkuList.forEach(function (comboSkuList, index) {
                        comboSkuList.skuList.forEach(function (skuList, skuindex) {
                            productName = skuList.productName
                            num = skuList.num
                            if (skuList.specList != null) {
                                let specList = JSON.parse(skuList.specList);
                                if (base.isArray(specList)) {
                                    specList.forEach(function (specList, skuindex) {

                                        specValue.push(specList.specValue + " X" + num)

                                    })
                                }
                            } else {
                                specValue.push(productName + " X" + num)
                            }
                        })
                    })
                    specValue = specValue.join('、') || ""
                    text = text + "(" + specValue + ")"

                }
                orderGood.num = orderGoodsSkuList[b].num;
                orderGood.allFee = base.fenToYuan(orderGoodsSkuList[b].price * orderGoodsSkuList[b].num)
                orderGood.skuText = text
                orderGood.fullFigure = fullFigure
                orderGoodList.push(orderGood)
            }
        }
        _self.setData({
            orderGoodList: orderGoodList
        })

        console.log(this.data.orderGoodList)
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

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

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    showlable() {


    }
})