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

const app = getApp()
import { areaList } from '../../data/index';

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, // 胶囊高度
        checked: true,
        areaList,
        show: false, //弹出层

        name: "",
        phone: "",
        area: "",
        address: "",
        message: "",

        page_num: 1,
        page_size: 10,
        flag: false,
        PartsList: [],
        currentId: [],
        currentName: [],
        price: 0,

        orderMsg: "",//订单信息
        GoodsMsg: "",//商户信息
    },

    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
        })
    },
    ipt4(e) {
        let that = this
        that.setData({
            message: e.detail.value
        })
    },

    onChange(e) {
        console.log(e);
        let that = this
        let PartsList = that.data.PartsList
        let currentId = that.data.currentId
        let currentName = that.data.currentName
        let price = that.data.price
        currentId = []
        currentName = []
        PartsList[e.currentTarget.dataset.idx].checked = !PartsList[e.currentTarget.dataset.idx].checked
        price = 0
        PartsList.forEach(item => {
            if (item.checked) {
                // price += item.unit_price
                price = util.floatCalculate(price, item.unit_price, '+=')
                currentId.push(item.parts_id)
                currentName.push(item.parts_name)
            }
        })
        that.setData({
            PartsList,
            currentId,
            currentName,
            price
        })
    },

    getPartsByid() {
        wx.showLoading({
            title: '加载中...',
        })
        let that = this
        util.postUrl(apiArr.getdeviceListByid, {
            device_id: Number(wx.getStorageSync('device_id')),
            page_num: that.data.page_num,
            page_size: that.data.page_size
        }, res => {
            wx.hideLoading()
            console.log(res, 'resss');
            let flag
            if (res.rows) {
                res.rows.forEach(item => {
                    item.checked = false
                })
                if (res.rows.length == that.data.page_size) {
                    flag = true
                } else {
                    flag = false
                }
                res.rows.forEach(item => {
                    item.parts_icon = util.img_url + item.parts_icon
                })
                that.setData({
                    PartsList: that.data.PartsList.concat(res.rows || []),
                    flag,
                    page_size: that.data.page_size + 1
                })
            }
        })
    },

    createDeriveOrder() {
        let that = this
        if (that.data.currentId.length == 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
        }
        let parts_ids = that.data.currentId.join()

        util.postUrl(apiArr.createDeviceOrder, {
            device_id: Number(wx.getStorageSync('device_id')),
            region: that.data.area,
            address: that.data.address,
            parts_ids,
            total_price: String(that.data.price),
            customer_name: that.data.name,
            customer_phone: that.data.phone,
            user_id: Number(wx.getStorageSync('userId')),
            is_up_door: 1
        }, res => {
            that.setData({
                orderMsg: res
            })
            that.getGoodsMsg()
        })
    },

    //获取商户id
    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

        let parts_ids = that.data.currentId.join()
        let subject = that.data.currentName.join()

        util.postUrl2(PayJs.pay, {
            address: that.data.area + that.data.address,
            goods_id: parts_ids,
            merchant_no: that.data.GoodsMsg.merchant_no,
            out_trade_no: that.data.orderMsg.OrderNo,
            quantity: 1,
            remark: that.data.message,
            subject,
            term_no: that.data.GoodsMsg.term_no,
            total_amount: String(that.data.price * 100),
            user: String(wx.getStorageSync('userId')),
            user_id: wx.getStorageSync('openId')
        }, res => {
            const { resp_data, msg } = res.data.data
            console.log(res, 'ssss');
            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) {
                        if(fal.errMsg == 'requestPayment:fail cancel'){
                            that.payFail(2)
                        }else{
                            that.payFail(1)
                        }
                    }
                })
            }
        })
    },

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


    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 || that.data.orderMsg.OrderNo
        }, res => {
            if (res.statusCode == '200') {
                wx.showToast({
                    title: '支付成功！',
                })
                setTimeout(() => {
                    wx.navigateBack({ delta: 1 })
                }, 800)
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        })
    },


    account() {
        wx.navigateTo({
            url: '../payList/payList',
        })
    },

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

    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
        })
    },
    onShareAppMessage() {
        return {
            title: '人人爱净水',  // 分享卡片标题（必填）
            path: '/pages/water_filter/water_filter',  // 用户点击后跳转的路径（可选，默认当前页）
            imageUrl: (__staticUrl + '/share.png')  // 自定义图片（可选，比例建议 5:4）
        }
    },
    onShareTimeline() {
        return {
            title: '人人爱净水', // 自定义标题
            query: '', // 自定义页面路径中的参数
            imageUrl: (__staticUrl + '/share.png') // 自定义分享图片路径
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.getPartsByid()
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

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

    }
})