<template>
  <div class="page">
    <main-page :isRegister="true">
      <template v-slot:formBox>
        <el-form ref="ruleForm" size="large" class="form-box" :model="loginForm" :rules="rules">
          <div class="title-container">
            <a href="#" class="span-a">欢迎登录</a>
            <!-- <a href="#" class="span-aa">注册</a> -->
          </div>
          <el-form-item prop="username">
            <label name="账号">账号</label>
            <el-input class="el-aa" v-model="loginForm.username" placeholder="请输入用户名" type="text" auto-complete="on" />
          </el-form-item>
          <el-form-item prop="password">
            <label name="密码">密码</label>
            <el-input v-model="loginForm.password" placeholder="请输入密码" type="password" auto-complete="on" />
          </el-form-item>
          <el-form-item prop="identifyCode">
            <div class="input-field">
              <label name="验证码">验证码</label>
              <div class="div-input">
                <el-input style="width:60%;margin-right:5px;" v-model.trim='loginForm.identifyCode' placeholder="验证码" @keyup.enter.native="submit('ruleForm')">
                </el-input>
                <div class="identi_img" style="width:40%;">
                  <img :src="src" @click="getCode()" style="width:100%;height:100%;" />
                </div>
              </div>

            </div>
          </el-form-item>
          <el-form-item class="btn-box" style="padding-top:10px;">
            <el-button class="btn" :loading="loading" @click="submit">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </template>
    </main-page>
    <registrationdialog :jurisdiction="jurisdiction" :machineRules="machineRules" :ruleForm="ruleForm"
      @cancel="cancel" />
  </div>
</template>

