<template>
  <div class="home">
    <HomeSide v-if="ifShowHomeSide" :key="sideKey" />

    <div class="home-header">
      <div v-if="ifShowHomeSide" class="header-breadcrumb">
        <LinkTitles :key="Math.random()" />
      </div>
      <ul class="header-menu">
        <li class="header-menu-item header-menu-org" title="机构名称">
          <i class="icon icon-users"></i>{{ user.rootOrgName }}
        </li>
        <li
          class="header-menu-item header-menu-user"
          title="个人信息管理"
          @click="openUserDialog"
        >
          <i class="icon icon-user"></i>{{ user.displayName }}
        </li>
        <li
          class="header-menu-item header-menu-logout"
          title="退出系统"
          @click="logout"
        >
          <i class="icon icon-logout"></i>
        </li>
      </ul>
    </div>

    <div class="home-body">
      <div class="home-main">
        <router-view class="main-content"></router-view>

        <div class="home-footer">
          Copyright &copy; 2021
          <a href="https://www.qmth.com.cn" target="_block">启明泰和</a>.<a
            href="https://beian.miit.gov.cn/"
            target="_blank"
            >鄂ICP备12000033号-13</a
          >
        </div>
      </div>
    </div>
    <!-- 添加用户信息弹出框 -->
    <el-dialog
      title="个人信息"
      width="620px"
      :visible.sync="userDialog"
      :modal="false"
      append-to-body
      custom-class="side-dialog"
      @close="() => $refs.passForm.clearValidate()"
    >
      <el-tabs v-model="userTabName">
        <el-tab-pane label="用户权限" name="first">
          <el-form :inline="true" label-position="right" label-width="90px">
            <el-tag
              v-for="role in user.roleList"
              :key="role.roleId"
              type="primary"
              style="margin-left: 10px; margin-top: 10px"
            >
              {{ role.roleName }}
            </el-tag>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="second">
          <el-form
            ref="passForm"
            inline-message
            class="form-tight"
            :model="passForm"
            :rules="passRules"
            label-width="80px"
          >
            <el-form-item label="密码" prop="pass">
              <el-input
                v-model="passForm.pass"
                type="password"
                class="dialog-input-width"
                auto-complete="off"
                placeholder="请输入密码"
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input
                v-model="passForm.checkPass"
                type="password"
                class="dialog-input-width"
                auto-complete="off"
                placeholder="请输入确认密码"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div v-if="userTabName === 'second'" slot="footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="danger" plain @click="userDialog = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
    <!-- 修改密码 -->
    <el-dialog
      title="修改密码"
      width="650px"
      :lock-scroll="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :visible.sync="passWeakDialog"
      @close="() => $refs.passWeakForm.clearValidate()"
    >
      <el-form
        ref="passWeakForm"
        :inline="true"
        inline-message
        class="form-tight"
        :model="passWeakForm"
        :rules="passWeakRules"
        label-width="80px"
      >
        <el-row>
          <el-form-item label="密码" prop="pass">
            <el-input
              v-model="passWeakForm.pass"
              type="password"
              class="dialog-input-width"
              auto-complete="off"
              placeholder="输入新密码"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input
              v-model="passWeakForm.checkPass"
              type="password"
              class="dialog-input-width"
              auto-complete="off"
              placeholder="再次输入新密码"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            ><span
              >*为保护您的账户安全，请重新录入新密码，以防泄露
            </span></el-form-item
          >
        </el-row>
        <el-row style="margin-left: 80px">
          <el-button type="primary" @click="submitPassWeakForm"
            >确 认</el-button
          >
          <el-button type="danger" plain @click="logout">取消</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from "vuex";
import { USER_SIGNOUT, USER_SIGNIN } from "../../store/user";
import { QUESTION_API } from "@/constants/constants";
import HomeSide from "./HomeSide.vue";
import LinkTitles from "./LinkTitles.vue";

