// pages/order/confirmOreder/confirmOreder.js
const app = getApp();
const addr = require('../../my/address/addSite/addSite.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isonline: 1,
        currentList: [],
        mode: 1,
        checked: true,
        show1: false,
        show2: false,
        code: "",
        order_no: "",
        orderinfo: "",
        address: "",
        useraddr: "",
        remark: "",
        address_id:0,
        freight:0,
        total_price:0,
        isphone: false,
        isphonenum: false,
        phonenum: '',
        couponinfo: ''
    },
    onLoad(opticon) {
        let order_no = opticon.order_no;
        this.detail(order_no);
        this.setData({
            order_no
        })

    },
    onShow(){
        this.setData({couponinfo: this.data.citem})
        if(this.data.couponinfo){
            if(this.data.couponinfo.type==1){
                if((parseFloat(this.data.freight)-parseFloat(this.data.couponinfo.money))>0){
                    this.setData({total_price: (parseFloat(this.data.total_price) - parseFloat(this.data.couponinfo.money)).toFixed(2)})
                }else{
                    this.setData({total_price: (parseFloat(this.data.total_price) - parseFloat(this.data.freight)).toFixed(2)})
                }
            }else if(this.data.couponinfo.type==2){
                if((parseFloat(this.data.total_price) - parseFloat(this.data.couponinfo.money))>0){
                    this.setData({total_price: (parseFloat(this.data.total_price) - parseFloat(this.data.couponinfo.money)).toFixed(2)})
                }else{
                    this.setData({total_price: 0})
                }
            }
        }
    },
    goyhq(){
        if(this.data.couponinfo){
            this.setData({
                total_price: parseFloat(parseFloat(this.data.total_price) + parseFloat(this.data.couponinfo.money)).toFixed(2)
            })
        }
        console.log(this.data.total_price)
        wx.navigateTo({
          url: '../coupon/coupon?totalprice='+this.data.total_price+'&freight='+this.data.freight,
        })
    },
    changeisphone(){
        this.setData({isphone: !this.data.isphone})
    },
    //详情
    detail(order) {
        var that = this;
        app.api.useApi(app.globalData.baseAppUrl + "api/order_detail", {
            order_no: order,
        }, "get").then(function (res) {
            if (res.code != 200) {
                wx.showLoading({
                    title: res.message.msg,
                })
                setTimeout(function () {
                    wx.hideLoading({
                        success: (res) => { },
                    })
                }, 2000);

            } else {
                that.setData({isonline: res.is_online})
                if(res.message.address!=' '&&res.message.address!=''){
                    console.log('不为空')
                    that.setData({isphone: false})
                }else{
                    that.setData({isphonenum: true,isphone:true})
                }
                var unit=res.message.data.network.unit[res.message.data.network.unit.length-1];

                var total_price=parseFloat(res.message.data.total_price);
                var price=parseFloat(unit.price);
                that.setData({
                    orderinfo: res.message.data,
                    address: res.message.address.address,
                    code: res.message.address.phone,
                    name: res.message.address.username,
                    address_id:res.message.address.id,
                    useraddr: res.message.address,
                    mode:unit.type,
                    order_type:unit.type,
                    freight:unit.price,
                    total_price:(total_price+price).toFixed(2),
                    currentList: res.message.data.services
                })
                let currentList = that.data.currentList
                currentList.map(item => {
                    item.active = false
                })
            }

        }).catch(function (err) {
            console.log(err);
        })
    },
    changeClose1(e) {
        this.setData({
            show1: !this.data.show1
        })
    },

    changeClose2(e) {
        // console.log(e)
        this.setData({
            show2: !this.data.show2,
            remark: this.data.remark
        })

    },
    onChange(event) {
        console.log(event);
        this.setData({
            checked: event.detail,
        });
    },
    chios(e) {
        let that = this
        let { item } = e.currentTarget.dataset

        let currentList = that.data.currentList
        currentList.map((it, index) => {
            if (item.id == it.id) {
                // it.active = !it.active
                if(it.active){
                    it.active = false
                    that.setData({total_price: (parseFloat(that.data.total_price) + parseFloat((it.price.start_time && it.price.end_time)?it.price.sale_price*it.stock:it.price.price*it.stock)).toFixed(2)})
                }else{
                    it.active = true
                    that.setData({total_price: (parseFloat(that.data.total_price) - parseFloat((it.price.start_time && it.price.end_time)?it.price.sale_price*it.stock:it.price.price*it.stock)).toFixed(2)})
                }
            }
        })
        that.setData({
            currentList
        })
        // total_price
    },
    changeMode(e) {
        var id = e.currentTarget.dataset.id
        var key=e.currentTarget.dataset.indx;
        var unit=this.data.orderinfo.network.unit[key];

        
        var total_price=parseFloat(this.data.total_price)
        var price=parseFloat(unit.price)
        console.log(total_price,price)
        this.setData({
            mode: id,
            freight:unit.price,
            total_price:parseFloat(total_price+price).toFixed(2)
    
        })
    },

    goto() {
        let that = this
        if(!that.data.checked){
            wx.showLoading({
                title: '请阅读并同意洗护协议',
            })
            setTimeout(function () {
                wx.hideLoading({
                    success: (res) => { },
                })
            }, 1000);
        }else{
            wx.requestSubscribeMessage({
                tmplIds: ['VGlAo-fOukIVSjdmOS5_-9IldrNplzrbKzZzWI2rFuc'],
                success (res) {
                    console.log('成功-'+res);
                    console.log(res)
                    that.orderConfirm();
                }
            })
        }
        
    },
    getPhoneNumber(e) {
        app.login();
        console.log(e)

        let that = this
        var data = {
            'mds': wx.getStorageSync('seisson_key'),
            'encryptedData': e.detail.encryptedData,
            'errMsg': e.detail.errMsg,
            'iv': e.detail.iv,
            'appid':wx.getAccountInfoSync().miniProgram.appId,
        }

        app.api.useApi(app.globalData.baseAppUrl+"api/user/getPhoneNumber",data,"post").then((res)=>{
            if (res.code == 200) {
                var phone = res.message.data.phone
                console.log(phone);
                if (phone) {
                    if(that.data.isphonenum){
                        that.setData({
                            code: phone,
                        })
                    }
                    that.changeisphone()
                }
            }
        }).catch((err)=>{
            console.log(err)
        })

        // console.log("fetch cloudfunction success", cloudResult.result)




    },
    input1(e) {
        console.log(e.detail);
        this.setData({
            name: e.detail.value
        })
    },
    input2(e) {
        this.setData({
            code: e.detail.value
        })
    },
    input3(e) {
        this.setData({
            address: e.detail.value
        })
    },
    input4(e) {
        this.setData({
            remark: e.detail.value
        })

    },
    addAddress() {
        var that = this;
        app.api.useApi(app.globalData.baseAppUrl + "api/address/create", {
            username: that.data.name,
            phone: that.data.code,
            address: that.data.address,

        }, "post").then(function (res) {
          
            if (res.code != 200) {
                wx.showLoading({
                    title: res.original.message.msg,
                })
                setTimeout(function () {
                    wx.hideLoading({
                        success: (res) => { },
                    })
                }, 1000);
            } else {
                that.changeClose1();
                that.setData({
                    address_id: res.message.data.address.id,
                })
            }
           
        }).catch(function (err) {
            console.log(err);
        })
    },
    updateaddr(e) {
        var that = this;
        app.api.useApi(app.globalData.baseAppUrl + "api/address/update", {
            username: that.data.name,
            phone: that.data.code,
            address: that.data.address,
            id: e.target.dataset.id,
        }, "post").then(function (res) {
          
            if (res.code != 200) { 
                wx.showLoading({
                    title: res.message.msg,
                })
            } else {
                that.changeClose1();
                // wx.navigateTo({
                //     url: '/pages/my/address/address',
                // })
            }
            setTimeout(function () {
                wx.hideLoading({
                    success: (res) => { },
                })
            }, 2000);


        }).catch(function (err) {
            console.log(err.message);
        })
    },
    orderConfirm() {
        var that=this;
        let cid = 0
        if(that.data.couponinfo!=''&&that.data.couponinfo!=undefined){
            cid = that.data.couponinfo.pivot.id
        }
        let services = []
        that.data.currentList.forEach((item,index)=>{
            if(item.active){
                services.push({
                    id: item.id,
                    price: parseFloat((item.price.start_time && item.price.end_time)?item.price.sale_price*item.stock:item.price.price*item.stock).toFixed(2),
                    price_id: item.price.id,
                    stock: item.stock
                })
            }
        })
        app.api.useApi(app.globalData.baseAppUrl + "api/orders", {
            order_no: that.data.order_no,
            order_type: that.data.mode,
            user_remark: that.data.remark,
            address_id:that.data.address_id,
            coupon_id: cid,
            services: services
        }, "post").then(function (res) {
            console.log(res)
            if (res.code != 200) {
                wx.showLoading({
                    title: res.message.msg,
                })
                if(res.code == 1020){
                    // that.changeisphone()
                    that.changeClose1()
                }
                setTimeout(function () {
                    wx.hideLoading({
                        success: (res) => { },
                    })
                }, 1000);

            } else {

                wx.navigateTo({
                    url: '/pages/my/cashier/cashier?order_no='+that.data.order_no
                })
            }


        }).catch(function (err) {
            // console.log(222);
            console.log(err)
        })
    },



})