<template>
  <div class="account-login-wrapper">
    <div class="account-input-list">
      <div class="account-input-item">
        <div class="phoneWrapper">
          <div class="inputBox" :class="[login_form_mobile ? 'alert' : '']">
            <input
              v-model="login_form.mobile"
              type="text"
              maxlength="50"
              placeholder="手机号/帐号"
              @blur="inputBlur($event, 'mobile')"
              @focus="inputFocus($event, 'mobile')"
            />
            <p class="inputAlert hasTitle">请输入正确的帐号</p>
          </div>
        </div>
      </div>
      <div class="account-input-item">
        <div class="passwordWrapper">
          <div class="inputBox" :class="[login_form_password ? 'alert' : '']">
            <input
              v-model="login_form.password"
              :type="login_form_look ? 'text' : 'password'"
              maxlength="50"
              placeholder="密码"
              @blur="inputBlur($event, 'password')"
              @focus="inputFocus($event, 'password')"
            />
            <i
              :class="[
                login_form_look ? 'icon-xianshimima' : 'icon-yincangmima',
              ]"
              class="iconfont eyes"
              @click="lookPwd"
            ></i>
            <p class="inputAlert hasTitle">请输入正确的密码</p>
          </div>
        </div>
      </div>
    </div>
    <el-button
      :loading="btn_loading"
      type="primary"
      class="login-btn big-button"
      @click="loginSubmit"
      @keydown="keyLogin($event)"
    >
      立即登录
    </el-button>
    <p v-if="isSystem" class="find-pass-des float_left" @click="register">
      没有账号？
      <a href="javascript:">立即注册</a>
    </p>
    <p v-if="isSystem" class="find-pass-des float_right" @click="forgetPwd">
      <a href="javascript:">忘记密码?</a>
    </p>
  </div>
</template>

<script>
  import { mapActions } from "vuex";
  import { login, getAclList, getStaffByToken } from "@/api/user";
  import router from "@/router";
  export default {
    name: "LoginView",
    props: {
      //source判断登录来源 1:后台管理员,员工 2:供应商 3:商户
      source: {
        type: [String, Number],
        default: 1,
      },
      // 是否显示忘记密码按钮
      isSystem: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        btn_loading: false,
        login_form_look: false,
        login_form_mobile: false,
        login_form_password: false,
        login_form: {
          mobile: "",
          password: "",
        },
      };
    },
    mounted() {
			console.log('denglu ')
      document.body.addEventListener("keydown", this.keyLogin);
    },
    destroyed() {
      document.body.removeEventListener("keydown", this.keyLogin, false);
    },
    methods: {
      ...mapActions({
        changeEnterpriseSalt: "MUser/changeEnterpriseSalt",
        login: "user/login",
        changeUserName: "MUser/changeUserName",
        setAccessToken: "user/setAccessToken",
        setEnToken: "user/setEnToken",
        changeExpireTime: "MUser/changeExpireTime",
        changeShelfLifeSetUp: "MUser/changeShelfLifeSetUp",
        changeUserCenterId: "MUser/changeUserCenterId",
        changeEnterpriseScope: "MUser/changeEnterpriseScope",
        changeEnterprise: "MUser/changeEnterprise",
        changeSystemType: "MUser/changeSystemType",
        changeEnterpriseLength: "MUser/changeEnterpriseLength",
        changeMerchantData: "MUser/changeMerchantData",
      }),
      keyLogin(e) {
        if (e.keyCode === 13) {
          this.loginSubmit();
        }
      },
      // 登录提交
      async loginSubmit() {
        if (!this.login_form.mobile) {
          this.login_form_mobile = true;
        }
        if (!this.login_form.password) {
          this.login_form_password = true;
        }
        const isSub = Object.values(this.login_form).every((item) => !!item);
        if (!isSub) {
          return;
        }
        try {
          this.btn_loading = true;
          const { data } = await login({
            mobile: this.login_form.mobile,
            password: this.login_form.password,
            source: this.source,
          });
          this.btn_loading = false;
          await this.login(data.token);
          await this.changeUserName(this.login_form.mobile);
          this.changeEnterpriseSalt(data.salt);
          // 存储登录后台类型
          await this.$store.dispatch("MUser/changeSystemType", this.source);
          if (this.source === 3) {
            // 多商户登录
            this.changeMerchantData(data.enterprise);
            await this.$router.push("/MultiMerchant");
          } else {
            // 后台登录
            // 进入企业
            
            this.changeEnterpriseLength(data.enterprise.length);
            if (data.enterprise.length === 1) {
              await this.goEnterprise(data.enterprise[0]);
            } else if (data.enterprise.length > 1) {
              await this.$router.push("/Enterprise");
            } else {
              await this.$router.push("/CreateStore");
            }
          }
        } finally {
          this.btn_loading = false;
        }
      },
      forgetPwd() {
        this.btn_loading = false;
        this.$emit("forgetPwd");
      },
      register() {
        this.btn_loading = false;
        this.$emit("register");
      },
      inputBlur(e, prop) {
        this["login_form_" + prop] = !this.login_form[prop];
      },
      inputFocus(e, prop) {
        this["login_form_" + prop] = false;
      },
      lookPwd() {
        this.login_form_look = !this.login_form_look;
      },
      // 进入企业
      async goEnterprise(row) {
        const Loading = this.$baseColorfullLoading(1, "正在进入企业...");
        this.setEnToken(row.token);
        this.changeEnterpriseScope(row.scope);
        this.changeEnterprise(row);
        this.changeExpireTime(row.expireTime);
        this.changeShelfLifeSetUp(row.shelfLifeSetUp);

        sessionStorage.setItem("roleType", row.roleType);

        await this.$store.dispatch("user/getUserInfo", row.roleType);

        if (!this.$route.params.isCashier) {
			console.log('账号权限',row.scope);
          if (row.scope === 4) {
            // 单店铺请求账号权限
            await this.getAclList(row.roleType);
            await this.getStaffByToken(row.roleType);
            await this.$router.push(`/`);
          } else {
            await this.$router.push(`/SelectStore`);
          }
        } else {
          await this.$router.push(`/CashierShop/CashierShop`);
        }
        Loading.close();
      },
      // 获取当前登录员工信息
      async getStaffByToken(roleType) {
        const { data } = await getStaffByToken(roleType);
        if (data.name) {
          this.changeUserName(data.name);
        }
        this.changeUserCenterId(data.userCenterId);
      },
      // 获取员工权限
      async getAclList(roleType) {
        const { data } = await getAclList(roleType);
        sessionStorage.setItem("dataField", JSON.stringify(data.dataField));
        sessionStorage.setItem("isSuper", data.isAdministrator);
        sessionStorage.setItem("nodes", JSON.stringify(data.custom));

        // 进入企业设置，根据权限设置菜单
        let accessRoutes = await this.$store.dispatch("routes/setRoutes");
        router.addRoutes(accessRoutes);
      },
    },
  };
