const app = getApp()
import WxValidate from '../../utils/wxValidate'
const moment = require("../../utils/moment.min")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        frameStyle: { useTop: true, name: '组队申请', leftArrow: true, useBar: false },
        searchInfo: {},
        form: {},
        teammateList: [],
        id: '',
        // 用户信息
        userinfo: {}
    },
    initValidate() {
        const rules = { teammate_id: { required: true }, teammate_name: { required: true } }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = { teammate_id: { required: '请输入组队用户', }, teammate_name: { required: '请输入组队用户姓名', } };
        this.WxValidate = new WxValidate(rules, messages)
    },
    // 跳转菜单
    back(e) {
        wx.navigateBack({ delta: 1 })
    },
    // 查询
    toSearch: function (e) {
        const that = this;
        that.setData({ 'searchInfo.name': e.detail.value });
        that.watchLogin()
    },
    // 选择组队用户
    toChoose: function (e) {
        const that = this;
        const { item } = e.currentTarget.dataset;
        let form = { teammate_id: item.openid, teammate_name: item.name }
        wx.showModal({
            title: '提示',
            content: '是否确认选择该名队员？可先与对方电话联系！',
            success(res) {
                if (res.confirm) {
                    that.onSubmit(form)
                } else if (res.cancel) {
                    that.setData({ form: {} });
                }
            }
        });
    },
    // 提交登录
    onSubmit: async function (e) {
        const that = this;
        const params = e;
        const data = that.data.form;
        params.match_id = data.match_id;
        params.grouping_id = data.grouping_id;
        params.project_id = data.project_id;
        params.applyuser_id = that.data.userinfo.openid;
        params.applyuser_name = that.data.userinfo.name;
        params.apply_time = moment().format('YYYY-MM-DD HH:mm:ss');
        if (!this.WxValidate.checkForm(params)) {
            const error = this.WxValidate.errorList[0];
            wx.showToast({ title: `${error.msg}`, icon: 'error', duration: 2000 })
            return false
        } else {
            let arr;
            arr = await app.$post(`/newCourt/api/teamApply`, params);
            if (arr.errcode == '0') { wx.showToast({ title: `添加信息完成`, icon: 'success', duration: 2000 }); that.back(); }
            else wx.showToast({ title: `${arr.errmsg}`, icon: 'error', duration: 2000 })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const that = this;
        if (options && options.id) that.setData({ id: options.id })
        //验证规则函数
        that.initValidate();
        // 监听用户是否登录
        that.watchLogin();
    },
    // 监听用户是否登录
    watchLogin: async function () {
        const that = this;
        let searchInfo = that.data.searchInfo;
        wx.getStorage({
            key: 'user',
            success: async res => {
                const arr = await app.$get(`/newCourt/api/enroll/${that.data.id}`);
                if (arr.errcode == '0') {
                    that.setData({ form: arr.data });
                    that.setData({ userinfo: res.data });
                }
                let info = {};
                if (searchInfo && searchInfo.name) {
                    info.name = searchInfo.name;
                    info.match_id = that.data.form.match_id;
                    info.grouping_id = that.data.form.grouping_id;
                    info.project_id = that.data.form.project_id;
                    const team = await app.$get(`/newCourt/api/enroll/findTeammate`, { ...info });
                    if (team.errcode == '0') {
                        that.setData({ teammateList: team.data })
                    } else {
                        wx.showToast({ title: `${team.errMsg}`, icon: 'fail', duration: 2000 });
                    }
                } else {
                    let info = {};
                    info.match_id = that.data.form.match_id;
                    info.grouping_id = that.data.form.grouping_id;
                    info.project_id = that.data.form.project_id;
                    info.openid = that.data.userinfo.openid;
                    const team = await app.$get(`/newCourt/api/enroll/findTeammate`, { ...info });
                    if (team.errcode == '0') {
                        for (const val of team.data) {
                            val.card = val.card.substr(0, 4) + "*".repeat(val.card.length - 8) + val.card.substr(-4);
                        }
                        that.setData({ teammateList: team.data })
                    }
                }
            },
            fail: res => {
                wx.redirectTo({ url: '/pages/index/index', })
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    }
})