<template>
  <div class="layout_wrap">
    <div class="layout_header">
      <div class="header_left">
        <img
          v-if="userInfo.logoPath"
          :src="$api.showImageUrl + userInfo.logoPath"
        />
        <img v-else src="@/assets/img/setting/LOGO.png" />
      </div>
      <div class="header_right">
        <div style="margin-right: 10px" v-if="powerParams.rtype === 2">
          所属区域【{{ belongName }}】
        </div>
        <div style="margin-right: 10px" v-else-if="powerParams.rtype === 3">
          所属学校【{{ belongName }}】
        </div>
        <div class="dope" @click="headerDope" v-if="powerParams.rtype != 1">
          <img class="img1" src="../assets/img/dope.png" />
          <div class="img2" v-if="nreadNum > 0">
            {{ nreadNum }}
          </div>
        </div>
        <Dropdown
          :transfer="true"
          @on-visible-change="userDropdownVisibleChange"
          @on-click="userDropdownSelectChange"
        >
          <div class="right_user_info">
            <div class="user_img">
              <img src="@/assets/img/user.png" />
            </div>
            <div class="user_name">{{ userInfo.aname }}</div>
            <Icon
              :class="['user_drop', userDropdown ? 'arrow_dropdown' : '']"
              type="md-arrow-dropdown"
              :size="20"
            />
          </div>
          <DropdownMenu slot="list">
            <DropdownItem name="1">个人信息</DropdownItem>
            <DropdownItem name="2">修改密码</DropdownItem>
            <DropdownItem name="3">更换手机号</DropdownItem>
            <DropdownItem name="4">退出</DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </div>
    </div>
    <div class="layout_main">
      <router-view></router-view>
    </div>
    <!-- 修改密码 -->
    <Modal
      class="modal_view"
      :mask-closable="false"
      v-model="pwInfo.show"
      title="修改密码"
    >
      <Form
        v-if="pwInfo.show"
        ref="pwInfo"
        :model="pwInfo"
        :rules="rules"
        :label-width="110"
      >
        <FormItem label="原密码" prop="oldpwd">
          <Input v-model="pwInfo.oldpwd" placeholder="请输入原密码"></Input>
        </FormItem>
        <FormItem label="新密码" prop="loginpwd">
          <Input v-model="pwInfo.loginpwd" placeholder="请输入新密码"></Input>
        </FormItem>
        <FormItem label="确认密码" prop="loginpwd1">
          <Input
            v-model="pwInfo.loginpwd1"
            placeholder="请输入确认密码"
          ></Input>
        </FormItem>
      </Form>
      <div
        slot="footer"
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="color: #b50000">
          注：密码必须是6-16位的大小写英文字母、数字组合。
        </div>
        <div>
          <Button @click="pwInfo.show = false">取消</Button>
          <Button @click="savepwInfo()" class="primary_btn" type="primary"
            >保存</Button
          >
        </div>
      </div>
    </Modal>
    <!-- 修改手机号 -->
    <Modal
      class="modal_view"
      :mask-closable="false"
      v-model="phoneInfo.show"
      title="修改手机号"
    >
      <Form
        v-if="phoneInfo.show"
        ref="phoneInfo"
        :model="phoneInfo"
        :rules="rules"
        :label-width="110"
      >
        <FormItem label="原手机号">
          <div style="line-height: 36px">{{ phoneInfo.oldphone }}</div>
        </FormItem>
        <FormItem label="新手机号" prop="phone">
          <Input v-model="phoneInfo.phone" placeholder="请输入新手机号"></Input>
        </FormItem>
        <FormItem label="短信验证码" prop="msgcode">
          <Input
            style="width: calc(100% - 102px)"
            v-model="phoneInfo.msgcode"
            placeholder="请输入短信验证码"
          ></Input>
          <div
            :class="['code_btn', phoneInfo.second === 60 ? '' : 'disabled']"
            @click="getMsgCode()"
          >
            {{
              phoneInfo.second === 60 ? "获取验证码" : `${phoneInfo.second}s`
            }}
          </div>
        </FormItem>
      </Form>
      <div
        slot="footer"
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div style="color: #b50000">
          注：更换手机号码之后，原来的手机号码将无法使用。
        </div>
        <div>
          <Button @click="phoneInfo.show = false">取消</Button>
          <Button @click="savephoneInfo()" class="primary_btn" type="primary"
            >保存</Button
          >
        </div>
      </div>
    </Modal>
    <Spin fix v-if="showLoading" style="background-color: transparent">
      <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
      <div>加载中</div>
    </Spin>
  </div>
