// pages/clock/clock.js
const app = getApp();
// 引入SDK核心类
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var getLocation = function (self) {//当第一次未授权时需要重新调用此接口
    wx.getLocation({
        type: 'wgs84',
        success: function (res) {
            console.log('再次授权结果', res);
            self.setData({
                latitude: res.latitude,
                longitude: res.longitude
            });
            var latitude = res.latitude;
            var longitude = res.longitude;
            // 实例化API核心类
            var demo = new QQMapWX({
                key: 'CLVBZ-KHZKP-KWLDW-VDJTA-QVUST-XOBVO' // 必填
            });

            // 调用接口
            demo.reverseGeocoder({
                location: {
                    latitude: res.latitude,//纬度
                    longitude: res.longitude//经度
                },
                success: function (res) {
                    console.log('城市', res);
                    wx.setStorageSync('city', res.result.address_component.city);
                    let params = {
                        city: res.result.address_component.city,
                        lat: latitude,//纬度
                        lng: longitude,//经度
                    };
                    self.postPosition(params);
                },
                fail: function (res) {
                    console.log(res);
                },
                complete: function (res) {
                    // console.log(res);
                }
            });
        },
        fail: function () {
            wx.showToast({
                title: '授权失败',
                icon: 'none',
                duration: 1000
            })
        }
    })
}


Page({

    /**
     * 页面的初始数据
     */
    data: {
        punchState: true,
        test: {name: '',id:1,},
        is_bingding: false,
        state_data: {
            is_showSuccessModal: false,
            icon: '../../../images/success.png',
            title:'恭喜您',
            content: '打卡成功!'
        },
        state_data_fail: {
            is_showSuccessModal: false,
            icon: '../../../images/fail.png',
            title:'提示',
            content: '打卡失败!'
        }
    },
    //首次登录小程序,跳转到认证手机页面
    goPhoneCode() {
        wx.navigateTo({url: '/pages/index/phone-code/phone-code?from_clock=' + true})
    },
    //判断手机号是否绑定
    checkMobile() {
        let url = '/portal/Index/check_mobile';
        let header = {
            "XX-token": wx.getStorageSync('token')
        };
        app.post(url, {}, header).then((res) => {
            console.log(res);
            if (res.is_binding) {
                this.setData({is_bingding: true})
            } else {
                this.setData({is_bingding: false})
            }
        })
    },
    //打卡申诉
    punchApply() {
        wx.navigateTo({
            url: 'punchAppeal/punchAppeal?test_name=' + this.data.test.name,
        })
    },
    //打卡
    punch() {
        if(wx.getStorageSync('city') !== '') {
            if (this.data.test.name !== '') {
                let url = '/portal/Experiment/user_sign';
                let header = {
                    "XX-token": wx.getStorageSync('token')
                };
                let params = {
                    lab_id: this.data.test.id,//实验室id
                    lat: this.data.latitude,
                    lng: this.data.longitude,
                };
                app.post(url, params, header).then((res) => {
                    console.log('打卡结果', res);
                    if (res.is_success) {
                        this.setData({
                            punchState: false,
                            'state_data.is_showSuccessModal': true,
                        })
                    }else {
                        this.setData({
                            // punchState: false,
                            'state_data_fail.is_showSuccessModal': true,
                        })
                    }
                })
            } else{
                wx.showToast({
                    title: '未获取当前实验室,无法打卡!',
                    icon: 'none',
                    duration: 2000
                })
            }
        }else {
            this.getExperiment();
        }

    },
    //关闭打卡成功弹框
    modalConfirm() {
        this.setData({
            'state_data.is_showSuccessModal': false,
            'state_data_fail.is_showSuccessModal': false})
    },
    // 打卡页面获取用户所在实验室
    postPosition(params) {
        let url = '/portal/Experiment/user_session';
        let header = {
            "XX-token": wx.getStorageSync('token')
        };
        app.post(url, params, header).then((res) => {
            console.log('获取用户所在实验室', res);
            this.setData({
                test: res
            });
            // this.punch();
        })
    },
    //打卡页面获取位置授权
    getExperiment() {
        console.log('实验室');
        const self = this;
        if (wx.getStorageSync('city') !== '') {//如果第一次授权过
            console.log(111);
            wx.getLocation({
                type: 'wgs84',
                success(res) {
                    self.setData({latitude:res.latitude,longitude:res.longitude});
                    let params = {
                        city: wx.getStorageSync('city'),
                        lat: res.latitude,//纬度
                        lng: res.longitude,//经度
                    };
                    self.postPosition(params);
                }
            });
        } else {//重新调起授权
            console.log('获取当前城市');
            wx.getSetting({
                success: (res) => {
                    console.log('成功');
                    if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化进入该页面,且未授权
                        console.log('非初始化进入该页面,且未授权');
                        wx.showModal({
                            title: '是否授权当前位置',
                            content: '需要获取您的地理位置,请确认授权,否则无法完成打卡',
                            success: function (res) {
                                if (res.cancel) {
                                    self.setData({
                                        isshowCIty: false
                                    })
                                    wx.showToast({
                                        title: '授权失败',
                                        icon: 'none',
                                        duration: 1000
                                    })
                                } else if (res.confirm) {
                                    wx.openSetting({
                                        success: function (dataAu) {
                                            if (dataAu.authSetting["scope.userLocation"] == true) {
                                                wx.showToast({
                                                    title: '授权成功',
                                                    icon: 'success',
                                                    duration: 1000
                                                })
                                                //再次授权,调用getLocationt的API
                                                getLocation(self);
                                            } else {
                                                wx.showToast({
                                                    title: '授权失败',
                                                    icon: 'none',
                                                    duration: 1000
                                                })
                                            }
                                        }
                                    })
                                }
                            }
                        })
                    } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化进入
                        console.log('初始化进入');
                        getLocation(self);
                    } else { //授权后默认加载
                        console.log('授权后默认加载');
                        getLocation(self);
                    }
                }
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const self = this;
        // self.checkMobile();
        self.setData({
            is_bingding:  app.globalData.is_bingding,
            screenHeight: wx.getSystemInfoSync().windowHeight,
        });
        if(wx.getStorageSync('city') !== '') {
            self.setData({city: wx.getStorageSync('city')})
        }
        self.getExperiment();
    },

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

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const self = this;
        // self.getExperiment();
    },

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

    },

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

    },

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

    },

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

    },

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

    }
})