// pages/water_filter/RechargeRecord/RechargeRecord.js
const app = getApp()
let util = require('../../../../utils/util')
let apiArr = require('../../../../api/water_filter')
let PayJs = require('../../../../api/pay')


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

    /**
     * 页面的初始数据
     */
    data: {
        s: app.system.statusBarHeight, // 状态栏高度
        n: (app.menu.top - app.system.statusBarHeight) * 2 + app.menu.height, // 导航栏高度
        t: app.menu.top, // 胶囊局顶部距离
        h: app.menu.height, // 胶囊高度
        page_num: 1,
        page_size: 10,
        flag: false,
        List: [],
        tab: [
            {
                name: "全部",
                type: "0"
            },
            {
                name: "待分配",
                type: "1"
            },
            {
                name: "待更换",
                type: "2"
            },
            {
                name: "已完成",
                type: "3"
            },
            {
                name: "已取消",
                type: "4"
            }
       
        ],
        state: 0,
        selectPackage: ""
    },

    changeTab(e) {
        console.log(e);
        let that = this
        that.setData({
            state: e.currentTarget.dataset.tab,
            flag: false,
            page_num: 1,
            List: []
        })
        that.getPayList()
    },

    getPayList() {
        wx.showLoading({
          title: '加载中...',
          mask:true
        })
        let that = this
        util.postUrl(apiArr.getFilterChangeList, {
            page_num: that.data.page_num,
            page_size: that.data.page_size,
            status: that.data.state,
            user_id: Number(wx.getStorageSync('userId'))
        }, res => {
            wx.hideLoading()
            if (res.rows) {
                let flag
                if (res.rows.length == that.data.page_size) {
                    flag = true
                } else {
                    flag = false
                }
                res.rows.forEach(item => {
                    console.log(item, 'item');
                    if (item.part_list) {
                        item.part_ids = item.part_list.map(items => items.parts_id).join(',')
                    }
                })
                that.setData({
                    flag,
                    List: that.data.List.concat(res.rows || []),
                    page_num: that.data.page_num + 1
                })
            }
        })
    },

    pay2(e) {
        let that = this
        that.setData({
            selectPackage: e.currentTarget.dataset.item
        })
        that.pay3()
    },

    pay3() {
        let that = this
        util.postUrl(apiArr.createDeviceOrder, {
            customer_name: that.data.selectPackage.customer_name,
            customer_phone: that.data.selectPackage.customer_phone,
            total_price: Number(that.data.selectPackage.total_price),
            parts_ids: that.data.selectPackage.part_ids || that.data.selectPackage.parts_ids,
            device_id: Number(wx.getStorageSync('device_id')),
            region: that.data.selectPackage.region,
            address: that.data.selectPackage.address,
            is_up_door: Number(that.data.selectPackage.is_up_door) || 1,
            user_id: Number(wx.getStorageSync('userId'))

        }, res => {
            that.setData({
                orderMsg: res
            })
            that.getGoodsMsg()
        })
    },

    //获取商户id
    getGoodsMsg() {
        let that = this
        util.postUrl(apiArr.getCurrentShopMsg, {
            dealer_id: Number(that.data.selectPackage.dealer_id),
            shop_id: Number(wx.getStorageSync('shopId')),
        }, res => {
            that.setData({
                goodsMsg: res
            })
            that.pay()
        })
    },
    //预支付
    pay() {
        let that = this
        util.postUrl2(PayJs.pay, {
            address: that.data.orderMsg.Region + that.data.orderMsg.Address,
            goods_id: that.data.orderMsg.order_name,
            remark: "",
            subject: that.data.orderMsg.OrderName,
            term_no: that.data.goodsMsg.term_no,
              total_amount:String(that.data.selectPackage.total_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.OrderNo),
            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);
                    }
                })
            }

        })
    },

    //查询支付结果
    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.OrderNo,

        }, res => {
            if (res.statusCode == '200') {
                wx.showToast({
                    title: '支付成功！',
                })
                that.setData({
                    flag: false,
                    page_num: 1,
                    List: []
                })
                this.getPayList()
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        })
    },

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

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

    },

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

    },

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

    },

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

    },

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

    },

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

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