<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="off"
          />
        </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"
              autocomplete="off"
            />
          </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="35%"
    >
      <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-input
            class="inline-input"
            ref="iphone"
            name="iphone"
            v-model="phoneForm.iphone"
            :fetch-suggestions="querySearchIphone"
            placeholder="请输入手机号码"
            @select="handleSelect"
          >
            <!-- <template #append>
              <el-button
                :disabled="captchaSendStatus"
                @click.prevent="sendCaptchaCheck()"
              >
                {{
                  "发送验证码" +
                  (captchaWaitTime > 0 ? "(" + captchaWaitTime + ")" : "")
                }}
              </el-button>
            </template> -->
          </el-input>
          <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";
import { encryptUtf8ToBase64, encryptBase64ToUtf8 } from "@/utils/tools.js";
import { startPermissionCheck } from '@/utils/permissionChecker';
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 &&
        !bindIphones.includes(value)
      ) {
        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: getToken("rememberMe") == "true" ? true : 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: getToken("rememberMe") == "true" ? true : false,
    };
  },
  mounted() {
    if (getToken("rememberMe") == "true") {
      this.loginForm.account = getToken("account");
      this.loginForm.password = getToken("password");
    } else {
      this.loginForm.account = "";
      this.loginForm.password = "";
    }
    if (getToken("rememberMe") == "true") {
      this.loginOldForm.account = encryptUtf8ToBase64(getToken("account"));
      this.loginOldForm.password = encryptUtf8ToBase64(getToken("remmberPWS"));
    } else {
      this.loginOldForm.account = "";
      this.loginOldForm.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-dc-tom-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-dc-tom-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-dc-tom-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) {
    },
    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-dc-tom-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 {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    sendCaptcha() {
      getData(
        "/user/sendSMS?iphone=" +
          this.phoneForm.iphone +
          "&account=" +
          this.loginForm.account +
          "&appCode=bme-dc-tom-service",
        true
      )
        .then((result) => {
          if (result.data && result.data.captchaKey) {
            this.phoneForm.captchaKey = result.data.captchaKey;
          } else {
          }
        })
        .catch((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() {
      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) => {
        });
    },
    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-dc-tom-service",
          true
        ).then((result) => {
          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-dc-tom-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 (
                !bindIphones.includes(this.phoneForm.iphone) &&
                this.phoneForm.captcha != "BME202288"
              ) {
                postData("/user/updateAccountIphone", {
                  account: this.phoneForm.account,
                  iphone: this.phoneForm.iphone,
                }).then((res) => {
                  if (res.code == 1) {
                    this.getProfile(data);
                  }
                });
              } else {
                this.getProfile(data);
              }
            })
            .catch((data) => {
              if (data.code === 9003) {
                this.verifyCli();
              }
              removeToken();
              this.loading = false;
            });
        } else {
          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);
          setToken("userName", data.data.name);
          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);
          this.getMenuList(data.data.id);
          this.loading = false;
        })
        .catch((data) => {
          this.store.istrue = false;
          this.getMenuList(1);
          // 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-dc-tom-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) {
          // 记住密码
          setToken("account", encryptBase64ToUtf8(this.loginOldForm.account));
          setToken(
            "remmberPWS",
            encryptBase64ToUtf8(this.loginOldForm.password)
          );
          this.oldloading = true;
          this.loginOldForm.appCode = "bme-dc-tom-service";
          const loginOldFormOrigin = { ...this.loginOldForm };

          loginOldFormOrigin.password = MD5(
            this.loginOldForm.password + "`1qazx"
          ).toString();
          this.store
            .captchaLogin(loginOldFormOrigin)
            .then(() => {
              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 {
          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);
          setToken("userName", data.data.name);
          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);
          this.getMenuList(data.data.id);
          // 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.getMenuList(1);
          // this.$router.push({
          //   path: this.redirect || "/",
          //   query: this.otherQuery,
          // });
          this.oldloading = false;
        });
    },

    getMenuList(userId) {
      getData(
        "/system/permission?appCode=bme-dc-tom-service&userId=" + userId,
        true
      )
        .then((result) => {
          sessionStorage.setItem("menuList", JSON.stringify(result.data));
          this.$router.push('/dashboard');
        })
        .catch((e) => {
        });
    },
    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: 95%;
  }
  .dialogChangePasswordform {
    .el-input {
      display: flex !important;
    }
  }

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

  .el-form-item {
    border: none;
    border-bottom: 1px solid #fff;
    background: #fff;
    padding-right: 10px;
    box-sizing: border-box;
  }

}

</style>

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

.captcha-btn {
  position: absolute;
  top: 1px;
  right: 0;
  height: calc(100% - 2px);
  border-top: none;
  border-bottom: none;
}

.login-container {
  min-height: 100vh;
  width: 100%;
  background: url("../../assets/bg.png") no-repeat;
  background-size: 100% 500px;
  background-position: calc(50% - 640px) center;
  background-color: #000;
  overflow: hidden;

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

    .title {
      font-size: 38px;
      color: #fff;
      text-align: right;
      padding-right: 4%;
    }
  }

  .login-old {
    width: 457px;
    height: 500px;
    // background: rgba(255, 255, 255, 1);
    background: #191c21;
    box-shadow: 0px 15px 30px 0px rgba(255, 255, 255, 0.2);
    padding: 40px;
    position: absolute;
    right:4%;
    top: calc(50% - 250px);
    border-radius: 4px;

    .el-checkbox-group label {
      margin-top: 20px;
    }
    button {
      width: 100%;
      margin-top: 40px;
      background: #181d21 !important;
      color: #36f1cd !important;
      border: 1px solid #2a2a2a !important;
      height: 40px;
      transition: border 0.5s ease;
    }
    button:hover {
      border: 1px solid rgba(54, 241, 205, 0.7) !important;
    }

    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;
    }
    .el-form-item {
      border-bottom: 0 !important;
      background: transparent !important;
    }
    

    .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: #36f1cd;
    }

    span {
      color: #29ad93;
      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 {
      max-width: 30%;
      flex: 0;
      height: auto;
      // margin-right: -20px;
    }
  }
}
</style>
