<template>
  <view class="container">
    <!--顶部返回按钮-->
    <text class="back-btn iconfont iconzuojiantou-up" @tap="navBack"></text>
    <view class="login-title">
      <image
        class="logo"
        mode="widthFix"
        src="@/static/img/logo-xd.png"
      ></image>
      <view class="title">商家端管理后台登录</view>
    </view>
    <!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
    <view class="wrapper">
      <view class="input-content">
        <view class="input-item">
          <input
            type="text"
            name="username"
            v-model="loginParams.username"
            placeholder="请输入账户名"
          />
        </view>
        <view class="input-item" v-if="loginByPass">
          <input
            name="password"
            type="password"
            v-model="loginParams.password"
            placeholder="请输入密码"
          />
        </view>
        <view class="input-item relative" v-if="loginByPass">
          <input class="codenum"
            name="code"
            type="text"
            v-model="loginParams.code"
            placeholder="请输入验证码"
          />
          <image
            @tap="getCaptchaImage"
            class="codeImage"
            mode="widthFix"
            :src="codeImage"
          ></image>
        </view>

        <button
          class="confirm-btn"
          :disabled="btnLoading"
          :loading="btnLoading"
          @tap="toLogin"
        >
          登录
        </button>
      </view>

      <view class="forget-section" @tap="navTo()">
        忘记密码?
      </view>
    </view>
  </view>
