let util = require('/../../utils/util')
let apiArr = require('../../api/water_filter')
let PayJs = require('../../api/pay')

const app = getApp()
// pages/water_filter/filter/filter.js
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, // 胶囊高度
        filterList: [],
        show: false,
        currentFilter: "",
        currentDevice: '',
        sucessMsg: "",
        Info: "",
    },

    getfilterList() {
        wx.showLoading({
            title: '加载中...',
        })
        let that = this
        util.headerStorage(that, 'currentDevice', that.data.currentDevice)
        util.postUrl(apiArr.getFilterListByid, {
            device_id: wx.getStorageSync('device_id')
        }, res => {
            wx.hideLoading()
            console.log(res, ';ssssss');
            that.setData({
                filterList: res.list
            })
        })
    },

    getFilterInfo(e) {
        let that = this
        util.postUrl(apiArr.deviceInfo, {
            device_id: e
        }, res => {
            that.setData({
                Info: res
            })
        })
    },

    showDesc(e) {
        let that = this
        that.setData({
            show: !that.data.show,
            currentFilter: e.currentTarget.dataset.item
        })
        that.getFilterInfo(e.currentTarget.dataset.item.device_id)
    },

    pay2() {
        let that = this
        util.postUrl(apiArr.createDeviceOrder, {
            device_id: Number(wx.getStorageSync('device_id')),
            region: that.data.currentFilter.region,
            address: that.data.currentFilter.address,
            parts_ids: String(that.data.currentFilter.parts_id),
            total_price: that.data.currentFilter.unit_price,
            remark: "",
            customer_name: String(that.data.Info.customer_name),
            customer_phone: String(that.data.Info.customer_phone),
            user_id: Number(wx.getStorageSync('userId')),

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

    getGoodsMsg() {
        let that = this
        util.postUrl(apiArr.getCurrentShopMsg, {
            dealer_id: Number(that.data.orderMsg.DealerId),
            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.currentFilter.address,
            goods_id: String(that.data.orderMsg.DealerId),
            merchant_no: that.data.GoodsMsg.merchant_no,
            out_trade_no: that.data.orderMsg.OrderNo,
            quantity: 1,
            remark: that.data.message,
            subject: that.data.currentFilter.parts_name,
            term_no: that.data.GoodsMsg.term_no,
            total_amount:String(that.data.currentFilter.unit_price * 100), 
            // total_amount: String(1),
            user: String(wx.getStorageSync('userId')),
            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.order_no

            merchant_no: that.data.GoodsMsg.merchant_no,
            term_no: that.data.GoodsMsg.term_no,
            out_trade_no: that.data.orderMsg.OrderNo
        }, res => {
            console.log(res);
            if (res.statusCode == '200') {
                wx.showToast({
                    title: '支付成功！',
                })
                that.getfilterList()
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        })
    },

    //变更订单状态
    changeOrderState() {
        wx.showLoading({
            title: '查询中...',
        })
        let that = this
        util.postUrl(apiArr.changeOrderState, {
            merchant_no: that.data.GoodsMsg.merchant_no,
            out_trade_no: that.data.sucessMsg.out_trade_no,
            payer_amount: that.data.sucessMsg.payer_amount,
            total_amount: that.data.sucessMsg.total_amount,
            trade_status: that.data.sucessMsg.trade_state,
            trade_time: that.data.sucessMsg.trade_time
        }, res => {
            wx.hideLoading()
            setTimeout(() => {
                that.getfilterList()
            }, 1500)
        })
    },

    onClose() {
        let that = this
        that.setData({
            show: false
        })
    },

    handleNavigateBack() {
        wx.navigateBack({ delta: 1 })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },

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

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let that = this
        that.getfilterList()
    },

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

    },

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

    },

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

    },

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

    },

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