</script>

<style scoped lang="scss">
  .account-login-wrapper {
    .find-pass-des {
      color: #879bba;
      font-size: 14px;
      a {
        color: #2153d4;
        font-size: 14px;
      }
    }
    .login-btn {
      margin: 0 auto 16px;
      width: 320px;
      height: 42px;
      border: 0 none;
      /*line-height: 56px;*/
      font-size: 16px;
      text-align: center;
      cursor: pointer;
      color: #fff;
      background-color: #2153d4;
      outline: none;
      font-family: SourceHanSansCN-Medium, SourceHanSansCN;
      font-weight: 500;
      border-radius: 2px;
    }
    .account-input-item {
      margin-bottom: 24px;
      .inputText {
        color: #999;
        transition: all 0.4s cubic-bezier(0.23, 1, 0.32, 1);
        font-size: 16px;
        margin: 0;
        line-height: 35px;
        transform: translate3d(0, 28px, 0) scale(1);
        transform-origin: left top;
        position: absolute;
        bottom: 30px;
      }
      .inputAlert {
        display: block;
        color: #ff3366;
        font-size: 12px;
        margin: 0;
        line-height: 12px;
        position: absolute;
        right: 0;
        bottom: -18px;
      }
      .inputBox {
        position: relative;
        width: 320px;
        height: 40px;
        .inputAlert {
          display: none;
          &.hasTitle {
            margin-left: 66px;
          }
        }
        input {
          padding-left: 16px;
          font-size: 16px;
          outline: none;
          box-shadow: none;
          width: 320px;
          line-height: 40px;
          height: 40px;
          display: block;
          position: absolute;
          left: 0;
          top: 0;
          border: solid 1px #cad0d7;
          background: transparent;
          color: #333;
          transition: all 0.2s linear;
          border-radius: 3px;
          &:focus {
            border: 1px solid #2a75ed;
            border-radius: 3px;
          }
        }
        &.alert {
          input {
            border-color: #cad0d7;
          }
        }
      }
      .inputTextFocus {
        transform: translateZ(0) scale(0.75);
      }
      .phoneWrapper {
        color: #353535;
        position: relative;
      }
      .passwordWrapper {
        color: #353535;
        position: relative;
        .eyes {
          position: absolute;
          bottom: 5px;
          right: 17px;
          color: #2d405e;
          cursor: pointer;
          font-size: 24px;
        }
      }
    }
  }
</style>
