<template>
    <view class="login" style="background: linear-gradient(to bottom, #FFFFE0, #00FF00);">
        <!-- <view class="bg">
            <image src="../../static/icons/bg.png" mode="widthFix"></image>
        </view> -->
		
		<view class="header" style="width: 100%;top: 10%;position: relative;">
			<view style="font-size: 50px;text-align: center;color: green;">
				精准大田专家填报系统
			</view>
		</view>
		
        <view class="padding flex flex-direction" style="margin-top:10vh">
            <view class="cu-bar btn-group margin-top-sm">
                <!-- <button class="cu-btn bg-red lg" @tap="handleWxLogin" style="margin-left: 0;">
                    微信快捷登录
                </button> -->
                <!-- <button class="cu-btn bg-green lg" style="width: 60%; margin-right: 0;top: 70%;position: absolute;" @tap="handlePhoneLogin"
                        data-target="passwordModal">
                    账号密码登录
                </button> -->
				<view class="padding bg-white" style="background: linear-gradient(to bottom, #b7ff98, #b0ffaa);">
				    <form bindsubmit="userNameLogin" bindtap="handleClick">
				        <view class="cu-form-group margin-top">
				            <view class="title">用户名</view>
				            <input placeholder="请输入用户名" type="text" v-model="username">
				        </view>
				        <view class="cu-form-group">
				            <view class="title">密码</view>
				            <input placeholder="请输入密码" type="password" v-model="password">
				        </view>
				        <view class="padding flex flex-direction margin-top-xl">
				            <button class="cu-btn bg-blue lg  margin-tb-sm shadow-blur text-lg"
				                    @click="handleLoginByUsername"
									style="margin: 0 auto;margin-bottom: 5%;width: 50%;">登录
				            </button>
				            <!-- <button class="cu-btn line-red lg shadow-blur text-lg" @tap="hideModal"
									style="margin-left: 20%;">取消</button> -->
				        </view>
				    </form>
				</view>
            </view>
            <!-- <button class="cu-btn bg-blue lg margin-top-sm" @tap="handlePhoneLogin" data-target="bottomModal">
                手机验证码登录
            </button> -->
        </view>

        <view class="footer">
            <view>主办单位：安徽省农业农村厅</view>
            <view>技术支持：安徽省北斗精准农业信息工程实验室</view>
        </view>

        <view class="cu-modal bottom-modal" :class="modalName==='passwordModal'?'show':''" @tap="hideModal">
            <view class="cu-dialog btDialog" @tap.stop.prevent>
                <view class="box margin-top-xxl">
                    <view class="cu-bar justify-center bg-white">
                        <view class="action sub-title">
                            <text class="text-xl text-bold text-blue">用户登录</text>
                            <text class="text-ABC text-blue">login</text>
                        </view>
                    </view>
                </view>

                <!-- <view class="padding bg-white">
                    <form bindsubmit="userNameLogin" bindtap="handleClick">
                        <view class="cu-form-group margin-top">
                            <view class="title">用户名</view>
                            <input placeholder="请输入用户名" type="text" v-model="username">
                        </view>
                        <view class="cu-form-group">
                            <view class="title">密码</view>
                            <input placeholder="请输入密码" type="password" v-model="password">
                        </view>
                        <view class="padding flex flex-direction margin-top-xl">
                            <button class="cu-btn bg-blue lg  margin-tb-sm shadow-blur text-lg"
                                    @click="handleLoginByUsername">登录
                            </button>
                            <button class="cu-btn line-red lg shadow-blur text-lg" @tap="hideModal">取消</button>
                        </view>
                    </form>
                </view> -->
            </view>
        </view>

        <view class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''" @tap="hideModal">
            <view class="cu-dialog btDialog" @tap.prevent.stop>
                <view class="box margin-top-xxl">
                    <view class="cu-bar justify-center bg-white">
                        <view class="action sub-title">
                            <text class="text-xl text-bold text-blue">验证码登录</text>
                            <text class="text-ABC text-blue">login</text>
                            <!-- last-child选择器-->
                        </view>
                    </view>
                </view>

                <view class="padding bg-white">
                    <form bindsubmit="userNameLogin" bindtap="handleClick">
                        <view class="cu-form-group ">
                            <view class="title">手机号</view>
                            <input name="input" placeholder="请输入手机号" type="number" @blur="onPhoneBlur"
                                   v-model="userPhone"></input>
                        </view>

                        <view class="cu-form-group">
                            <view class="title">验证码</view>
                            <input placeholder="请输入验证码" type="number" v-model="userCode"></input>
                            <button class="cu-btn bg-green shadow" type="" @tap="handleGetCode"
                                    :disabled="disableCodeBtn">
                                {{ showTime ? time + "s" : "验证码" }}
                            </button>
                        </view>
                        <view class="padding flex flex-direction margin-top-xl">
                            <button class="cu-btn bg-blue lg  margin-tb-sm shadow-blur text-lg"
                                    @click="handlePhoneCodeLogin">登录
                            </button>
                            <button class="cu-btn line-red lg shadow-blur text-lg" @tap="hideModal">取消</button>
                        </view>
                    </form>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    import {
        _login
    } from "./login-model.js";

    export default {
        data() {
            return {
                nameInputClass: "",
                pwdInputClass: "",
                username: wx.getStorageSync('username') || '',
                password: wx.getStorageSync('password') || '',
                modalName: null,
                time: 60,
                showTime: false,
                userPhone: "",
                userCode: "",
                disableCodeBtn: true
            };
        },
        onLoad() {
            wx.showShareMenu({
                withShareTicket: true,
                //设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
                menus: ["shareAppMessage", "shareTimeline"]
            });
        },
        methods: {

            //失去焦点后判断手机号是否注册过
            onPhoneBlur() {
                if (this.userPhone) {
                    _login.selectphone(this.userPhone, res => {
                        const { code, message } = res;
                        if (code !== 200) {
                            this.toast(message);
                            return false;
                        } else {
                            this.disableCodeBtn = false;
                        }
                    });
                }
            },

            /**
             * 获取验证码
             */
            handleGetCode() {
                if (this.showTime) {
                    return;
                }
                if (!this.userPhone) {
                    uni.showToast({
                        title: "请输入手机号",
                        duration: 1500,
                        icon: "none"
                    });
                    return;
                }
                this.$loading("发送中...");
                let timer = null;
                // 调用获取验证码接口
                setTimeout(() => {
                    this.showTime = true;
                    _login.getVerificCode(this.userPhone, res => {
                        uni.hideLoading();
                        if (res.data.code === 200) {
                            uni.showToast({
                                title: "验证码发送成功",
                                duration: 1500,
                                icon: "none"
                            });
                        }

                    });


                    timer = setInterval(() => {
                        if (this.time <= 1) {
                            clearInterval(timer);
                            this.showTime = false;
                            this.time = 60;
                        }
                        this.time = this.time - 1;
                    }, 1000);
                }, 1000);
            },
            /**
             * 关闭验证码弹框
             */
            hideModal() {
                this.modalName = null;
            },
            /**
             * 手机验证码登录
             */
            handlePhoneLogin(e) {
                this.modalName = e.currentTarget.dataset.target;
            },
            /**
             * 账号密码登录
             * */
            handleLoginByUsername() {
                if (!this.username) {
                    this.toast("请输入用户名");
                    return;
                }
                if (!this.password) {
                    this.toast("请输入密码");
                    return;
                }
                this.$loading("登录中...");
                const data = {
                    username: this.username,
                    password: this.password
                };
				wx.setStorageSync('username', data.username);
				wx.setStorageSync('password', data.password);
				console.log("登陆缓存2："+ data.username);
				//将账号信息作为全局变量
				/* getApp().globalData.username = res.data[0].username
				uni.setStorageSync('username', res.data[0].username)
				console.log("全局变量"+usernaem) */
				/* uni.reLaunch({ //跳转到主页，并携带账号参数
					url: '../../start_production/start_index/start_index?username=' +
						res.data[0].username
				}) */
                _login.login(data, res => {
                    this.loginResult(res);

                });
            },
            /**
             * 微信快捷登录
             */
            handleWxLogin() {
                this.$loading("登录中...");
               /* uni.login({
                    success: res => {
                        _login.wxOpenidLogin(res.code, res => {
                            uni.hideLoading();
                            // console.log(res);
                            this.loginResult(res);
                        });
                    }
                }); */
				uni.hideLoading();
				wx.redirectTo({
				    url: "/pages/index/index"
				});
				
            },
            /**
             * 跳转注册页面
             */
            handleRegister() {
                uni.navigateTo({
                    url: "/pages/register/index"
                });
            },

            handlePhoneCodeLogin() {
                if (this.userPhone === null || this.userPhone === "") {
                    this.toast("手机号不能为空");
                    return;
                }
                if (this.userCode === null || this.userCode === "") {
                    this.toast("验证码不能为空");
                    return;
                }
                _login.verificationCodeLogin(this.userPhone, this.userCode, res => {
                    uni.hideLoading();
                    if (res.code === 1003) {
                        this.toast("验证码错误");
                    } else if (res.code === 1001) {
                        this.toast(res.message);
                    } else if (res.code === 200 || res.code === 1) {
                        // 登录成功
                        this.loginResult(res);
                    }


                });
            },
            loginResult(res) {

                const {
                    code,
                    data,
                    msg
                } = res.data;
                if (code === 200 || code === 1) {
                    this.toast("登录成功");
                    setTimeout(() => {
						console.log("登陆成功")
						//console.log("登陆缓存："+ wx.getStorageSync('username'));
                        //uni.setStorageSync("token", data.token);
                        //uni.setStorageSync("tokenHead", data.tokenHead);
                        //wx.setStorageSync('username', res.data.username);
						//console.log("登陆缓存："+ data.username);
						//wx.setStorageSync("password", data.password);
						//localStorage.setItem('user',JSON.stringify())
                        // // uni.setStorageSync("deviceSerial",info.deviceSerial)
                        // // uni.setStorageSync('mark',info.mark)
                        // uni.setStorageSync('info',info)
                        wx.redirectTo({
                            url: "/pages/index/index"
                        });
                    }, 500);
                } else {
                    this.toast(msg);
                }

            },
            toast(message) {
                uni.showToast({
                    icon: "none",
                    title: message,
                    duration: 1000
                });
            }
        },
        onShareAppMessage(res) {
            return {
                title: "欢迎使用农监宝",
                path: "/pages/login/index"
            };
        }
    };
