<template>
  <modal
    :value="isShowLogin"
    title="您好<br />欢迎来到芒果保险"
    :closeable="true"
    cancel-btn
    confirm-btn="确定"
    @close="setIsShowLogin(false)"
    @confirm="$refs.loginForm.submit()"
  >
    <cr-form
      class="login-form"
      ref="loginForm"
      show-error
      validate-trigger="onBlur"
      @submit="login"
      @failed="onFormFailed"
    >
      <cr-field
        v-model="formData.phoneNo"
        name="phoneNo"
        type="tel"
        label="手机号"
        placeholder="请填写您的手机号"
        :rules="validOptions[0]"
      />
      <cr-field
        v-model="formData.verifyCode"
        name="verifyCode"
        type="tel"
        label="验证码"
        placeholder="请填写验证码"
        :rules="validOptions[1]"
      >
        <template v-slot:button>
          <a href="javascript:;" @click="getCode" v-if="!showCount">获取验证码</a>
          <span class="login-form-remain" v-else>{{ count }}s</span>
        </template>
      </cr-field>
      <div class="protocol">
        确定登录即表示同意
        <a href="javascript:;" @click="showProtocol(0)">《用户协议》</a>
        <a href="javascript:;" @click="showProtocol(1)">《隐私政策》</a>
      </div>
    </cr-form>
  </modal>
</template>

<script>
import { mapState, mapActions } from "vuex";
import Modal from "@/components/Modal";
import { loginByPhone, getCaptchaSms } from "@/api/user";
import protocol from "@/api/protocol";
import { isPhone, isWeixinBrower } from "@/service/validation";
import localStorage from "@/service/localStorage";
export default {
  name: "LoginModal",
  components: {
    Modal
  },
  data() {
    return {
      protocol: [
        {
          title: "用户协议",
          url: protocol.userAgreement
        },
        {
          title: "隐私政策",
          url: protocol.privacyPolicy
        }
      ],
      show: true,
      showCount: false,
      count: "",
      timer: null,
      formData: {
        phoneNo: "",
        verifyCode: ""
      },
      validOptions: [
        [
          { required: true, message: "请填写您的手机号" },
          { validator: isPhone, message: "请填写正确的手机号码" }
        ],
        [{ required: true, message: "请填写验证码" }]
      ]
    };
  },
  computed: {
    ...mapState(["isShowLogin"])
  },
  methods: {
    ...mapActions(["setIsShowLogin", "setPublicPopup"]),
    showProtocol(idx) {
      this.setPublicPopup(this.protocol[idx]);
    },
    onFormFailed(errorInfo) {
      const { errors } = errorInfo;
      this.$notify({ type: "warning", message: errors[0].message });
    },
    async login() {
      this.formData.loginChannel = isWeixinBrower ? 1 : 2;
      this.formData.openId = localStorage.get("openId") || null;
      const res = await loginByPhone(this.formData);
      if (res) {
        this.$notify({ type: "success", message: "登录成功" });
        this.setIsShowLogin(false);
        localStorage.set("mongoToken", res.token);
        // TODO 开发目前使用这个token
        // localStorage.setItem("mongoToken", "6ae7da7dd4c543f1a36c702c6f419f12");
      }
    },
    async getCode() {
      const TIME_COUNT = 60;
      const { phoneNo } = this.formData;
      if (this.timer) return;
      if (!isPhone(phoneNo)) {
        this.$notify({ type: "warning", message: "请填写正确的手机号码" });
        return;
      }
      const res = await getCaptchaSms({ phoneNo });
      if (res && !this.timer) {
        this.count = TIME_COUNT;
        this.showCount = true;
        this.$notify({ type: "success", message: "短信验证码已发送，请注意查收" });
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.showCount = false;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    }
  }
};
</script>

<style lang="less" scoped>
@import "../style/var.less";
.login-form {
  @{deep} .cr-field--error-message {
    display: none;
  }
  @{deep} .cr-cell {
    &-group {
      &::after {
        display: none;
      }
    }
    background-color: @gray-1;
    border-radius: @border-radius-md;
    margin-bottom: 12px;
    align-items: center;
    padding: 9px 16px;
    &::after {
      display: none;
    }
    &__title {
      color: #333333;
      display: flex;
      align-items: center;
    }
  }
}
.protocol {
  font-size: 11px;
  text-align: center;
  a {
    font-size: 11px;
  }
}
</style>
