const _Http = getApp().globalData.http,
    {
        formatTime
    } = require("../../utils/getTime");
let pageNumber = 1,
    pageTotal = 1,
    sys_payorderid = null,
    currency = require("../../utils/currency"),
    CNY = value => currency(value, {
        symbol: "￥",
        precision: 2
    }).format();
Page({
    data: {
        users: [],
        remarks: "",
        showAmount: "￥0.00",
        isDelete: true,
        useDiscount: 0
    },
    onLoad(options) {
        this.setData({
            sys_payinstructions: wx.getStorageSync('siteP').sys_payinstructions,
            sys_payincidence: 1,
            opUsers: options.users ? JSON.parse(options.users) : []
        })
        sys_payorderid = options.sys_payorderid;
        this.getVersions(options.vid || "");
        this.getDiscounts();
    },
    /* 获取优惠卷 */
    getDiscounts() {
        _Http.basic({
            "id": 20230801162402,
            "content": {
                nocache: true
            }
        }).then(res => {
            console.log("获取优惠卷", res)
            this.setData({
                discounts: res.data
            })
        })
    },
    /* 保存订单进度 */
    changeOrder() {
        _Http.basic({
            "classname": "system.payorder.payorder",
            "method": "insertUsers",
            "content": {
                "sys_site_systempartitionid": this.data.sys_site_systempartitionid,
                sys_payorderid,
                "remarks": this.data.remarks,
                "users": this.data.users.map(v => {
                    let item = this.data.userList.find(s => {
                        let id = this.data.sys_payincidence == 1 ? s.userid : s.sa_agentsid;
                        return id == v
                    })
                    return {
                        "isleader": item.isleader,
                        "userid": item.userid,
                        "sa_agentsid": item.sa_agentsid,
                        "enddate": item.enddate[this.data.sys_site_systempartitionid] || ''
                    }
                })
            }
        }).then(res => {
            console.log("修改订单信息", res)
            if (res.msg != '成功') return wx.showToast({
                title: res.msg,
                icon: "none",
                mask: true
            });
            this.setData({
                showAmount: CNY(res.data.amount),
                orderno: res.data.orderno
            })
        })
    },
    /* 更改备注 */
    onblur(e) {
        console.log(e)
        if (e.detail.value == this.data.remarks) return;
        this.setData({
            remarks: e.detail.value
        });
        this.changeOrder();
    },
    /* 获取版本 */
    getVersions(vid) {
        _Http.basic({
            "classname": "system.payorder.payorder",
            "method": "chooseSystemPartition",
            "content": {
                "pageNumber": 1,
                "pageSize": 9999,
                "where": {
                    "condition": ""
                }
            }
        }).then(res => {
            console.log("版本列表", res)
            if (res.msg != '成功') {
                wx.showToast({
                    title: res.msg,
                    icon: "none",
                    mask: true
                })
                setTimeout(() => {
                    wx.navigateBack();
                }, 1000)
                return;
            };
            let sys_site_systempartitionid = res.data[0].sys_site_systempartitionid || '';
            if (vid && res.data.some(v => v.sys_site_systempartitionid == vid)) sys_site_systempartitionid = vid - 0;
            this.setData({
                versionsList: res.data,
                sys_site_systempartitionid
            })
            this.getUsers(true);
        })
    },
    /* 切换版本 */
    changeVer(e) {
        const {
            sys_site_systempartitionid
        } = e.currentTarget.dataset.item;
        if (this.data.sys_site_systempartitionid == sys_site_systempartitionid) return;
        this.setData({
            sys_site_systempartitionid
        });
        this.setUsers();
    },
    checkVer(e) {
        const {
            item
        } = e.currentTarget.dataset;
        this.selectComponent("#inventory").show(item.systemapp)
    },
    /* 获取可添加账号/主体 */
    getUsers(init = false) {
        if (init) {
            pageNumber = 1;
            pageTotal = 1;
        };
        if (pageNumber > pageTotal) return;
        _Http.basic({
            "classname": "system.payorder.payorder",
            "method": "chooseUsers",
            "content": {
                pageNumber,
                "pageSize": 99999,
                "where": {
                    "condition": ""
                }
            }
        }).then(res => {
            console.log("用户列表", res)
            if (res.msg != '成功') {
                wx.showToast({
                    title: res.msg,
                    icon: "none",
                    mask: true
                })
                setTimeout(() => {
                    wx.navigateBack();
                }, 1000)
                return;
            };
            pageTotal = res.pageTotal;
            if (res.data.some(v => v.isleader == 1)) {
                this.setData({
                    userList: res.pageNumber == 1 ? res.data : this.data.userList.concat(res.data)
                })
                pageNumber = res.pageNumber + 1;
                this.setUsers(this.data.opUsers.filter(id => this.data.userList.some(v => id == v.userid)));
            } else {
                wx.showModal({
                    title: '提示',
                    content: "您的团队缺少主账号无法使用，请联系客服！",
                    showCancel: false,
                    complete: (res) => {
                        if (res.confirm) {
                            wx.navigateBack()
                        }
                    }
                })
            }
        })
    },
    setUsers(users = []) {
        let list = this.data.userList,
            idname = this.data.sys_payincidence == 1 ? 'userid' : 'sa_agentsid',
            useDiscount = 0;
        list.forEach(v => {
            let date = v.enddate[this.data.sys_site_systempartitionid];
            if (v.userid == wx.getStorageSync('userMsg').userid || v.isleader == 1) {
                if (date) {
                    // if (formatTime(new Date(), '-').split(" ")[0] >= date) users.push(v[idname] + '');
                } else {
                    if (!users.some(v => v == v[idname])) users.push(v[idname] + '');
                }
            }
            if (users.some(id => id == v.userid) && v.isleader == 0) useDiscount += 1
        });
        this.setData({
            users,
            useDiscount
        });
        this.changeOrder();
    },
    onReachBottom() {
        // this.getUsers();
    },
    onChange(e) {
        const {
            id,
            isleader
        } = e.currentTarget.dataset;
        let users = this.data.users,
            useDiscount = this.data.useDiscount;
        if (users.some(v => v == id)) {
            users = users.filter(s => s != id)
            if (isleader == 0) useDiscount -= 1;
        } else {
            users.push(id + "")
            if (isleader == 0) useDiscount += 1;
        }
        this.setData({
            users,
            useDiscount
        });
        this.changeOrder();
    },
    examine() {
        return new Promise((resolve, reject) => {
            if (currency(this.data.showAmount).value == 0) {
                wx.showModal({
                    title: '提示',
                    content: '优惠后金额为0，是否确认',
                    complete: (res) => {
                        if (res.cancel) resolve(false)
                        if (res.confirm) resolve(true)
                    }
                })
            } else {
                resolve(true)
            }
        })
    },
    isRenew() {
        return new Promise((resolve, reject) => {
            const idname = this.data.sys_payincidence == 1 ? 'userid' : 'sa_agentsid',
                renew = this.data.users.map(v => this.data.userList.find(s => s[idname] == v)).filter(v => v.enddate[this.data.sys_site_systempartitionid]).map(v => v[this.data.sys_payincidence == 1 ? 'name' : 'agentname']).join(',');
            if (renew) {
                wx.showModal({
                    title: '提示',
                    content: `${renew}还未到期，是否继续付费`,
                    confirmText: "继续付费",
                    complete: (res) => {
                        if (res.cancel) resolve(false)
                        if (res.confirm) resolve(true)
                    }
                })
            } else {
                resolve(true)
            }
        })
    },
    /* 支付 */
    async payment() {
        let isRenew = await this.isRenew();
        if (!isRenew) return;
        let isPayment = await this.examine();
        if (!isPayment) return;
        let that = this;
        that.data.isDelete = false;
        wx.login({
            success: (s) => {
                _Http.basic({
                    "classname": "system.payment.wechatpay",
                    "method": "createWechatOrder",
                    "content": {
                        "orderno": that.data.orderno,
                        "wechat_code": s.code,
                        "trade_type": "JSAPI"
                    }
                }).then(res => {
                    if (res.data == '失败') return wx.showToast({
                        title: res.msg,
                        icon: "none",
                        mask: true
                    });
                    wx.requestPayment({
                        timeStamp: res.data.timeStamp,
                        nonceStr: res.data.nonceStr,
                        package: res.data.package,
                        signType: res.data.signType,
                        paySign: res.data.paySign,
                        success() {
                            wx.showToast({
                                title: '支付成功',
                                mask: true
                            })
                        },
                        fail(err) {
                            if (res.msg == '成功' && currency(that.data.showAmount).value == 0) {
                                wx.showToast({
                                    title: '支付成功',
                                    mask: true
                                })
                            } else {
                                wx.showToast({
                                    title: '支付失败',
                                    icon: "error",
                                    mask: true
                                })
                                console.error(err)
                            }
                        },
                        complete(e) {
                            console.log(e)
                            setTimeout(() => {
                                wx.redirectTo({
                                    url: '/pages/teams/order?id=' + sys_payorderid,
                                })
                            }, 1000)
                        }
                    })
                })
            },
        })

    },
    onUnload() {
        if (this.data.isDelete) _Http.basic({
            "classname": "system.payorder.payorder",
            "method": "delete",
            "content": {
                sys_payorderid
            }
        }).then(res => {
            console.log("删除订单", res)
        })
    }
})