export default {
  name: "Home",
  components: { HomeSide, LinkTitles },
  data() {
    var validatePass = (rule, value, callback) => {
      if (this.passForm.checkPass !== "") {
        this.$refs.passForm.validateField("checkPass");
      }
      callback();
    };
    var validatePass2 = (rule, value, callback) => {
      if (value !== this.passForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePassWeakPass = (rule, value, callback) => {
      if (this.passWeakForm.checkPass !== "") {
        this.$refs.passWeakForm.validateField("checkPass");
      }
      callback();
    };
    var validatePassWeakPass2 = (rule, value, callback) => {
      if (value !== this.passWeakForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    const pwdRule = [
      {
        validator: (rule, value, callback) => {
          if (
            value &&
            (/^([0-9]+|[a-z]+|[A-Z]+)$/.test(value) ||
              !/^[a-zA-Z0-9_]+$/.test(value))
          ) {
            callback(new Error("密码只能大写字母、小写字母、数字至少两种组成"));
          } else {
            callback();
          }
        },
        trigger: "change",
      },
      {
        required: true,
        min: 8,
        max: 16,
        message: "密码只能8-16个字符",
        trigger: "change",
      },
    ];

    return {
      unreadMessageCount: 0,
      userDialog: false,
      userTabName: "first",
      passWeakDialog: false,
      passForm: { pass: "", checkPass: "" },
      passWeakForm: { pass: "", checkPass: "" },
      passRules: {
        pass: [{ validator: validatePass, trigger: "blur" }, ...pwdRule],
        checkPass: [{ validator: validatePass2, trigger: "blur" }, ...pwdRule],
      },
      passWeakRules: {
        pass: [
          { validator: validatePassWeakPass, trigger: "blur" },
          ...pwdRule,
        ],
        checkPass: [
          { validator: validatePassWeakPass2, trigger: "blur" },
          ...pwdRule,
        ],
      },
    };
  },
  computed: {
    ...mapState({ user: (state) => state.user }),
    ...mapState(["currentPaths"]),
    ifShowHomeSide() {
      return this.$route.fullPath.startsWith("/home") === false;
    },
    sideKey() {
      const module = this.$route.fullPath.split("/")[1];
      return module;
    },
  },
  created() {
    if (!this.user.passwordWeak) {
      this.passWeakDialog = true;
    }
  },
  methods: {
    ...mapActions([USER_SIGNOUT, USER_SIGNIN]),

    openMessageHome() {
      this.$router.push({ path: "/home/site-message" });
    },
    changeUnreadMessageCount(count) {
      this.unreadMessageCount = count;
    },
    openUserDialog() {
      this.passForm = { pass: "", checkPass: "" };
      this.userDialog = true;
    },
    //保存密码
    submitForm() {
      this.$refs.passForm.validate((valid) => {
        if (valid) {
          var password = encodeURIComponent(this.passForm.pass);
          var url = QUESTION_API + "/user/password?password=" + password;
          this.$httpWithMsg.put(url).then(() => {
            this.$notify({
              type: "success",
              message: "修改密码成功！",
            });
            this.resetForm();
            this.userDialog = false;
          });
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
    submitPassWeakForm() {
      this.$refs.passWeakForm.validate((valid) => {
        if (valid) {
          var password = encodeURIComponent(this.passWeakForm.pass);
          var url = QUESTION_API + "/user/password?password=" + password;
          this.$httpWithMsg.put(url).then(() => {
            this.$notify({
              type: "success",
              message: "修改密码成功！",
            });
            this.user.passwordWeak = false;
            this.USER_SIGNIN(this.user);
            this.$refs.passWeakForm.resetFields();
            this.passWeakDialog = false;
          });
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
    //重置
    resetForm() {
      this.$refs.passForm.resetFields();
    },
    logout() {
      const orgId = this.user.rootOrgId;
      const getRootOrgId = () => {
        if (location.hostname.includes("qmth.com.cn")) {
          return "";
        } else {
          return "?orgId=" + orgId;
        }
      };

      this.$http
        .post(QUESTION_API + "/auth/logout")
        .then(() => {
          this.USER_SIGNOUT();
          window.name = "";
          this.$router.replace({
            path: "/login" + getRootOrgId(),
          });
        })
        .catch((response) => {
          if (response.status == 500) {
            this.$notify({
              showClose: true,
              message: response.data.desc,
              type: "error",
            });
          }
          this.USER_SIGNOUT();
          window.name = "";
          this.$router.replace({
            path: "/login" + getRootOrgId(),
          });
        });
    },
  },
};
</script>
