<template>
  <header class="header">
    <div class="container clearfix">
      <div class="logo logo--no" v-if="header.companyLogo">
        <img
          style="cursor: pointer; width: 162px; height: 33px"
          :src="$tools.splitImgHost(header.companyLogo)"
          alt=""
          @click="go('/')"
        />
      </div>
      <h1 class="logo" v-else @click="go('/')"></h1>
      <nav class="nav">
        <ul class="list">
          <li v-for="(item, index) in showNav(header.Nav)" :key="index">
            <a v-if="item.name == '首页'" @click="go('/index')">首页</a>
            <a v-if="item.name == '走进祥粤'" @click="go('/about')">走进祥粤</a>
            <a v-if="item.name == '课程'" @click="go('/course-list')">课程</a>
            <a v-if="item.name == '直播'" @click="go('/live-list')">直播</a>
            <a v-if="item.name == '题库'" @click="go('/bank-list')">题库</a>
          </li>
        </ul>
      </nav>

      <div class="userinfo" v-if="userInfo">
        <!-- <a class="msg" @click="go('/person-center/my-message')">
          <i class="pi" v-if="msgCount > 0"></i>
          <i class="el-icon-message-solid icon"></i>
          <div @click.stop="" class="popover_style">
            {{ msgData.text }} <el-button style="float:right;" type="text">立即学习</el-button>
          </div>
        </a> -->
        <el-tooltip
          placement="bottom"
          effect="light"
          v-model="msgShow"
          :hide-after="0"
          manual
        >
          <el-badge :is-dot="msgCount > 0 ? true : false" class="item">
            <el-button
              style="font-size: 18px; padding: 0px"
              icon="el-icon-message-solid"
              type="text"
              @click="go('/person-center/my-message')"
            ></el-button>
          </el-badge>
          <div slot="content">
            {{ msgData.text }}
            <div>
              <el-button type="text" @click="newGoToStudy">立即学习</el-button
              ><el-button type="text" @click="clearMsg">关闭</el-button>
            </div>
          </div>
        </el-tooltip>
        <el-dropdown @command="handleCommand">
          <span
            class="el-dropdown-link"
            @click="go('/person-center/my-course')"
            style="margin-left: 10px; cursor: pointer"
          >
            <img
              style="width: 24px; vertical-align: middle"
              :src="
                userInfo
                  ? userInfo.avatar
                    ? $tools.splitImgHost(userInfo.avatar, true)
                    : '@/assets/qrcode.png'
                  : ''
              "
              alt=""
            />
            <span>{{ userInfo && userInfo.realname }}</span>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">我的课程</el-dropdown-item>
            <el-dropdown-item command="2">我的题库</el-dropdown-item>
            <el-dropdown-item command="3">个人中心</el-dropdown-item>
            <el-dropdown-item command="4">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="userinfo" v-else>
        <div class="text-list" v-if="!userInfo">
          <a @click="go('/login', { state: 1 })">登录</a>
          <a @click="go('/login', { state: 2 })">注册</a>
        </div>
      </div>

      <div class="search">
        <div class="search__select">
          <select v-model="type">
            <option value="1">课程</option>
            <option value="2">题库</option>
            <option value="6">直播</option>
          </select>
        </div>
        <div class="search__input">
          <input type="text" v-model="searchKey" autocomplete="off" />
          <input
            type="password"
            autocomplete="new-password"
            style="display: none"
          />
        </div>
        <el-button type="primary" @click="search" class="search__btn"
          >搜索</el-button
        >
      </div>
    </div>

    <RebuildModal
      ref="rebuildModal"
      @rebuildSubmit="rebuildSubmit($event)"
    ></RebuildModal>
  </header>
</template>