</template>

<script>
import { admin_detail, admin_edit_phone, admin_edit_pwd } from "@/api/admin";
import { login_msg_code } from "@/api/login";
import { login_check_login, login_login_out } from "@/api/school";
import { logdoperatemsg_get_nrn } from "@/api/log";
import { pwdCheck, reg } from "@/utils";
export default {
  data() {
    // 重复密码验证
    const pwdAgainCheck = async (rule, value, callback) => {
      if (!reg.test(value)) {
        return callback(new Error("密码格式不正确!"));
      }
      if (this.pwInfo.loginpwd != value) {
        return callback(new Error("两次输入密码不一致！"));
      }
      callback();
    };
    return {
      showLoading: false,
      userDropdown: false,
      nreadNum: 0,
      pwInfo: {
        show: false,
        adminid: "",
        loginpwd: "",
        oldpwd: "",
        rversion: ""
      },
      phoneInfo: {
        show: false,
        timer: null,
        second: 60,
        rversion: "",
        adminid: "",
        oldphone: "",
        phone: "",
        msgcode: ""
      },
      rules: {
        oldpwd: [
          {
            required: true,
            message: "请输入原密码",
            trigger: "blur"
          }
        ],
        loginpwd: [
          {
            required: true,
            validator: pwdCheck,
            trigger: "blur"
          }
        ],
        loginpwd1: [
          {
            required: true,
            validator: pwdAgainCheck,
            trigger: "blur"
          }
        ]
      },
      time1: null,
      userInfo: {}
    };
  },
  watch: {
    $route: {
      handler() {
        if (this.$route.path.includes("home") && this.powerParams.rtype > 1) {
          this.init();
        }
      }
    }
  },
  created() {
    this.userInfo = JSON.parse(
      localStorage.getItem("xh_control_userInfo")
    ).content;
    this.get_check_user();
    this.init();
  },
  computed: {
    // 所属名称
    belongName() {
      let belong = this.$store.state.userPower.belong;
      return belong.length > 0 ? belong[belong.length - 1] : "";
    },
    powerParams() {
      return this.$store.getters.powerParams;
    }
  },
  mounted() {
    this.$EventBus.$on("nreadChange", () => {
      this.nreadNum = this.nreadNum > 0 ? this.nreadNum - 1 : 0;
    });
    this.time1 = setInterval(() => {
      this.get_check_user();
    }, 1000 * 60);
  },
  beforeDestroy() {
    if (this.time1) {
      clearInterval(this.time1);
    }
  },
  methods: {
    //判断用户是否需要重新登录
    get_check_user() {
      let adminid = this.userInfo.adminid;
      let loginpwd = this.userInfo.loginpwd;
      login_check_login({ adminid, loginpwd }).then((res) => {
        if (res.code === 0) {
          if (res.obj) {
            let needLogin = res.obj.needLogin;
            if (needLogin) {
              this.toLoginOut();
            }
          }
        } else {
          this.toLoginOut();
        }
      });
    },
    init() {
      logdoperatemsg_get_nrn({
        rtype: this.powerParams.rtype,
        objectid: this.powerParams.objectid
      }).then((res) => {
        if (res.code === 0) {
          this.nreadNum = res.obj >= 100 ? 99 : res.obj;
        } else {
          this.$Message.error(res.msg);
        }
      });
    },
    headerDope() {
      this.$router.push("dope");
    },
    // 获取短信验证码
    getMsgCode() {
      if (this.phoneInfo.second < 60) {
        return;
      }
      // 手机号验证
      if (!this.phoneInfo.phone) {
        this.$Message.error("手机号码不能为空");
        return;
      }
      let filter = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!filter.test(this.phoneInfo.phone)) {
        this.$Message.error("手机号码格式不正确");
        return;
      }
      login_msg_code({
        phone: this.phoneInfo.phone
      }).then((data) => {
        if (data.code === 0) {
          this.setRegionSecond();
          this.$Message.success(data.msg);
        } else {
          this.$Message.error(data.msg);
        }
      });
    },
    setRegionSecond() {
      this.phoneInfo.second = 59;
      this.phoneInfo.timer = setInterval(() => {
        this.phoneInfo.second--;
        if (this.phoneInfo.second === 0) {
          clearInterval(this.phoneInfo.timer);
          this.phoneInfo.timer = null;
          this.phoneInfo.second = 60;
        }
      }, 1000);
    },
    savephoneInfo() {
      this.$refs.phoneInfo.validate((valid) => {
        if (valid) {
          this.showLoading = true;
          admin_edit_phone({
            adminid: this.userInfo.adminid,
            phone: this.phoneInfo.phone,
            msgcode: this.phoneInfo.msgcode,
            rversion: this.phoneInfo.rversion
          }).then((data) => {
            this.showLoading = false;
            if (data.code === 0) {
              this.phoneInfo.show = false;
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    savepwInfo() {
      this.$refs.pwInfo.validate((valid) => {
        if (valid) {
          this.showLoading = true;
          admin_edit_pwd({
            adminid: this.userInfo.adminid,
            loginpwd: this.pwInfo.loginpwd,
            oldpwd: this.pwInfo.oldpwd,
            rversion: this.pwInfo.rversion
          }).then((data) => {
            this.showLoading = false;
            if (data.code === 0) {
              this.pwInfo.show = false;
              this.$Message.success(data.msg);
            } else {
              this.$Message.error(data.msg);
            }
          });
        }
      });
    },
    // 下拉菜单显示隐藏
    userDropdownVisibleChange(visible) {
      this.userDropdown = visible;
    },
    // 用户点击下拉菜单项
    userDropdownSelectChange(name) {
      if (name === "1") {
        // 个人信息
        this.$router.push("personal");
      } else if (name === "2" || name === "3") {
        // 2修改密码 3更换手机号
        admin_detail({ adminid: this.userInfo.adminid }).then((res) => {
          if (res.code === 0) {
            if (name === "2") {
              this.pwInfo = {
                show: true,
                rversion: res.obj.rversion,
                adminid: "",
                loginpwd: "",
                oldpwd: ""
              };
            } else {
              if (this.phoneInfo.timer) {
                clearInterval(this.phoneInfo.timer);
              }
              this.phoneInfo = {
                show: true,
                timer: null,
                second: 60,
                rversion: res.obj.rversion,
                adminid: "",
                oldphone: res.obj.phone,
                phone: "",
                msgcode: ""
              };
            }
          } else {
            this.$Message.error(res.msg);
          }
        });
      } else if (name === "4") {
        // 退出
        this.$Modal.confirm({
          title: "提示",
          content: "确定退出吗？",
          onOk: () => {
            this.toLoginOut();
          },
          onCancel: () => {}
        });
      }
    },
    // 退出
    toLoginOut() {
      login_login_out({ adminid: this.userInfo.adminid }).then(() => {
        this.$router.replace({
          path: "/login"
        });
      });
    }
  }
};
</script>

<style lang="less" scoped>
.layout_wrap {
  width: 100vw;
  height: 100vh;
  background-color: #f1f6fc;
  overflow: auto;
  .layout_header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
    height: 50px;
    background-color: #fff;
    .header_left {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      img {
        width: 236px;
        height: 32px;
      }
    }
    .header_right {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .right_user_info {
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        .user_img {
          width: 30px;
          height: 30px;
          overflow: hidden;
          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
          }
        }
        .user_name {
          margin: 0 6px 0 10px;
        }
        .user_drop {
          transition: all 0.2s ease-in-out;
          &.arrow_dropdown {
            transform: rotate(180deg);
          }
        }
      }
    }
    .dope {
      margin: 0 10px;
      cursor: pointer;
      position: relative;
      .img1 {
        width: 26px;
        height: 24px;
      }
      .img2 {
        width: 18px;
        height: 18px;
        position: absolute;
        right: -1px;
        top: -4px;
        text-align: center;
        line-height: 18px;
        font-size: 12px;
        color: white;
        background: url("../assets/img/Ellipse.png") no-repeat;
        background-size: 100% 100%;
      }
      .dopenum {
        color: white;
        font-size: 12px;
        position: absolute;
        right: 1px;
        top: -1px;
      }
    }
  }
  .layout_main {
    position: relative;
    width: 100%;
    height: calc(100% - 50px);
    overflow: auto;
  }
}
.code_btn {
  display: inline-block;
  margin-left: 10px;
  width: 92px;
  font-size: 14px;
  text-align: center;
  color: #339dff;
  line-height: 30px;
  border: 1px solid #339dff;
  border-radius: 6px;
  background-color: #fff;
  cursor: pointer;
  &.disabled {
    color: #c5c8ce;
    background-color: #f7f7f7;
    border-color: #dcdee2;
    cursor: not-allowed;
  }
}
.modal_view {
  .ivu-modal {
    width: 520px;
  }
}
</style>
