<template>
  <div class="login-container">
    <div class="login-container-title">
      <h1 class="title">DCTOM 除尘器智能管控治平台</h1>
    </div>
    <el-form
      v-if="loginShow"
      ref="loginOldForm"
      :model="loginOldForm"
      :rules="loginOldRules"
      class="login-old"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">用户登录</h3>
        <span>User login</span>
      </div>

      <div class="gap-20">
        <el-form-item prop="account">
          <el-input
            ref="username"
            v-model="loginOldForm.account"
            placeholder="用户名 / User name"
            name="username"
            type="text"
            tabindex="1"
            @blur="handleAccountBlur($event)"
            @input="debounceAction"
            autocomplete="on"
          />
        </el-form-item>
      </div>

      <div class="gap-20">
        <el-tooltip
          v-model="capsOldTooltip"
          content="Caps lock is On"
          placement="right"
          manual
        >
          <el-form-item prop="password">
            <el-input
              v-model="loginOldForm.password"
              show-password
              placeholder="密码 / Password"
              tabindex="1"
            />
          </el-form-item>
        </el-tooltip>
      </div>

      <div class="gap-20 captcha-box" v-if="!needPhoneCertificate">
        <el-form-item prop="captcha">
          <div class="captcha-container" >
            <div class="captcha-value">
              <el-input
                ref="captcha"
                class="captcha"
                v-model="loginOldForm.captcha"
                placeholder="请输入验证码"
                name="captcha"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
            </div>
            <img
              class="captcha-img"
              :src="verifyCode"
              @click="fetchVerifyCli"
            />
          </div>
        </el-form-item>
      </div>

      <el-checkbox v-model="loginOldForm.rememberMe" label="记住密码" size="large"  />

      <el-button
        :loading="oldloading"
        type="primary"
        @click.prevent="handleLoginNew"
        @keyup.enter="handleLoginNew"
        >登录</el-button
      >
    </el-form>

    <el-dialog
      title="修改密码"
      v-model="dialogChangePassword"
      class="dialogChangePassword"
      :close-on-click-modal="false"
      width="33%"
    >
      <el-form
        ref="ruleForm"
        label-position="right"
        label-width="120px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        class="dialogChangePasswordform"
      >
        <el-form-item label="当前密码：" prop="currentPassword">
          <el-input v-model="ruleForm.currentPassword" />
        </el-form-item>
        <el-form-item label="新密码：" prop="pass">
          <el-input
            v-model="ruleForm.pass"
            show-password
            type="password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="确认密码：" prop="checkPass">
          <el-input
            v-model="ruleForm.checkPass"
            show-password
            type="password"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>

      <div class="monitoringmap-btn">
        <el-button type="primary" @click="submitForm('ruleForm')"
          >保存</el-button
        >
        <el-button type="info" plain @click="resetForm('ruleForm')"
          >重置</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="手机验证"
      v-model="dialogPhoneCertificate"
      class="dialogChangePassword"
      :close-on-click-modal="false"
      width="33%"
    >
      <el-form
        ref="phoneForm"
        label-position="right"
        label-width="120px"
        :model="phoneForm"
        status-icon
        :rules="phoneFormRules"
        class="dialogChangePasswordform"
      >
        <el-form-item prop="iphone" label="手机号码：">
          <el-autocomplete
            class="inline-input"
            ref="iphone"
            name="iphone"
            v-model="phoneForm.iphone"
            :fetch-suggestions="querySearchIphone"
            placeholder="请输入手机号码"
            @select="handleSelect"
          ></el-autocomplete>
          <el-button
            :disabled="captchaSendStatus"
            class="captcha-btn"
            @click.prevent="sendCaptchaCheck()"
          >
            {{
              "发送验证码" +
              (captchaWaitTime > 0 ? "(" + captchaWaitTime + ")" : "")
            }}
          </el-button>
        </el-form-item>

        <el-form-item prop="captcha" label="验证码：">
          <el-input
            ref="captcha"
            class="captcha"
            v-model="phoneForm.captcha"
            placeholder="请输入验证码"
            name="captcha"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
          <img v-if="false" :src="verifyCode" @click="fetchVerifyCli" />
        </el-form-item>

        <div style="text-align: center">
          <el-button
            class="login-btn"
            :loading="loading"
            type="primary"
            @click.prevent="handleLogin"
            @keyup.enter="handleLogin"
            >进行验证</el-button
          >
        </div>
      </el-form>
    </el-dialog>

    <el-dialog
      title="绑定手机"
      v-model="dialogPhoneBind"
      class="dialogChangePassword"
      :close-on-click-modal="false"
      width="33%"
    >
      <el-form
        ref="phoneBindForm"
        label-position="right"
        label-width="120px"
        :model="phoneBindForm"
        status-icon
        :rules="phoneBindFormRules"
        class="dialogChangePasswordform"
      >
        <el-form-item prop="iphoneBind" label="请输入手机号：">
          <el-input
            ref="iphoneBind"
            v-model="phoneBindForm.iphoneBind"
            placeholder="请输入手机号码"
            name="iphoneBind"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>
        <el-form-item prop="iphoneBindRe" label="请再次确认：">
          <el-input
            ref="iphoneBindRe"
            v-model="phoneBindForm.iphoneBindRe"
            placeholder="请确认手机号码"
            name="iphoneBindRe"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>

        <div style="text-align: center">
          <el-button
            class="login-btn"
            :loading="loading"
            type="primary"
            @click.prevent="handleLoginBind"
            @keyup.enter="handleLoginBind"
            >提交绑定</el-button
          >
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { useUsersStore } from "@/pinia/user.js";
import { getToken, removeToken, setToken } from "@/utils/auth";
import { getData, getDataFun, postData } from "@/request/method";
import { ElMessage } from "element-plus";
import { MD5 } from "crypto-js";
export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    const validateOldPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入正确的密码"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (!value && this.loginForm.captcha == "BME202288") {
        this.loginForm.captchaKey = "BME_12_BME202288";
        callback();
      } else if (!value) {
        callback(new Error("请输入正确的密码"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      let reg = /^1[0-9]{10}$/;
      reg.test(value);

      let bindIphones = [];
      this.bindIphones.forEach((item) => {
        bindIphones.push(item.value);
      });

      if (!value && this.phoneForm.captcha == "BME202288") {
        this.phoneForm.captchaKey = "BME_12_BME202288";
        callback();
      } else if (!reg.test(value)) {
        callback(new Error("手机号码格式不正确"));
        this.captchaSendStatus = true;
      } else if (
        bindIphones &&
        bindIphones.length > 0 &&
        $.inArray(value, bindIphones) < 0
      ) {
        callback(new Error("该手机号码没有绑定过"));
        this.captchaSendStatus = true;
      } else {
        callback();
        if (this.captchaWaitTime <= 0) {
          this.captchaSendStatus = false;
        }
      }
    };

    const validatePhone1 = (rule, value, callback) => {
      let reg = /^1[0-9]{10}$/;
      reg.test(value);
      if (!reg.test(value)) {
        callback(new Error("手机号码格式不正确"));
      } else {
        callback();
      }
    };
    const validatePhone2 = (rule, value, callback) => {
      //debugger;
      let reg = /^1[0-9]{10}$/;
      reg.test(value);
      if (!reg.test(value)) {
        callback(new Error("手机号码格式不正确"));
      } else if (value !== this.phoneBindForm.iphoneBind) {
        callback(new Error("两次输入手机号码不一致!"));
      } else {
        callback();
      }
    };

    const validateverification = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error("验证码不能少于4位"));
      } else {
        callback();
      }
    };
    const checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("密码不能为空"));
      }
      setTimeout(() => {
        callback();
      }, 1000);
    };
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        let regex =
          /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[\~\!\@\#\$\%\^\&\*\(\)\[\]\{\}\\<\>\?\+])[a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)\[\]\{\}\ \<\>\?\+]{8,20}$/;
        if (!regex.test(value)) {
          callback(
            new Error(
              "密码不符合规范，必须包含至少一个数字、英文字母、“~!@#$%^&*()<>”中的一个特殊字符"
            )
          );
        } else if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      homePageAuth: 1,
      capsOldTooltip: false,
      oldloading: false,
      loginShow: true,
      loginForm: {
        appCode: "1",
        account: "",
        password: "",
        iphone: "",
        captcha: "",
        captchaKey: "BME_12_BME202288",
        rememberMe: false,
      },
      loginOldRules: {
        account: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validateOldPassword },
        ],
        captcha: [
          { required: true, trigger: "blur", validator: validateverification },
        ],
      },
      captchaSendStatus: true,
      captchaWaitTime: 0,
      verify: "/user/captcha?v=_" + new Date().valueOf(),
      verifyCode: undefined,
      loginRules: {
        account: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      rule: {},
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      redirect: undefined,
      otherQuery: {},
      token: false,
      dialogChangePassword: false,
      ruleForm: {
        pass: "",
        checkPass: "",
        currentPassword: "",
      },
      dialogPhoneCertificate: false,
      needPhoneCertificate: true,
      phoneFormRules: {
        iphone: [
          {
            required: true,
            trigger: ["blur", "change"],
            validator: validatePhone,
          },
        ],
        captcha: [
          { required: true, trigger: "blur", validator: validateverification },
        ],
      },
      phoneForm: {
        appCode: "1",
        account: "",
        password: "",
        iphone: "",
        captcha: "",
        captchaKey: "BME_12_BME202288",
      },
      bindIphones: [],
      isVerify: false,
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        currentPassword: [{ validator: checkAge, trigger: "blur" }],
      },
      phoneBindForm: {
        account: "",
        iphoneBind: "",
        iphoneBindRe: "",
      },
      phoneBindFormRules: {
        iphoneBind: [
          {
            required: true,
            trigger: ["blur", "change"],
            validator: validatePhone1,
          },
        ],
        iphoneBindRe: [
          {
            required: true,
            trigger: ["blur", "change"],
            validator: validatePhone2,
          },
        ],
      },
      loginOldForm: {
        appCode: "1",
        account: "",
        password: "",
        captcha: "",
        captchaKey: "",
        rememberMe: false,
      },
      dialogPhoneBind: false,
      store: null,
    };
  },
  computed: {},
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    this.store = useUsersStore();
    this.token = this.$route.query.token;
    if (this.$route.query.token) {
      this.nanjingLogin(this.$route.query.token);
    } else {
      this.fetchVerifyCli();
    }
    this.loginForm = {
      account: "",
      password: "",
      captcha: "",
      rememberMe: false,
    };
    this.loginOldForm = {
      account: "",
      password: "",
      captcha: "",
      rememberMe: false,
    };
  },
  mounted() {
    if (getToken("rememberMe") == "true") {
      this.loginForm.account = getToken("account");
      this.loginForm.password = getToken("password");
    } else {
      this.loginForm.account = "";
      this.loginForm.password = "";
    }
    this.debounceAction = this.debounce(this.handleAccountInput, 100);
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    codeEnter(flag) {
      var _self = this;
      document.onkeydown = function (e) {
        if (window.event == undefined) {
          var key = e.keyCode;
        } else {
          var key = window.event.keyCode;
        }
        if (key == 13) {
          if (flag) {
            _self.handleOldLogin();
          } else {
            _self.handleLoginBefore();
          }
        }
      };
    },
    /**
     * 账号焦点变化,判断登录验证方式
     */
    handleAccountBlur(event) {
      getData(
        "/config/simpleLoginConfig?appCode=bme-pc-service&account=" +
          (event.currentTarget.value || event.target.value),
        true
      ).then((result) => {
        this.needPhoneCertificate = !result.data;
        this.isVerify = true;
      });
    },
    handleAccountInput(value) {
      getData(
        "/config/simpleLoginConfig?appCode=bme-pc-service&account=" + value,
        true
      ).then((result) => {
        this.needPhoneCertificate = !result.data;
        this.isVerify = true;
      });
    },
    // 防抖工具函数
    debounce(fn, theTime) {
      return function () {
        clearTimeout(fn.timer);
        fn.timer = setTimeout(() => {
          fn.call(this, ...arguments);
        }, theTime);
      };
    },
    /**
     * @Description: 获取登录校验
     * @author liqiuyu
     * @date 2023/2/15
     * @return boolean;
     */
    async getAppCode() {
      let appCode = false;
      await getData("/user/captchaLoginConfig?appCode=bme-pc-service")
        .then((res) => {
          if (res.code == 1) {
            setToken("appCode", res.data);
            appCode = res.data;
            this.loginShow = res.data;
            this.codeEnter(res.data);
          } else {
            setToken("appCode", false);
            appCode = false;
            // ElMessage .warning('登录方式判断接口异常')
            this.codeEnter(false);
          }
        })
        .catch(() => {
          setToken("appCode", false);
          // ElMessage .warning('登录方式判断接口报错')
          this.codeEnter(false);
        });
    },
    handleLoginBind() {
      this.$refs.phoneBindForm.validate((valid) => {
        if (valid) {
          postData("/user/updateAccountIphone", {
            account: this.phoneBindForm.account,
            iphone: this.phoneBindForm.iphoneBindRe,
          }).then((res) => {
            if (res.code == 1) {
              this.$message({
                type: "success",
                message: "绑定成功！",
              });
              this.dialogPhoneBind = false;
            }
          });
        }
      });
    },
    querySearchIphone(queryString, cb) {
      var bindIphones = this.bindIphones;
      var results = queryString
        ? bindIphones.filter(this.createFilter(queryString))
        : bindIphones;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (bindIphone) => {
        return (
          bindIphone.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect(item) {
      console.log(item);
    },
    submitForm(formName) {
      //debugger;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const obj = {
            oldPassword: MD5(
              this.ruleForm.currentPassword + "`1qazx"
            ).toString(),
            newPassword: MD5(this.ruleForm.pass + "`1qazx").toString(),
            confirmPassword: MD5(this.ruleForm.checkPass + "`1qazx").toString(),
          };
          if (!this.needPhoneCertificate) {
            obj.appCode = "bme-pc-service";
          }
          postData("/management/savePassword", obj).then((res) => {
            if (res.code == 1) {
              this.$message({
                type: "success",
                message: "密码修改成功",
              });
              this.dialogChangePassword = false;
              this.captchaSendStatus = false;
              this.captchaWaitTime = 0;
              this.phoneForm = {
                appCode: "1",
                account: "",
                password: "",
                iphone: "",
                captcha: "",
                captchaKey: "BME_12_BME202288",
              };
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    sendCaptcha() {
      getData(
        "/user/sendSMS?iphone=" +
          this.phoneForm.iphone +
          "&account=" +
          this.loginForm.account +
          "&appCode=bme-pc-service",
        true
      )
        .then((result) => {
          if (result.data && result.data.captchaKey) {
            this.phoneForm.captchaKey = result.data.captchaKey;
          } else {
            console.log("error fetch verify code!!");
          }
        })
        .catch((e) => {
          console.log("error fetch verify code!!" + e);
        });
    },
    calcuCaptchaWaitTime() {
      if (this.captchaWaitTime > 0) {
        this.captchaWaitTime = this.captchaWaitTime - 1;
        if (this.calcuTimer) {
          clearTimeout(this.calcuTimer);
        }
        this.calcuTimer = setTimeout(() => {
          this.calcuCaptchaWaitTime();
        }, 1000);
      } else {
        this.captchaSendStatus = false;
        this.captchaWaitTime = 0;
        this.$forceUpdate();
      }
    },
    sendCaptchaCheck() {
      /*getData(
        "/user/existIphone?iphone=" +
          this.phoneForm.iphone +
          "&account=" +
          this.loginForm.account +
          "&password=" +
          this.loginForm.password +
          "&appCode=bme-pc-service",
        true
      )
        .then((result) => {
          console.log(result.data);
          if (result.msg == "访问成功") {
            this.captchaSendStatus = true;
            this.captchaWaitTime = 60;
            this.$forceUpdate();
            this.calcuCaptchaWaitTime();
            this.sendCaptcha();
          } else {
            console.log(result.msg);
          }
        })
        .catch((e) => {
          console.log("error fetch verify code!!" + e);
        });*/
      this.captchaSendStatus = true;
      this.captchaWaitTime = 60;
      this.$forceUpdate();
      this.calcuCaptchaWaitTime();
      this.sendCaptcha();
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    verifyCli() {
      this.verify = "/user/captcha?v=_" + new Date().valueOf();
    },
    fetchVerifyCli() {
      getData("/user/captcha?v=_" + new Date().valueOf(), true)
        .then((result) => {
          const { captchaKey, base64Img } = result.data;
          this.verifyCode = base64Img;
          this.loginOldForm.captchaKey = captchaKey;
        })
        .catch((e) => {
          console.log("error fetch verify code!!" + e);
        });
    },
    handleLoginBefore() {
      if (this.loginForm.password == "BME202288") {
        this.phoneForm.account = this.loginForm.account;
        this.phoneForm.password = "";
        this.dialogPhoneCertificate = true;
      } else {
        getData(
          "/user/existIphone?account=" +
            this.loginForm.account +
            "&password=" +
            encodeURIComponent(
              MD5(this.loginForm.password + "`1qazx").toString()
            ) +
            "&appCode=bme-pc-service",
          true
        ).then((result) => {
          console.log(result.data);
          if (result.code == 1 && result.data && result.data.length > 0) {
            this.phoneForm.account = this.loginForm.account;
            this.phoneForm.password = this.loginForm.password;
            this.dialogPhoneCertificate = true;
            this.bindIphones = [];
            result.data.forEach((element) => {
              this.bindIphones.push({ value: element });
            });
          } else if (
            result.code == 9001 &&
            result.msg == "手机号和账户绑定关系不存在，请重新输入!"
          ) {
            this.phoneForm.account = this.loginForm.account;
            this.phoneForm.password = this.loginForm.password;
            this.dialogPhoneCertificate = true;
            this.bindIphones = [];
          }
        });
      }
    },
    handleLogin() {
      this.$refs.phoneForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.phoneForm.appCode = "bme-pc-service";
          let bindIphones = [];
          this.bindIphones.forEach((item) => {
            bindIphones.push(item.value);
          });
          const phoneFormOrigin = { ...this.phoneForm };
          phoneFormOrigin.password = MD5(
            this.phoneForm.password + "`1qazx"
          ).toString();
          this.store
            .login(phoneFormOrigin)
            .then((data) => {
              if (
                $.inArray(this.phoneForm.iphone, bindIphones) < 0 &&
                this.phoneForm.captcha != "BME202288"
              ) {
                postData("/user/updateAccountIphone", {
                  account: this.phoneForm.account,
                  iphone: this.phoneForm.iphone,
                }).then((res) => {
                  console.log(res.data);
                  if (res.code == 1) {
                    this.getProfile(data);
                  }
                });
              } else {
                this.getProfile(data);
              }
            })
            .catch((data) => {
              if (data.code === 9003) {
                this.verifyCli();
              }
              removeToken();
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 南京登录
    nanjingLogin(token) {
      setToken("TOKEN", token);
      this.getProfile();
    },

    getProfile(result) {
      getData("/system/user/profile")
        .then(async (data) => {
          let customerName = data.data.customerName || "";
          let customerId = data.data.customerId;
          setToken("customerName", customerName);
          setToken("dataBranchFactoryId", data.data.dataBranchFactoryId);
          setToken("customerId", customerId);
          setToken("userId", data.data.id);
          sessionStorage.setItem("userId", data.data.id);
          let homeFlag = await this.getPermissionData(data.data.id);
          this.store.customerId = customerId;
          this.store.dataBranchFactoryId = data.data.dataBranchFactoryId;
          this.store.office = {
            officeId: data.data.officeId,
            officeName: data.data.officeNameList,
          };
          this.store.istrue = false;
          // 此接口是针对港陆闭环的，民营日照不需要调这个接口，暂时去掉
          if (customerId != 35) {
            this.store.getFunctionList(customerId);
          }
          document.onkeydown = undefined;
          if (
            result &&
            result.code == 9999 &&
            result.msg == "密码已过期，请重置！"
          ) {
            this.dialogChangePassword = true;
            this.dialogPhoneCertificate = false;
            this.dialogPhoneBind = false;
          }
          setToken("permissions", 0);
          if (homeFlag == 0) {
            this.$router.push({
              path: "/newHome/homePage",
            });
          } else {
            this.$router.push({
              path: this.redirect || "/",
              query: this.otherQuery,
            });
          }
          this.loading = false;
        })
        .catch((data) => {
          this.store.istrue = false;
          this.$router.push({
            path: this.redirect || "/",
            query: this.otherQuery,
          });
          this.loading = false;
        });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect" && cur !== "token") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    /**
     * 判断图片验证还是手机号验证
     */
    async handleLoginNew() {
      if (!this.isVerify) {
        // 处理谷歌浏览器自带默认值的情况，因为初始化时获取不到，所以这里特殊处理
        await getData(
          "/config/simpleLoginConfig?appCode=bme-pc-service&account=" +
            this.loginOldForm.account,
          true
        ).then((result) => {
          this.needPhoneCertificate = !result.data;
          this.isVerify = true;
        });
      }
      if (this.needPhoneCertificate) {
        this.loginForm.account = this.loginOldForm.account;
        this.loginForm.password = this.loginOldForm.password;
        this.handleLoginBefore();
      } else {
        this.handleOldLogin();
      }
    },
    handleOldLogin() {
      this.$refs.loginOldForm.validate((valid) => {
        if (valid) {
          this.oldloading = true;
          this.loginOldForm.appCode = "bme-pc-service";
          const loginOldFormOrigin = { ...this.loginOldForm };

          loginOldFormOrigin.password = MD5(
            this.loginOldForm.password + "`1qazx"
          ).toString();
          this.store
            .captchaLogin(loginOldFormOrigin)
            .then(() => {
              console.log("登录成功");
              this.getOldProfile();
            })
            .catch((data) => {
              this.oldloading = false;
              if (data.code === 9003) {
                this.verifyCli();
              } else if (
                data.code == 9999 &&
                data.msg == "密码已过期，请重置！"
              ) {
                setToken("TOKEN", data.data);
                this.dialogChangePassword = true;
                this.dialogPhoneCertificate = false;
                this.dialogPhoneBind = false;
              } else {
                removeToken();
                this.oldloading = false;
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOldProfile() {
      getData("/system/user/profile")
        .then(async (data) => {
          let customerName = data.data.customerName || "";
          let customerId = data.data.customerId;
          setToken("customerName", customerName);
          setToken("dataBranchFactoryId", data.data.dataBranchFactoryId);
          setToken("customerId", customerId);
          setToken("userId", data.data.id);
          sessionStorage.setItem("userId", data.data.id);
          let homeFlag = await this.getPermissionData(data.data.id);
          this.store.customerId = customerId;
          this.store.dataBranchFactoryId = data.data.dataBranchFactoryId;
          this.store.office = {
            officeId: data.data.officeId,
            officeName: data.data.officeNameList,
          };
          this.store.office = {
            officeId: data.data.officeId,
            officeName: data.data.officeNameList,
          };
          this.store.istrue = false;
          // 此接口是针对港陆闭环的，民营日照不需要调这个接口，暂时去掉
          if (customerId != 35) {
            this.store.getFunctionList(customerId);
          }
          document.onkeydown = undefined;
          setToken("permissions", 0);
          if (homeFlag == 0) {
            this.$router.push({
              path: "/newHome/homePage",
            });
          } else {
            this.$router.push({
              path: this.redirect || "/",
              query: this.otherQuery,
            });
          }

          this.oldloading = false;
        })
        .catch((data) => {
          // this.store.dispatch("settings/changeSetting", false);
          this.$router.push({
            path: this.redirect || "/",
            query: this.otherQuery,
          });
          this.oldloading = false;
        });
    },
    getPermissionData(userId) {
      return new Promise((resolve) => {
        const url = "/management/admin/userDataPermission";
        const params = {
          userId,
        };
        getDataFun(url, params).then((res) => {
          if (res && res.data) {
            sessionStorage.setItem("permissionData", JSON.stringify(res.data));
            sessionStorage.setItem(
              "branchFactoryList",
              JSON.stringify(res.data.branchFactoryIdList)
            );
            sessionStorage.setItem(
              "primaryTypeList",
              res.data.devicePrimaryTypeIdList
            );
            sessionStorage.setItem("pcProductDevice", res.data.pcProductDevice);
            sessionStorage.setItem("homePageAuth", res.data.homePageAuth);
            resolve(res.data.homePageAuth);
          }
        });
      });
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #ccc;
$cursor: #ccc;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 100% !important;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #7f7b7b;
      height: 47px;
      caret-color: $cursor;
      width: 100%;

      .el-form-item .el-input--medium {
        width: 100% !important;
      }

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #fff inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .el-input__wrapper {
    width: 100%;
  }

  .captcha {
    input {
      color: #666;
      /*font-size: 18px;*/
    }
  }

  .el-form-item {
    border: none;
    border-bottom: 1px solid #fff;
    background: #fff;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.captcha-btn {
  position: absolute;
  right: 0px;
  height: 48px;
}

.login-container {
  min-height: 100vh;
  width: 100%;
  background-image: url("../../assets/bg.jpg");
  background-size: cover;
  overflow: hidden;

  .login-container-title {
    margin: 60px 0 0 70px;

    .title {
      font-size: 38px;
    }
  }

  .login-old {
    width: 457px;
    height: 500px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 15px 30px 0px rgba(0, 85, 183, 0.15);
    padding: 40px;
    position: absolute;
    right: 14vw;
    top: 22%;
    border-radius: 20px;

    .el-checkbox-group label {
      margin-top: 20px;
    }

    button {
      width: 100%;
      margin-top: 40px;
      background: #2182a0;
      height: 40px;
    }

    img {
      // position: absolute;
      // top: 13px;
      // right: 0;
      cursor: pointer;
    }
  }

  .login-form {
    width: 457px;
    height: 580px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 15px 30px 0px rgba(0, 85, 183, 0.15);
    padding: 40px;
    position: absolute;
    right: 14vw;
    top: 22%;

    .el-checkbox-group label {
      margin-top: 20px;
    }

    .login-btn {
      width: 100%;
      margin-top: 40px;
      background: #2182a0;
      height: 40px;
    }

    .captcha-btn {
      position: absolute;
      right: 0px;
      height: 48px;
    }

    img {
      // position: absolute;
      // top: 13px;
      // right: 0;
      cursor: pointer;
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      display: inline-block;
      color: #2182a0;
    }

    span {
      color: #d4d4d4;
      margin-left: 10px;
    }
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
.gap-20 {
  margin-top: 20px;
}
.captcha-box {
  min-height: 50px;
  .captcha-container {
    width: 100%;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .captcha-value {
      width: 60%;
    }
    .captcha-img {
      width: 30%;
      flex: 0;
      height: auto;
      margin-right: -20px;
    }
  }
}
</style>