<script>
import RebuildModal from "@/components/rebuildModal";
import { mapGetters, mapMutations } from "vuex";
export default {
  name: "Header",
  components: {
    RebuildModal,
  },
  data() {
    return {
      searchKey: "",
      type: "1",
      showBox: false,
      timer: null,
      msgData: {},
      sysTime: 0,
      msgShow: false,
    };
  },
  computed: {
    ...mapGetters(["header", "userInfo", "msgCount"]),
    showNav: function () {
      return function (list) {
        var newList = [];
        if (list) {
          newList = list.filter((item) => {
            return item.status === 1;
          });
        }
        return newList;
      };
    },
  },
  mounted() {
    if (this.$tools.isLogin()) {
      this.$request.informUserselectLastUnStudyMsg().then((res) => {
        if (res.data && res.data.id) {
          let today = new Date(new Date().toLocaleDateString()).getTime();
          if (localStorage.getItem("msg")) {
            let ary = JSON.parse(localStorage.getItem("msg"));
            if (ary.updateTime === today) {
              this.msgShow = false;
              return;
            }
          }
          this.$nextTick(() => {
            this.msgData = res.data;
            this.msgShow = true;
          });
        } else {
          this.msgShow = false;
        }
      });
      this.getMsgCount();
    }
  },
  methods: {
    ...mapMutations(["getMsgCount"]),
    rebuildSubmit(item) {
      this.$router.push({
        path: `/my-course-detail/${item.goodsId}`,
        query: {
          gradeId: item.gradeId,
          orderGoodsId: item.orderGoodsId,
          rebuild: 1,
        },
      });
    },
    getGoodsData() {
      return new Promise((resolve, reject) => {
        this.$request.goodsDetail(this.msgData.goodsId).then((res) => {
          resolve(res.data);
        });
      });
    },
    /**
     * 关闭消息
     */
    clearMsg() {
      let ary = {
        userId: this.msgData.userId,
        msgId: this.msgData.id,
        updateTime: new Date(new Date().toLocaleDateString()).getTime(),
      };
      localStorage.setItem("msg", JSON.stringify(ary));
      this.msgShow = false;
    },
    /**
     * 前往学习
     */
    async newGoToStudy() {
      let item = await this.getGoodsData();
      if (item.goodsType == 1) {
        this.sysTime = this.$tools.timest();
        item.orderGoodsId = this.msgData.orderGoodsId;
        this.canJump(item).then((res) => {
          this.clearMsg();
          this.$router.push({
            path: `/my-course-detail/${item.goodsId}`,
            query: {
              gradeId: item.gradeId,
              orderGoodsId: item.orderGoodsId,
              courseId: res.rows[0].courseId || "",
            },
          });
        });

        // arsty = '立刻学习';

        //题库
      } else if (item.goodsType == 2) {
        this.clearMsg();
        this.$router.push({
          path: "/person-center/my-bank/bank-detail/" + item.goodsId,
          query: {
            orderGoodsId: item.orderGoodsId,
          },
        });
      }
    },
    canJump(item) {
      return new Promise((resolve) => {
        this.$request
          .orderInfo({
            orderGoodsId: item.orderGoodsId,
          })
          .then(async (res) => {
            let items = res.data;
            let currentTime = this.$tools.timest();
            if (items.interfaceAccountId > 0) {
              //学习账号已开通

              if (items.learnStatus == 1) {
                //跳转第三方h5

                const confirmText = [
                  "您的学习账号已经开通，请按照步骤操作，进行学习。",
                  "1.点击【跳转学习网址】按钮",
                  "2.打开学习网址后，选择【个人用户】进行登录",
                  "(1)账号：您个人的身份证号码",
                  "(2)密码：身份证号码，再加111111",
                ];
                const newDatas = [];
                const h = this.$createElement;
                for (const i in confirmText) {
                  newDatas.push(h("p", null, confirmText[i]));
                }
                this.$confirm(h("div", null, newDatas), "温馨提示", {
                  confirmButtonText: "跳转学习网址",
                  cancelButtonText: "关闭",
                  closeOnClickModal: false,
                  closeOnPressEscape: false,
                  distinguishCancelAndClose: false,
                  showClose: false,
                })
                  .then((_) => {
                    window.open("http://admin.zhujianpeixun.com/", "_blank");
                  })
                  .catch((_) => {});

                return;
              } else {
                this.$message({
                  type: "warning",
                  message:
                    "您的学习账号未开通，请稍后再尝试，有疑问，请联系020-87085982！",
                });
                return;
              }
            }
            // //内部系统
            // if (items.interfacePushId > 0 && items.officialStatus != 1) {
            //   this.$message({
            //     type: "warning",
            //     message:
            //       "机构正在为您报名中，请耐心等待，有疑问请联系020-87085982！",
            //   });
            //   return;
            // }
            if (
              this.sysTime <= items.serviceStartTime ||
              this.sysTime >= items.serviceEndTime
            ) {
              this.$message({
                type: "warning",
                message: "不在学习服务期，不能进入学习",
              });
              return;
            }

            if (
              (items.classStartTime && this.sysTime <= items.classStartTime) ||
              (items.classEndTime && this.sysTime >= items.classEndTime)
            ) {
              this.$message({
                type: "warning",
                message: "不在班级有效期，不能进入学习",
              });
              return;
            }

            if (items.learningStatus == 2) {
              this.$message({
                type: "warning",
                message: "开放学习时间待定，不能进入学习",
              });
              return;
            }

            if (items.classStatus == 0) {
              this.$message({
                type: "warning",
                message: "尚未开班，不能进入学习",
              });
              return;
            }
            if (
              items.learningStatus == 3 &&
              this.sysTime < items.learningTimeStart
            ) {
              this.$message({
                type: "warning",
                message: "不在开放学习时间,不能进入学习",
              });
              return;
            }

            let rebuildStatus = await this.courseGoodsRebuildStatus(
              items.goodsId,
              items.gradeId
            );

            if (rebuildStatus == 0) {
              this.$refs.rebuildModal.showModal(items);
              return;
            }

            // if (item.educationName == "继续教育") {
            this.$request
              .lockLockStatus({
                action: "jxjy",
              })
              .then((res) => {
                //有其他端在操作，不能学习
                this.$message({
                  type: "warning",
                  message: res.msg,
                });
              })
              .catch((err) => {
                //可以学习
                this.$request
                  .courseCourseList({
                    pageNum: 1,
                    pageSize: 1,
                    goodsId: items.goodsId,
                    gradeId: items.gradeId,
                  })
                  .then((res) => {
                    if (res.rows.length) {
                      resolve(res);
                    } else {
                      this.$message({
                        type: "warning",
                        message: "课程内暂无可以学习的科目",
                      });
                    }
                  });
              });

            // } else {
            //   this.$request
            //     .courseCourseList({
            //       pageNum: 1,
            //       pageSize: 1,
            //       goodsId: items.goodsId,
            //       gradeId: items.gradeId,
            //     })
            //     .then((res) => {
            //       if (res.rows.length) {
            //         resolve(res);
            //       } else {
            //         this.$message({
            //           type: "warning",
            //           message: "课程内暂无可以学习的科目",
            //         });
            //       }
            //     });
            // }
          });
      });
    },

    /**
     * @param {Object} goodsId 商品id
     * 查询商品重修状态
     */
    courseGoodsRebuildStatus(goodsId, gradeId) {
      return new Promise((resolve) => {
        this.$request
          .courseGoodsRebuildStatus({
            goodsId: goodsId,
            gradeId: gradeId,
          })
          .then((res) => {
            resolve(res.data);
          });
      });
    },
    handleCommand(command) {
      switch (command) {
        case "1":
          this.go("/person-center/my-course");
          break;
        case "2":
          this.go("/person-center/my-bank");
          break;
        case "3":
          this.go("/person-center/my-info");
          break;
        case "4":
          this.$tools.exit();
          break;

        default:
          break;
      }
    },
    go(path, query) {
      this.$router.push({
        path,
        query,
      });
    },

    search() {
      if (!this.searchKey.trim()) {
        this.$message({
          type: "warning",
          duration: 2000,
          message: "请输入搜索内容",
        });

        return;
      }
      let type = this.type;
      let path = this.$route.path;

      if (path == "/bank-list") {
        //在题库列表页面直接传参
        if (type == "2") {
          this.$emit("search", this.searchKey);
        } else if (type == "6") {
          this.$router.push({
            path: "/live-list",
            query: {
              searchKey: this.searchKey,
            },
          });
        } else {
          this.$router.push({
            path: "/course-list",
            query: {
              searchKey: this.searchKey,
            },
          });
        }
      } else if (path == "/course-list") {
        //在课程列表页面直接传参
        if (type == "1") {
          this.$emit("search", this.searchKey);
        } else if (type == "6") {
          this.$router.push({
            path: "/live-list",
            query: {
              searchKey: this.searchKey,
            },
          });
        } else {
          this.$router.push({
            path: "/bank-list",
            query: {
              searchKey: this.searchKey,
            },
          });
        }
      } else if (path == "/live-list") {
        //在课程列表页面直接传参
        if (type == "6") {
          this.$emit("search", this.searchKey);
        } else if (type == "1") {
          this.$router.push({
            path: "/course-list",
            query: {
              searchKey: this.searchKey,
            },
          });
        } else {
          this.$router.push({
            path: "/bank-list",
            query: {
              searchKey: this.searchKey,
            },
          });
        }
      } else {
        //根据类型跳转题库或者列表页面
        console.log(type);
        if (type == "1") {
          this.$router.push({
            path: "/course-list",
            query: {
              searchKey: this.searchKey,
            },
          });
        } else if (type == "6") {
          this.$router.push({
            path: "/live-list",
            query: {
              searchKey: this.searchKey,
            },
          });
        } else {
          this.$router.push({
            path: "/bank-list",
            query: {
              searchKey: this.searchKey,
            },
          });
        }
      }
    },

    mouseover() {
      clearTimeout(this.timer);
      this.showBox = true;
    },

    mouseLeave() {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.showBox = false;
      }, 500);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.header {
  position: relative;
  background: #fff;
  box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.04);

  .container {
    height: 80px;

    .logo {
      margin-top: 23px;
      float: left;
      cursor: pointer;
      width: 162px;
      height: 33px;
      background: url("~@/assets/logo.png") no-repeat center;

      &--no {
        background: none;
      }
    }

    .nav {
      float: left;
      margin-top: 30px;
      .list {
        margin-left: 146px;
        display: flex;

        li {
          margin: 0 20px;
          a {
            color: #333;
          }
          a:hover {
            color: #3f8dfd;
          }
        }
      }
    }

    .search {
      float: right;
      margin-right: 12px;
      margin-top: 20px;
      width: 324px;
      background: #fafbfc;
      border: 1px solid #3f8dfd;
      border-radius: 8px;
      display: flex;
      overflow: hidden;

      &__select {
        width: 76px;
        border-right: 1px solid #fff;

        select {
          text-align: center;
          width: 100%;
          height: 100%;
          border: 0;
          outline: none;
        }
      }

      &__input {
        flex: 1;

        input {
          width: 100%;
          height: 100%;
        }
      }

      &__btn {
        padding: 0;
        text-align: center;
        width: 80px;
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        border-radius: 0;
      }
    }

    .userinfo {
      margin-top: 30px;
      float: right;
      white-space: nowrap;
      a {
        display: inline-block;
        margin-left: 20px;
        vertical-align: middle;

        &.msg {
          position: relative;
          margin-top: 2px;

          .icon {
            font-size: 20px;
            color: #3f8dfd;
          }
          .pi {
            display: inline-block;
            width: 10px;
            height: 10px;
            background: #ff3b30;
            border: 1px solid #ffffff;
            border-radius: 10px;
            position: absolute;
            top: 0;
            right: 0;
          }
          .popover_style {
            position: absolute;
            top: 150%;
            left: -100px;
            border-radius: 8px;
            background-color: #fff;
            border: 1px solid #333;
            padding: 0px 6px;
            width: 300px;
            white-space: normal;
          }
        }

        &.name {
          position: relative;
          z-index: 99;
          img {
            width: 24px;
            vertical-align: middle;
          }

          .modal-box {
            width: 162px;
            background: #ffffff;
            box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            position: absolute;
            top: 55px;
            left: -40px;
            li {
              margin-left: 10px;
              border-bottom: 1px solid #eeeeee;
              height: 40px;
              line-height: 40px;
              cursor: pointer;
              padding-left: 5px;

              &:hover {
                background: #eeeeee;
                color: #3f8dfd;
              }

              &:nth-last-of-type(1) {
                border: 0;
              }
            }
          }
        }
      }
    }

    .text-list {
      text-align: right;
      font-size: 0;

      a {
        display: inline-block;
        margin: 0;
        color: #3f8dfd;
        font-size: 14px;
        padding: 0 14px;

        &:nth-last-of-type(1) {
          padding-right: 0;
          border-left: 1px solid #3f8dfd;
        }
      }
    }
  }
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
  height: 0;
}
.fade-enter-to,
.fade-leave {
  opacity: 1;
  height: 122px;
}
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s;
}
</style>