</script>

<style scoped>
    .login {
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
        background-color: #FFF;
    }

    .cu-form-group .title {
        min-width: calc(4em + 30upx);
    }

    .bg {
        width: 100%;
        position: relative;

    }

    .bg image {
        width: 100%;
    }

    .bg-text {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 10%;
        text-align: center;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
    }

    .bg-text-title {
        width: 152px;
        height: 53px;
        font-size: 38px;
        color: #FFFFFF;
    }

    .bg-text-desc {
        width: 276px;
        height: 30px;
        font-family: PingFangSC-Regular;
        font-size: 22px;
        margin-top: 5px;
        color: #FFFFFF;
    }

    .login-form {
        width: 100%;
        justify-content: center;
        padding-top: 16%;

    }

    .btDialog {
        height: 85vh;
        padding-top: 10vh;
        border-radius: 30upx 30upx 0 0 !important;
        overflow: hidden;
    }

    /*.login-form input {
          width: 84%;
          margin-left: 8%;
          font-size: 17px;
          height: 50px;
          font-weight: 400;
          border-bottom: 1px solid rgba(190, 190, 190, 1);
          margin-bottom: 30px;
      }

      .login-form .focus {
          border-bottom: 1px solid #00B525;
      }*/
    /*
          button {
              width: 84%;
              margin-left: 8%;
              background-image: linear-gradient(90deg, #10A32D 0%, #007230 100%);
              border-radius: 4px;
              font-family: PingFangSC-Medium;
              font-size: 17px;
              color: #FFFFFF;
              font-weight: 500;
              margin-bottom: 10px;
          }*/

    .footer {
        position: fixed;
        text-align: center;
        line-height: 40px;
        margin-bottom: 2px;
        bottom: 5vh;
        width: 100%;
        font-size: 12px;
    }

    .footer view {
        line-height: 22px;
    }

    .register {
        padding: 0 8%;
        text-align: right;
        font-size: 12px;
    }

    .register text {
        text-decoration: underline;
    }

    .wx-login-btn {
        background-image: none;
        background-color: #007aff;
        margin-top: 26%;
        margin-bottom: 30px;
    }

    .login-popup {
        width: 100%;
        height: 50vh;
        background-color: #FFF;
    }

    .login .cu-form-group input {
        text-align: left;
    }

    .code-span {
        display: inline-block;
        width: 70px;
        color: #0081ff;
    }
</style>