<script>
import CryptoJS from 'crypto-js';
import mainPage from "./components/main.vue";
// 改为使用统一的auth方法：
import { setToken } from "@/utils/auth";
import registrationdialog from "./components/registrationdialog.vue";
import {
  getDbMac2,
  getLocalMac,
  saveDbMac,
  titleSuper,
  closeTitle,
} from "@/api/user";
import { clearObjValue, message } from "@/utils/common";
import { checkCode3, checkCodeImage, login, registerUser,getconfig} from "@/api/login";
import localStronge from "@/api/localData";
import { validUsername } from "@/utils/validate";
import Layout from "@/layout";
import websocket from "../../mixins/websocket";
import { constantRoutes } from "@/router";
export default {
  mixins: [websocket],
  data() {
    return {
      identiCode: "",
      src: "",
      loginForm: {
        username: "",
        password: "",
        identifyCode:""
      },
      sysConfig:{},
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
        ],
        identifyCode: [{
            required: true,
              message: "请输入验证码",
            trigger: "blur",
        }],
      },
      loading: false,
      jurisdiction: false,
      machineRules: {
        machineCode: [
          {
            required: true,
            message: "请输入机器码",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入注册码",
            trigger: "blur",
          },
        ],
      },
      ruleForm: {
        machineCode: "",
        password: "",
        roleId: "",
      },
      codeValue:''
    };
  },
  components: {
    mainPage,
    registrationdialog,
  },
  computed: {
    routes: {
      get() {
        return this.$store.state.user.routes;
      },
      set(val) {
        this.$store.state.user.routes = val;
      },
    },
    roleName: {
      get() {
        return this.$store.state.user.roleName;
      },
      set(val) {
        this.$store.state.user.roleName = val;
      },
    },
    name: {
      get() {
        return this.$store.state.user.name;
      },
      set(val) {
        this.$store.state.user.name = val;
      },
    },

  },
  methods: {
    getCode() {
      this.getIdentifyCode();
    },
    getIdentifyCode() {
      checkCode3().then(res => {
        let base64Data = res.body.base64String;
        this.src = base64Data;
        // 验证码
        this.codeValue = res.body.code;
      })
    },
    getBase64(data){
      return new Promise((resolve, reject) => {
        const blob = new Blob([data], { type: 'image/png' }) // 必须指定type类型
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = () => resolve(reader.result)
        reader.onerror = (error) => reject(error)
      })
    },
    cancel() {
      this.jurisdiction = false;
    },
    getMac2() {
      getDbMac2()
        .then((res) => {
          this.jurisdiction = false;
        })
        .catch((err) => {
          this.jurisdiction = true;
        });
    },
    getLocalMac() {
      getLocalMac().then((res) => {
        this.ruleForm.machineCode = res;
      });
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const encryptedPassword = CryptoJS.MD5(this.loginForm.password).toString();
          let param = {
            username: this.loginForm.username,
            password: encryptedPassword,
            checkCode:this.loginForm.identifyCode
          };
          if(this.loginForm.identifyCode !=this.codeValue){
            message('warning','输入的验证码不正确',3000);
            return;
          }
          this.loading = true;
          debugger;
          login(param)
            .then((res) => {
              if (res.success) {
                let menu = res.body.userRole.roles[0].menus;
                this.sumbitFuncTypeCode(menu);
                localStronge.setMenus(menu);
                sessionStorage.setItem("username", this.loginForm.username);
                sessionStorage.setItem(
                  "userCHname",
                  res.body.userRole.user.userChnName
                );
                sessionStorage.setItem("userid", res.body.userRole.user.id);
                sessionStorage.setItem("roleid", res.body.userRole.roles[0].id);
                sessionStorage.setItem(
                  "passWorld",
                  res.body.userRole.user.password
                );
                sessionStorage.setItem(
                  "roles",
                  res.body.userRole.roles[0].roleName
                );
                sessionStorage.setItem('token',res.body.token);
                setToken(res.body.token)
                this.name = res.body.userRole.user.username;
                this.roleName = res.body.userRole.roles[0].roleName;
                this.$router.push({
                  path: "/",
                });

                this.getTitleSuper();
                if (!this.socket) {
                  this.init();
                }
              }
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    getTitleSuper() {
      titleSuper().then((res) => {
        if (res.body.total) {
          const h = this.$createElement;
          this.$notify({
            title: "您有监督指导意见待查看!",
            type: "success",
            // message: "您有监督指导意见带查收!",
            duration: 0,
            // position: 'bottom-right',
            offset: 20,
            dangerouslyUseHTMLString: true,
            message: h("p", null, [
              "",
              h("a", [
                h(
                  "el-button",
                  {
                    style: {
                      float: "right",
                    },
                    attrs: {
                      size: "mini",
                      type: "primary",
                    },
                    on: {
                      click: this.closeNotify, // 路由加载之后，调用关闭消息弹窗的方法
                    },
                  },
                  "我已阅读 前往查看"
                ),
              ]),
            ]),
          });
        }
      });
    },
    closeNotify() {
      closeTitle().then((res) => {
        this.$notify.closeAll();
        this.$router.push("/supervise-management/supervise-guide");
      });
    },
    sumbitFuncTypeCode(data) {
      let dashboard = [
        {
          path: "/",
          component: Layout,
          redirect: "/dashboard",
          children: [
            {
              path: "/dashboard",
              name: "Dashboard",
              component: () => import("@/views/dashboard/index"),
              meta: {
                title: "首页",
                icon: "dashboard",
                affix: true,
              },
            },
          ],
        },
      ];
      let TypeList = {};
      let idList = {};
      let list = [];
      let OtherRouter = [];
      constantRoutes.forEach((item) => {
        if (
          item.path === "/login" ||
          item.path === "/404" ||
          item.path === "*"
        ) {
          OtherRouter.push(item);
        }
      });
      data.forEach((ele) => {
        let obj = {};
        obj.children = [];

        // if (ele.childs && !ele.childs.length) {
        if (!ele.childs || !ele.childs.length) {
          idList[ele.url] = ele.id;
          let menus = {};
          menus.path = ele.url;
          menus.meta = {
            title: ele.name,
            noCache: true,
            icon: ele.icon,
          };
          obj.children.push(menus);
          if (ele.url && ele.funcTypeCode) {
            TypeList[ele.url] = ele.funcTypeCode;
          }
        } else {
          obj.path = ele.url;
          obj.component = Layout;
          obj.alwaysShow = true;
          obj.meta = {
            title: ele.name,
            icon: ele.icon,
            noCache: true,
          };
          ele.childs.forEach((element) => {
            idList[element.url] = element.id;
            let menu = {};
            menu.path = element.url;
            menu.children = [];
            menu.meta = {
              title: element.name,
              noCache: true,
              icon: element.icon,
            };
            if (element.childs != null && element.childs.length) {
              element.childs.forEach((aea) => {
                idList[aea.url] = aea.id;
                if (aea.childs === null) {
                  let me = {};
                  me.path = aea.url;
                  me.meta = {
                    title: aea.name,
                    noCache: true,
                    icon: aea.icon,
                  };
                  menu.children.push(me);
                  if (aea.url && aea.funcTypeCode) {
                    TypeList[aea.url] = aea.funcTypeCode;
                  }
                }
              });
            } else {
              if (element.url && element.funcTypeCode) {
                TypeList[element.url] = element.funcTypeCode;
              }
            }
            obj.children.push(menu);
            // idList[element.url] = element.id
          });
        }
        list.push(obj);
      });
      this.routes = [...dashboard, ...list, ...OtherRouter];
      sessionStorage.setItem("routes", JSON.stringify(this.routes));
      sessionStorage.setItem("funcTypeCodeList", JSON.stringify(TypeList));
      sessionStorage.setItem("routerIdList", JSON.stringify(idList));
      message("success", "登录成功", 500);
      this.$router.push({
        path: "/dashboard",
      });
    },
  },
  created() {
    this.getIdentifyCode();
    //this.getMac2();
    //this.getLocalMac();
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100%;

  .form-box {
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 0 10px 10px 0;
    padding: 5px 35px 35px;
    box-shadow: 0 0 10px rgba(0,0,0,.2);

    .el-form-item {
      margin-bottom: 10px;
      label{
        font-size:14px;
        color:#b1b1b1;
      }
      .input-field{
        .div-input{
          display:flex;
          justify-content: center;
          height:40px;
          .identi_img{
            border:1px solid #dcdfe6;
            padding:0 5px;
            border-radius: 5px;
          }
        }

      }
      .el-aa{
        ::v-deep
          .el-input__inner{
            background-color:#fff;
            &:focus{
              border:1px solid #53a8ff;
            }
        }
      }

    }

    .title-container {
      color: #333;
      font-size: 28px;
      padding-bottom: 10px;
      padding-top: 20px;
      display:flex;
      justify-content: space-between;
      .span-aa{
        font-size: 14px;
        color: #195cd4;
      }
      .span-a{
        text-align: left;
        font-size: 20px;
        letter-spacing: normal;
        color: #000;
        font-weight: 400;
        padding-bottom: 5px;
        cursor:pointer;
      }
      .title {
        margin: 20px 0 30px;
      }
    }

    .btn-box {
      text-align: center;

      .btn {
        background:#409eff;
        color: #fff;
        letter-spacing: 8px;
        border: none;
        width: 100%;
        opacity: 0.9;
        font-size: 18px;

        &:hover {
          opacity: 1;
        }
      }
    }
  }
}
</style>
