let util = require('../../../../utils/util')
let apiArr = require('../../../../api/water_filter')
import { areaList } from '../../data/index';

let PayJs = require('../../../../api/pay')

// pages/water_filter/Recharge/Recharge.js
const __staticUrl = require('../../../../config/env.js').static_url
Page({

    /**
     * 页面的初始数据
     */
    data: {
        name: "",
        phone: "",
        area: "",
        address: "",
        show: false,
        areaList,

        active: 0,
        page_size: 10,
        page_num: 1,
        flag: false,
        packageList: [],
        price: 0,
        selectPackage: {
            discounted_price: 0
        },
        orderMsg: "",
        goodsMsg: "",
        currentDevice: ''
    },
    //充值记录
    RechargeRecord() {
        let that = this
        wx.navigateTo({
            url: '../RechargeRecord/RechargeRecord',
        })
    },
    changelog(e) {
        let that = this
        that.setData({
            active: e.currentTarget.dataset.catlog
        })
    },

    getPackageList() {
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        let that = this
        that.setData({
            currentDevice: wx.getStorageSync('currentDevice')
        })

        util.postUrl(apiArr.getpackageList, {
            device_id: that.data.currentDevice.device_id
        }, res => {
            wx.hideLoading()
            res.package_icon = util.img_url + res.package_icon
            that.setData({
                packageList: res
            })
        })
    },


    onChange(e) {
        let that = this
        let packageList = that.data.packageList
        let selectPackage = that.data.selectPackage

        packageList.checked = e.detail

        if (e.detail) {
            selectPackage.discounted_price = packageList.suggested_price
        } else {
            selectPackage.discounted_price = 0
        }

        that.setData({
            packageList,
            selectPackage
        })
    },

    account2() {
        let that = this
        if (that.data.selectPackage.discounted_price == '0') {
            wx.showToast({
                title: '请选择套餐',
                icon: "none"
            })
            return
        }
        util.postUrl(apiArr.createPackageOrder, {
            device_id: that.data.currentDevice.device_id,
            package_id: that.data.packageList.package_id
        }, res => {

            that.setData({
                orderMsg: res
            })
            that.getGoodsMsg()

        })
    },

    account() {
        let that = this
        console.log(that.data.selectPackage);
        if (that.data.selectPackage.discounted_price == '0') {
            wx.showToast({
                title: '请选择套餐',
                icon: "none"
            })
            return
        }

        if (!that.data.name) {
            wx.showToast({
                title: '请填写收货人',
                icon: "none"
            })
            return
        }
        if (!that.data.phone) {
            wx.showToast({
                title: '请填写收货人电话',
                icon: "none"
            })
            return
        }
        if (!util.isPhone(that.data.phone)) {
            wx.showToast({
                title: '请填写正确电话',
                icon: "none"
            })
            return
        }
        if (!that.data.area) {
            wx.showToast({
                title: '请选择所在地区',
                icon: "none"
            })
            return
        }
        if (!that.data.address) {
            wx.showToast({
                title: '请填写详情地址',
                icon: "none"
            })
            return
        }
        util.postUrl(apiArr.createPackageOrder, {
            billing_method: Number(that.data.packageList.package_type),
            is_new: 1,
            order_name: that.data.packageList.package_name,
            total_price: Number(that.data.packageList.suggested_price),
            package_id: that.data.packageList.package_id,
            device_customer_name: that.data.name,
            device_customer_phone: that.data.phone,
            device_customer_addr: that.data.area + that.data.address,
            user_id: Number(wx.getStorageSync('userId'))
        }, res => {
            console.log(res, '1123213');
            that.setData({
                orderMsg: res
            })
            that.getGoodsMsg()
        })
    },
    //获取商户id
    getGoodsMsg() {
        let that = this
        util.postUrl(apiArr.getCurrentShopMsg, {
            dealer_id: Number(that.data.packageList.dealer_id),
            user_id: Number(wx.getStorageSync('userId')),
            shop_id: Number(wx.getStorageSync('shopId')),
        }, res => {
            that.setData({
                goodsMsg: res
            })
            that.pay()
        })
    },
    //预支付
    pay() {
        let that = this
        util.postUrl2(PayJs.pay, {
            address: that.data.area + that.data.address,
            goods_id: that.data.orderMsg.order_id,
            remark: "",
            subject: that.data.orderMsg.order_name,
            term_no: that.data.goodsMsg.term_no,
            total_amount: String(that.data.packageList.suggested_price * 100),
            // total_amount:String(1),
            user: String(wx.getStorageSync('userId')),
            merchant_no: that.data.goodsMsg.merchant_no,
            out_trade_no: String(that.data.orderMsg.order_no),
            user_id: wx.getStorageSync('openId')
        }, res => {
            const { resp_data, msg } = res.data.data
            if (msg == '成功') {
                wx.requestPayment({
                    timeStamp: String(resp_data.acc_resp_fields.time_stamp),
                    nonceStr: String(resp_data.acc_resp_fields.nonce_str),
                    package: String(resp_data.acc_resp_fields.package),
                    signType: String(resp_data.acc_resp_fields.sign_type),
                    paySign: String(resp_data.acc_resp_fields.pay_sign),
                    success(res) {
                        that.queryPay()
                    },
                    fail(fal) {
                        console.log(fal.errMsg);
                        if(fal.errMsg == 'requestPayment:fail cancel'){
                            that.payFail(2)
                        }else{
                            that.payFail(1)
                        }
                    }
                })
            }

        })
    },

    //查询支付结果
    queryPay() {
        let that = this
        util.postUrl2(PayJs.queryPay, {
            merchant_no: that.data.goodsMsg.merchant_no,
            term_no: that.data.goodsMsg.term_no,
            out_trade_no: that.data.orderMsg.order_no
        }, res => {
            if (res.statusCode == '200') {
                wx.showToast({
                    title: '支付成功！',
                })

                // wx.requestSubscribeMessage({
                //     tmplIds: ["2BX7Zh5ccLzmHvvbCHuPWiaoZQyDCGfziCruxUct_EU"],
                //     success(res) {
                //         if (res['2BX7Zh5ccLzmHvvbCHuPWiaoZQyDCGfziCruxUct_EU'] === 'accept') {
                //             console.log('用户同意订阅');
                //             // 调用后端接口保存用户订阅状态
                //         }
                //     },
                // })

                setTimeout(() => {
                    wx.navigateBack({
                        delta: 1
                    })
                }, 1500)

            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        })
    },

    payFail(e){
        let that = this
        util.postUrl(PayJs.payFail,{
            order_id:that.data.orderMsg.order_id,
            type:"2",
            state:e,
        },res=>{
            console.log(res);
        })
    },

    changeShow() {
        let that = this
        that.setData({
            show: true
        })

    },
    //选择地区
    AreaConfirm(e) {
        let that = this

        let area = ''
        if (e.detail.values[0].name == e.detail.values[1].name) {
            area = e.detail.values[1].name + e.detail.values[2].name
        } else {
            area = e.detail.values[0].name + e.detail.values[1].name + e.detail.values[2].name
        }

        that.setData({
            show: false,
            area
        })


    },
    //取消
    cancel(e) {
        let that = this
        that.setData({
            show: false
        })
    },

    ipt1(e) {
        let that = this
        that.setData({
            name: e.detail.value
        })
    },
    ipt2(e) {
        let that = this
        that.setData({
            phone: e.detail.value
        })
    },
    ipt3(e) {
        let that = this
        that.setData({
            address: e.detail.value
        })
    },

    onShareTimeline() {
        return {
            title: '人人爱净水', // 自定义标题
            query: '', // 自定义页面路径中的参数
            imageUrl: (__staticUrl + '/share.png') // 自定义分享图片路径
        }
    },
    onShareAppMessage() {
        return {
            title: '人人爱净水',  // 分享卡片标题（必填）
            path: '/pages/water_filter/water_filter',  // 用户点击后跳转的路径（可选，默认当前页）
            imageUrl: (__staticUrl + '/share.png')  // 自定义图片（可选，比例建议 5:4）
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.setData({
            phone: wx.getStorageSync('phone')
        })
        that.getPackageList()
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

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

    },

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

    },

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

    },

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

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        let that = this
        if (that.data.flag) {
            that.getPackageList()
        }
    },

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

    }
})