</template>
<script>
import { authLogin, loginByPass, loginBySmsCode, smsCode } from '@/api/login';
import moment from '@/common/moment';
export default {
  data() {
    return {
      loginParams: {
        username: 'wljq',
        code: '',
        password: 'Ectrip2020',
        uuid: null,
      },
      codeImage: null,
      btnLoading: false,
      reqBody: {},
      codeSeconds: 0, // 验证码发送时间间隔
      loginByPass: true,
      smsCodeBtnDisabled: true,
      userInfo: null,
    };
  },

  onShow() {
    if (this.$mStore.getters.hasLogin) {
      this.$mRouter.reLaunch({ route: '/pages/index/index' });
    }
  },
  // 页面生命周期 监听页面加载是否加载完成
  onLoad() {
    const time = moment().valueOf() / 1000 - uni.getStorageSync('loginSmsCodeTime');   // 从本地缓存中异步获取指定 key 对应的内容。
    if (time < 60) {
      this.codeSeconds = this.$mConstDataConfig.sendCodeTime - parseInt(time, 10);
      this.handleSmsCodeTime(this.codeSeconds);
    } else {
      this.codeSeconds = this.$mConstDataConfig.sendCodeTime;
      this.smsCodeBtnDisabled = false;
      uni.removeStorageSync('loginSmsCodeTime');
    }
    this.loginParams.mobile = uni.getStorageSync('loginMobile') || '';
    this.loginParams.password = uni.getStorageSync('loginPassword') || '';
    this.userInfo = uni.getStorageSync('wechatUserInfo');

    this.getCaptchaImage();
  },
  methods: {
    loginTest(mobile, password) {
      this.loginParams.mobile = mobile;
      this.loginParams.password = password;
    },

    // 发送验证码并进入倒计时
    async getSmsCode() {
      this.reqBody['mobile'] = this.loginParams['mobile'];
      let checkSendCode = this.$mGraceChecker.check(
        this.reqBody,
        this.$mFormRule.sendCodeRule
      );
      if (!checkSendCode) {
        this.$mHelper.toast(this.$mGraceChecker.error);
        return;
      }
      await this.$http
        .post(smsCode, {
          mobile: this.loginParams.mobile,
          usage: 'login',
        })
        .then((r) => {
          if (r.data) {
            this.$mHelper.toast(`验证码发送成功, 验证码是${r.data}`);
          } else {
            this.$mHelper.toast('验证码已发送.');
          }
          this.smsCodeBtnDisabled = true;
          uni.setStorageSync('loginSmsCodeTime', moment().valueOf() / 1000);
          this.handleSmsCodeTime(59);
        });
    },

    handleSmsCodeTime(time) {
      let timer = setInterval(() => {
        if (time === 0) {
          clearInterval(timer);
          this.smsCodeBtnDisabled = false;
        } else {
          this.codeSeconds = time;
          this.smsCodeBtnDisabled = true;
          time--;
        }
      }, 1000);
    },
    // 失去焦点的手机号
    blurMobileChange(e) {
      this.mobile = e.detail.value;
    },
    // 切换登录方式
    showLoginBySmsCode() {
      this.loginByPass = !this.loginByPass;
    },
    // 返回上一页
    navBack() {
      this.$mRouter.back();
    },
    // 统一跳转路由
    navTo() {
      this.$mRouter.redirectTo({ route: '/pages/public/resetpassword' });
    },
    // 返回主页
    toHome() {
      this.$mRouter.reLaunch({ route: '/pages/index/index' });
    },

		// 获取验证码
    async getCaptchaImage() {
      await this.$http
        .get('captchaImage', {})
        .then(async (r) => {
          this.codeImage = 'data:image/gif;base64,' + r.data.img;
          this.loginParams.uuid = r.data.uuid;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 提交表单
    async toLogin() {
      let cheRes, loginApi;
      if (this.loginByPass) {
        loginApi = loginByPass;
        cheRes = this.$mGraceChecker.check(
          this.loginParams,
          this.$mFormRule.loginByPassRule
        );
      }
      //表单验证规则是否通过，否，终止登陆提示错误信息
      if (!cheRes) {
        this.$mHelper.toast(this.$mGraceChecker.error);
        return;
      }
      /*  #ifdef  APP-PLUS  */
      this.reqBody.group = 'tinyShopApp';
      /*  #endif  */
      /*  #ifdef H5  */
      this.reqBody.group = 'tinyShopH5';
      /*  #endif  */
      /*  #ifdef  MP-WEIXIN  */
      this.reqBody.group = 'tinyShopWechatMq';
      /*  #endif  */
      /*  #ifdef  MP-QQ  */
      this.reqBody.group = 'tinyShopQqMq';
      /*  #endif  */
      this.handleLogin(this.loginParams, loginApi);
    },
    // 登录
    async handleLogin(params, loginApi) {
      this.btnLoading = true;
      await this.$http
        .post(loginApi, params)
        .then((r) => {
          this.$mHelper.toast('恭喜您，登录成功！');
          this.$mStore.commit('login', r.data);
          const backToPage = uni.getStorageSync('backToPage');
          if (backToPage) {
            if (
              backToPage.indexOf('/pages/user/user') !== -1 ||
              backToPage.indexOf('/pages/cart/cart') !== -1 ||
              backToPage.indexOf('/pages/index/index') !== -1 ||
              backToPage.indexOf('/pages/notify/notify') !== -1 ||
              backToPage.indexOf('/pages/category/category') !== -1
            ) {
              this.$mRouter.reLaunch(JSON.parse(backToPage));
            } else {
              this.$mRouter.redirectTo(JSON.parse(backToPage));
            }
            uni.removeStorageSync('backToPage');
            uni.removeStorageSync('wechatUserInfo');
          } else {
            this.$mRouter.reLaunch({ route: '/pages/index/index' });
          }
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
page {
  background: #fff;
}

.container {
  padding-top: 115px;
  position: relative;
  width: 100vw;
  overflow: hidden;
  background: #fff;
}

.wrapper {
  position: relative;
  z-index: 90;
  background: #fff;
  padding-bottom: 40upx;
}

.back-btn {
  position: absolute;
  left: 40upx;
  z-index: 9999;
  padding-top: var(--status-bar-height);
  top: 40upx;
  font-size: 40upx;
  color: $font-color-dark;
}

.login-title {
  padding-left: 32upx;
  margin-bottom: 40upx;

  .logo {
    width: 156upx;
  }
  .title {
    font-size: 48upx;
    color: #2f2f2f;
  }
}

.left-top-sign {
  font-size: 120upx;
  color: $page-color-base;
  position: relative;
  left: -16upx;
}

.right-top-sign {
  position: absolute;
  top: 80upx;
  right: -30upx;
  z-index: 95;

  &:before,
  &:after {
    display: block;
    content: '';
    width: 400upx;
    height: 80upx;
    background: #b4f3e2;
  }

  &:before {
    transform: rotate(50deg);
    border-radius: 0 50px 0 0;
  }

  &:after {
    position: absolute;
    right: -198upx;
    top: 0;
    transform: rotate(-50deg);
    border-radius: 50px 0 0 0;
  }
}

.left-bottom-sign {
  position: absolute;
  left: -270upx;
  bottom: -320upx;
  border: 100upx solid #d0d1fd;
  border-radius: 50%;
  padding: 180upx;
}

.welcome {
  position: relative;
  left: 50upx;
  top: -90upx;
  font-size: 46upx;
  color: #555;
  text-shadow: 1px 0px 1px rgba(0, 0, 0, 0.3);
}

.input-content {
  padding: 0 32upx;
}

.input-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  padding: 0 30upx;
  background: $page-color-light;
  height: 80upx;
  border-radius: 4px;
	margin-bottom: 30upx;
	background-color: #fff;
	border-bottom: 1px solid #e7e7e7;
	

  .tit {
    height: 50upx;
    line-height: 56upx;
    font-size: $font-sm + 2upx;
    color: $font-color-base;
  }

  input {
    height: 60upx;
    font-size: $font-base + 2upx;
		color: $font-color-dark;
		background-color: #fff;
		width: 100%;
	}
	.codenum {
		width: 65%;
	}
}

.input-item-sms-code {
  position: relative;
  width: 100%;
  .sms-code-btn {
    position: absolute;
    color: #111;
    right: 20upx;
    bottom: 20upx;
    font-size: 28upx;
  }

  .sms-code-resend {
    color: #999;
  }

  .sms-code-btn:after {
    border: none;
    background-color: transparent;
  }
}

.forget-section {
  font-size: $font-sm + 2upx;
  color: $font-color-spec;
  text-align: center;
  margin-top: 40upx;
}

.register-section {
  margin: 30upx 0 50upx 0;
  width: 100%;
  font-size: $font-sm + 2upx;
  color: $font-color-base;
  text-align: center;

  text {
    color: $font-color-spec;
    margin-left: 10upx;
  }

  text:first-child {
    margin-right: 10upx;
  }
}

.btn-group {
  display: flex;
  margin-bottom: 20upx;
}

.codeImage {
  width: 220upx;
  position: absolute;
  top: 0;
  right: 0;
}
.confirm-btn {
  background-color: rgb(255, 205, 0);
  color: rgb(35, 40, 40);
  font-weight: bold;
  border-radius: 40upx;
}
</style>
