const Parse = getApp().Parse;
const company = getApp().globalData.company
const req = require('../../../utils/request')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        length: 0,
        earnings: 0,
        list: [{
            'num': '提现到银行卡'
        }],
        idx: null,
        name: null,
        price: null,
        checked: true,
        merchant: null,
        names: null,
        bankName: null,
        accountId: null,
        activeColor: getApp().globalData.activeColor,
        titleColor: getApp().globalData.titleColor,
        times:null,
        minCount:null,
        bankList: [],
        bank_index:null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad:async function (options) {
        let earnings = options.earnings
        let merchant = wx.getStorageSync('merchant'); //用户
        this.setData({
            earnings: earnings,
            merchant: merchant.objectId
        })
        let d = new Date();
        this.date = d
        let data = new Date(d.getFullYear(), d.getMonth() + 1, 0);
        let day = data.getDate();
        let year = d.getFullYear()
        let month = d.getMonth() + 1 > 9 ? d.getMonth() + 1 : "0" + (d.getMonth() + 1)
        //  当前月份的 第一天 和最后一天
        let startTime = year + "-" +  month + "-" + "01" + " 00:00:00"
        let endTime = year + "-" + month + "-" + day + " 23:59:57"
        await this.getSeeting()
        await this.getTotal(startTime, endTime)
        // await this.getBank()
    },

    async getSeeting() {
        let sql = `select "value" from "Setting" where "oid" = '${company}' and "key" = 'store-withdraw' and "type" = 'company'`
        let setting = await req.customSQL(sql)
        if(setting && setting.length > 0) {
            console.log(setting)
            if(setting[0] && setting[0].value ) {
                this.setData({
                    times: setting[0].value.times?   setting[0].value.times : null,
                    minCount: setting[0].value.minCount?   setting[0].value.minCount : null
                })
            }
        }
        
    },

    async getBank() {
        let user = Parse.User.current()
        let Account = new Parse.Query('Account')
        Account.equalTo('company', company)
        Account.equalTo('user',user)
        Account.select('bank')
        let account = await Account.first()
        if(account && account.id) {
            this.setData({
                bankList: account.get('bank') ? account.get('bank') : []
            })
        }
    },

    onChangBank(e) {
        let {
            index, item
        } = e.currentTarget.dataset
      
        this.setData({
            bank_index: index,
            names: item.name,
            accountId:item.cardId,
            bankName: item.bankName

        })
    },
        

    async getUserAgentWithdraw() {
        let store = wx.getStorageSync("store");
        if (store == "") {
            wx.redirectTo({
                url: '/nova-bzzb/pages/my/login/index'
            });
            return;
        }
        let uid = store.user.objectId
        if (this.data.times && this.data.length >= this.data.times) {
            wx.showToast({
                title: '您本月的提现次数已到上限',
                icon: 'none',

            });
            return;
        }
        if (this.data.minCount && this.data.minCount >  Number(this.data.price)) {
            wx.showToast({
                title: '提现金额小于最小提现金额',
                icon: 'none',
            });
            return
        }
        if (!this.data.price) {
            wx.showToast({
                title: '请输入提现金额',
                icon: 'none',
            });
            return
        }
        if (Number(this.data.price) > Number(this.data.earnings)) {
            wx.showToast({
                title: '您输入的金额超过了您的可提现金额',
                icon: 'none',
            });
            return
        }
        if (!this.data.name) {
            wx.showToast({
                title: '请选择提现方式',
                icon: 'none',
            });
            return
        }
        if (!this.data.names || !this.data.bankName || !this.data.accountId) {
            wx.showToast({
                title: '请输入完整银行卡信息',
                icon: 'none',
            });
            return
        }
        let UserAgentWithdraw = Parse.Object.extend("UserAgentWithdraw")
        let userAgentWithdraw = new UserAgentWithdraw()
        userAgentWithdraw.set("count", Number(this.data.price))
        userAgentWithdraw.set("type", "bank")
        userAgentWithdraw.set("isVerified", false)
        userAgentWithdraw.set("name", store.storeName)
        userAgentWithdraw.set("company", {
            __type: 'Pointer',
            className: 'Company',
            objectId: company
        })
        userAgentWithdraw.set("user", {
            __type: 'Pointer',
            className: '_User',
            objectId: uid
        })
        userAgentWithdraw.set("info", [{
            name: this.data.names,
            accountId: this.data.accountId,
            bankName: this.data.bankName
        }])
        userAgentWithdraw.set("bank", {
            name: this.data.names,
            accountId: this.data.accountId,
            bankName: this.data.bankName
        })
        userAgentWithdraw.set("channel", "shopStore")
        userAgentWithdraw.save().then(res => {
            if(res && res.id) {
                wx.showToast({
                    title: '提现成功',
                    icon: 'none',
                });
                setTimeout(()=> {
                    wx.navigateBack({
                        delta: 1
                    })
                },500)
            }
        })
    },

    bindBank() {
        wx.navigateTo({
            url: `/common-page/pages/info/bindBank/index`,
        })
    },

    goIndex(e) {
        let index = e.currentTarget.dataset.index;
        let name = e.currentTarget.dataset.item.num
        if (index == this.data.idx) {
            this.setData({
                idx: null,
                name: null
            })
        } else {
            this.setData({
                idx: index,
                name: name
            })
        }
    },
    // 输入框失去焦点 触发事件
    blur(e) {
        let name = e.currentTarget.dataset.name
        this.setData({
            [name]: e.detail.value
        })
    },
    // 
    async getTotal(startTime, endTime) {
        let UserAgentWithdraw = new Parse.Query('UserAgentWithdraw')
        UserAgentWithdraw.equalTo('user', this.data.merchant)
        UserAgentWithdraw.equalTo('type', 'bank')
        UserAgentWithdraw.greaterThan('createdAt', startTime)
        UserAgentWithdraw.lessThan('createdAt', endTime)
        let userAgentWithdraw = await UserAgentWithdraw.find()
        let length
        if (userAgentWithdraw) {
            console.log(userAgentWithdraw.length);
            length = userAgentWithdraw.length
        }
        this.setData({
            length: length
        })
        console.log(this.data.length);
    },

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

    },

    /**
     * 生命周期函数--监听页面显示
     */
     onShow: async function () {
        await this.getBank()
    },

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

    },

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

    },

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

    },

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

    },

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

    }
})