<template>
  <div class="custom-search-header">
    <div class="fixed-box">
      <div class="header-content">
        <div class="left">
          <img class="logo" @click="toUrl('home')" v-if="basicSet.set" :src="basicSet.set.logo_src" alt="">
          <!-- <div class="breadcrumb-box" v-if="breadcrumbs">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-if="breadcrumbs.base">
                <span class="hover-class overflow-hide" @click="toUrl('knowledge-home')">知识库首页</span>
              </el-breadcrumb-item>
              <el-breadcrumb-item v-if="breadcrumbs.base">
                <span style="max-width: 300px;display: inline-block" class="hover-class overflow-hide"
                      @click="toUrl('knowledge-knowledge_detail-articleId', {articleId: -1}, {base_id: breadcrumbs.base.id})">{{breadcrumbs.base.name}}</span>
              </el-breadcrumb-item>
              <el-breadcrumb-item v-if="breadcrumbs.article">
                <span style="max-width: 330px;display: inline-block" class="hover-class overflow-hide"
                      @click="toUrl('knowledge-knowledge_detail-articleId', {articleId: breadcrumbs.article.id}, {base_id: breadcrumbs.base.id})">{{breadcrumbs.article.name}}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div> -->
        </div>
        <div class="tab-list" ref="tabListRef" id="tabListID" @mousewheel.prevent>
          <!-- @click="onClickTab(index,$event)"  -->
          <div class="tab"
            :ref="`tabChild_${index}`"
            :class="{'tab-selected':tabSelectedIndex===index}"
            v-for="(tab,index) in tabList"
            @click="toArticle(tab.id,-1)" :key="tab.id" @mousewheel.prevent>
            {{tab.name}}
          </div>
        </div>
        <div style="width: 10vw;"></div>
        <div class="right">
          <el-input v-model="inputKeyword" placeholder="搜索" @keyup.enter.native="toSeach" size="small">
            <template slot="prepend"><i class="el-icon-search"></i></template>
          </el-input>
          <el-button size="small" class="btn-search" @click="toSeach">搜索知识库</el-button>
          <el-button size="small" v-if="baseAuths && (baseAuths.isMember || baseAuths.isManager) && baseAuths.isNoList"
                     class="btn-edit btn-default" @click="optionNode('new')">新建
          </el-button>
          <el-button size="small" v-if="baseAuths && (baseAuths.isMember || baseAuths.isManager) && isEditor"
                     class="btn-edit btn-default" @click="optionNode('save')">发布
          </el-button>
          <el-button size="small"
                     v-if="baseAuths && (baseAuths.isMember || baseAuths.isManager) && !isEditor && !baseAuths.isNoList"
                     class="btn-edit btn-default" @click="optionNode('edit')">编辑
          </el-button>

          <el-button size="small" v-if="baseAuths && baseAuths.isManager" class="btn-delete btn-default"
                     @click="optionNode('delete')">删除
          </el-button>
          <el-button size="small" class="btn-login btn-default" v-if="!basicSet.is_login"
                     @click="toUrl('login',{select: '1'})">登录
          </el-button>
          <el-button size="small" class="btn-login logout btn-default" @click="toUrl('order')" v-else>个人中心</el-button>
        </div>
      </div>
    </div>
    <div class="empty"></div>

    <el-dialog title="发布到..."
               :visible.sync="dialogTableVisible"
               :lock-scroll="true"
    >
      <div class="scroll-box">
        <el-input v-model="article_sort" placeholder="请输入文章排序（数字越大排序越前，默认0）">
        </el-input>
        <el-tree
          highlight-current
          :node-key="NODE_KEY"
          :data="catalogueTree"
          :props="catalogueProps"
          :default-expand-all="true"
          :expand-on-click-node="false"
          :current-node-key="article_id"
          @node-click="clickDialogNode"
        >
          <div class="catalogue-tree-node" slot-scope="{ node, data }">
            <div class="node-containe">
              <span class="node-text text-over">
              {{node.label}}
              </span>
              <div class="hidden radio-box">
                <span style="color:#bfbfbf">移动为</span>
                <el-radio-group v-model="radio">
                  <el-radio :label="0">同级</el-radio>
                  <el-radio :label="1">子级</el-radio>
                </el-radio-group>
              </div>
              <div class="hidden selector-tree-placeholder" :style="{left: radio==1?'25px':'',width: radio==1?'96%':''}"></div>
            </div>
          </div>
        </el-tree>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {mapState} from 'vuex'

  export default {
    name: "KHeader",
    data() {
      return {
        tabList: [],
        tabSelectedIndex: 0,
        tabListRef: null,

        isEditor: false,
        inputKeyword: "",
        radio: 0,
        article_sort: "",
        parentData: "",
        // 目录
        catalogueTree: [],
        catalogueProps: {
          label: "article_name",
          children: "child",
        },
        // 树节点参数
        NODE_KEY: 'id',
        dialogTableVisible: false,
      };
    },
    computed: {
      ...mapState(['basicSet', 'basicCategory', 'breadcrumbs', 'baseAuths', 'articleContent']),
      article_id() {
        if (this.breadcrumbs.article && this.breadcrumbs.article.id) {
          return this.breadcrumbs.article.id
        } else {
          return 0
        }
      },
    },
    watch: {
      '$route'(res) {
        this.url = this.fun.redirectH5(this.$route.path, this.$route.fullPath);
        if(location.href.indexOf('knowledge_editor')>-1) {
          this.isEditor = true;
        }else {
          this.isEditor = false;
        }
      }
    },
    mounted() {
      // PC跳转移动端
      this.url = this.fun.redirectH5(this.$route.path, this.$route.fullPath);
      if(location.href.indexOf('knowledge_editor')>-1) {
        this.isEditor = true;
      }

      this.getTabData();
    },
    destroyed() {
      let box = document.querySelector("#tabListID")
      // 由于不同的浏览器所兼容的函数不同，所以需要首先判断浏览器类型，再按照不同浏览器写不同的函数
      let explorer =navigator.userAgent;
      if(explorer.indexOf("Firefox") >= 0){
          box.removeEventListener("DOMMouseScroll",this.throttleFn)
        }else{
          box.removeEventListener("mousewheel",this.throttleFn)
        }
    },
    methods: {
      toSeach() {
        this.$router.push(this.fun.getUrl("knowledge-knowledge_search", {}, {keyword: this.inputKeyword}))
      },
      toUrl(url, params, query) {
        if (url == 'login') {
          sessionStorage.setItem("yz_redirect", document.location.href);
        }
        if (url == 'knowledge-knowledge_detail-articleId' && params.articleId != -1) {
          this.$store.commit('setKnowledgeLoading', true);
        }
        this.$router.push(this.fun.getUrl(url, params, query));
      },
      logout() {
        this.fun.$get("member.logout.index").then(
          response => {
            if (response.result == 1) {
              sessionStorage.setItem("yz_redirect", document.location.href);
              this.$store.commit("setLogin", {is_login: false});
              this.$alert(response.msg, '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  this.$router.push(this.fun.getUrl("login"));
                }
              });
            }
          },
          response => {
            console.log(response.msg);
          }
        );
      },
      optionNode(type) {
        let artId = this.article_id || this.$route.params.articleId;
        let base_id = this.fun.getKey("base_id");
        if (!base_id) {
          this.$message.error("知识库不存在");
          return;
        }
        if (!artId && type != "save") {
          this.$message.error("文章不存在");
          return;
        }
        if (type == 'new') this.editArticle(base_id, -1);
        if (type == "edit") this.editArticle(base_id, artId);
        if (type == "delete") this.deleteArticle(artId);
        if (type == "save") this.saveArticle(base_id, artId);
      },
      editArticle(base_id, artId) {
        this.$router.push(this.fun.getUrl("knowledge-knowledge_editor", {}, {base_id: base_id, articleId: artId}));
      },
      deleteArticle(artId) {
        this.$confirm("是否删除此节点？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then((res) => {
          removeQuery();
        }).catch(() => {
        })
        let removeQuery = () => {// 发送删除请求
          this.fun.$get("plugin.message-base.frontend.article.deleteArticle", {article_id: artId}, "loading")
            .then((response) => {
              if (response.result !== 1) {
                this.$message.error(response.msg);
                return false;
              }
              this.$message.success("删除节点成功");
            });
        }
      },
      // 目录树结构
      saveArticle(base_id, artId) {
        if ((this.article_id && this.article_id != -1) || this.$route.query.parent_id) {
          // 暂时只有编辑或者新建子级
          this.confirmSave(base_id);
          return;
        }
        // 知识库目录新建
        this.fun.$get("plugin.message-base.frontend.article.baseArticle", {base_id: base_id}, "loading")
          .then((response) => {
            if (response.result !== 1) {
              this.$message.error(response.msg);
              return false;
            }
            this.catalogueTree = response.data.article_list || 0;
            if (this.catalogueTree.length > 0) {
              this.dialogTableVisible = true;
              this.$nextTick(() => {
                //默认选中
                if (this.$refs.slotTree) this.$refs.slotTree.setCurrentKey(artId);
              })
            } else {
              this.confirmSave()
            }
          })
      },
      // 弹框节点点击
      clickDialogNode(_data, _node) {
        this.parentData = _data;
        // this.radio ==0同级添加
        // this.radio ==1子级添加
      },
      confirmSave() {
        this.dialogTableVisible = false;
        if (!this.articleContent.article_name) {
          this.$message.error("请输入标题");
          document.getElementById('tinymceTitle').focus();
          return
        }
        // 去除字体样式
        let articleContent=this.articleContent.content.replace(/font-family.*?;/ig,"");
        let parentNodeId = this.radio==1 ? this.parentData.id : this.parentData.parent_id;
        let json = {
          base_id: this.breadcrumbs.base ? this.breadcrumbs.base.id : this.$route.query.base_id || 1,
          parent_id: this.$route.query.parent_id || parentNodeId || 0,
          article_name: this.articleContent.article_name,
          article: encodeURIComponent(articleContent),
          article_sort: this.article_sort,
          is_private: this.articleContent.is_private
        };
        if (this.article_id && this.article_id != -1) {
          // 编辑
          json = {
            article_id: this.article_id,
            article_name: this.articleContent.article_name,
            article: encodeURIComponent(articleContent) || '',
            article_sort: this.article_sort,
            is_private: this.articleContent.is_private
          };
        }
        this.fun
          .$post('plugin.message-base.frontend.article.changeArticle', json, "正在提交")
          .then(res => {
            if (res.result === 1) {
              this.article_sort = "";
              this.$confirm(res.msg, '提示', {
                distinguishCancelAndClose: true,
                confirmButtonText: '返回知识库',
                cancelButtonText: '留在当前页面'
              })
                .then(() => {
                  this.toUrl('knowledge-knowledge_detail-articleId', {articleId: res.data.id}, {base_id: res.data.base_id});
                })
                .catch(action => {
                  this.$store.commit("setBreadcrumbs", {
                    base: {
                      id: this.breadcrumbs.base.id,
                      name: this.breadcrumbs.base.name
                    },
                    article: {
                      id: res.data.id,
                      name: res.data.article_name,
                    }
                  });
                });
            } else {
              this.$message.error(res.msg);
            }
          })
          .catch(error => {
            console.log(error);
          });
      },


      getTabData() {
        this.fun.$get("plugin.message-base.frontend.base.firstPage", {show_type: 1}, "加载中")
          .then((res) => {
            if (res.result !== 1) {
              this.$message.error(res.msg);
              return;
            }
            if (res.data.list) {
              this.tabList = res.data.list.data||[];
              this.tabList.push({
                id: 0,
                name: '更多'
              });
              let base_id = this.fun.getKey("base_id");
              this.tabList.forEach((element,i) => {
                if(element.id == base_id){
                  this.tabSelectedIndex = i;
                }
              });
              this.handleTabScroll();
              this.$nextTick(()=>{
                setTimeout(() => {
                  this.onClickTab();
                }, 80);
              });
            }
          })
      },
      handleTabScroll(){
        // 处理顶部导航 的 鼠标左右滚动
        let box = document.querySelector("#tabListID")
        // 由于不同的浏览器所兼容的函数不同，所以需要首先判断浏览器类型，再按照不同浏览器写不同的函数
        let explorer = navigator.userAgent;
        if(explorer.indexOf("Firefox") >= 0){
          box.addEventListener("DOMMouseScroll",this.throttleFn, true)
        }else{
          box.addEventListener("mousewheel",this.throttleFn, true)
        }
      },
      NavsListener(box,explorer){
        if(!event) return;
        if(explorer.indexOf("Firefox") >= 0){
          //计算鼠标滚轮滚动的距离
          // event.detail * 40 代表幅度(速度),40可以更改
          box.scrollLeft += event.detail * 40;
          //阻止浏览器默认方法
          event.preventDefault();
        } else {
          //计算鼠标滚轮滚动的距离
          // -event.wheelDelta / 2 代表幅度(速度),2可以更改
          let v = -event.wheelDelta*3 ;
          box.scrollLeft += v;
          //阻止浏览器默认方法
          event.preventDefault();
        }
      },
      onClickTab(index,e) {
        // this.tabSelectedIndex=index
        this.tabListRef = this.$refs.tabListRef;
        if(!this.$refs[`tabChild_${this.tabSelectedIndex}`]) return;
        let target = this.$refs[`tabChild_${this.tabSelectedIndex}`][0];
        this.tabListRef.scrollLeft = target.offsetLeft -this.tabListRef.offsetLeft -(this.tabListRef.clientWidth-target.offsetWidth)/2;
      },
      toArticle(base_id, article_id) {
        let url = this.fun.getSiteRoot() + `/plugins/shop_server/knowledge/knowledge_detail/${article_id}?i=${this.fun.getKeyByI()}&base_id=${base_id}`;
        if(base_id == 0) {
          url = this.fun.getSiteRoot() + `/plugins/shop_server/knowledge/knowledge_whole?i=${this.fun.getKeyByI()}`;
        }
        // this.$router.push(this.fun.getUrl("knowledge-knowledge_detail", {}, {base_id: base_id, articleId: articleId}));
        window.open(url, "_self");
      },
      throttleFn() {
        // 节流
        let interval = 200;
        this.now = + new Date();
        let box = document.querySelector("#tabListID")
        // 由于不同的浏览器所兼容的函数不同，所以需要首先判断浏览器类型，再按照不同浏览器写不同的函数
        let explorer =navigator.userAgent;
        if (this.last && this.now - this.last < interval) {
          clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            this.last = this.now;
            this.NavsListener(box,explorer);
          }, interval);
        } else {
          this.last = this.now;
          this.NavsListener(box,explorer);
        }
      },
    },
    components: {},
  };

</script>
<style lang='scss' rel='stylesheet/scss' scoped>
  .custom-search-header {
    min-width: 1300px;
    height: 60px;
    padding: 4px;
    box-sizing: border-box;
    .empty {
      width: 100%;
      height: 100%;
    }
    .fixed-box {
      z-index: 999;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      background-color: #ffffff;
      box-shadow: 0px 3px 7px 0px rgba(234, 234, 234, 0.81);
    }
    .header-content {
      /*max-width: 1300px;*/
      padding: 0 30px;
      height: 60px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .left {
        width: 18vw;
        display: flex;
        align-items: center;
        position: relative;
        .logo {
          cursor: pointer;
          width: 220px;
          height: 32px;
        }
        .breadcrumb-box {
          margin-left: 20px;
        }
        .hover-class {
          cursor: pointer;
        }
        .hover-class:hover {
          color: var(--color);
        }
      }
      .right {
        display: flex;
        align-items: center;
        :deep(.el-input) {
          .el-input-group__prepend {
            padding: 0 12px;
            background: transparent;
            border: 1px solid #DCDFE6;
            border-right: none !important;
          }
          .el-input__inner {
            padding-left: 5px;
            border-left: none;
          }
        }
        .btn-search {
          z-index: 2;
          height: 32px;
          border: none;
          margin-left: -3px;
          color: #ffffff;
          background-color: var(--color);
        }
        .btn-default {
          border: none;
          color: #ffffff;
        }
        .btn-edit {
          background-color: #298DF8;
        }
        .btn-delete {
          background-color: #E1564C;
        }
        .btn-login {
          background-color: #3a75f4;
        }
      }
    }
     .tab-list{
      flex: 1;
      font-size: 16px;
      display:flex;
      height: 60px;
      line-height: 60px;
      overflow-x:scroll;
      scroll-behavior:smooth;
    }
    .tab-list::-webkit-scrollbar{
      display:none;
    }
    .tab{
      flex:none;
      margin: 0 12px;
      text-align:center;
      color: #333;
      cursor: pointer;
    }
    .tab-selected{
      font-weight:bold;
      position: relative;
    }
    .tab-selected{
      font-weight:bold;
      position: relative;
    }
    .tab-selected:after {
      content: "";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 3px;
      background-color: #000000;
      z-index: 1;
    }
  }

  .scroll-box {
    height: 50vh;
    overflow-y: scroll;
    :deep(.el-tree) {
      background: transparent;
      .el-tree-node__content {
        margin: 6px 0;
        .hidden {
          display: none;
        }
        .catalogue-tree-node {
          position: relative;
          flex: 1;
          .node-containe {
            display: flex;
            width: 100%;
            flex-wrap: nowrap;
            white-space: nowrap;
            .node-text {
              flex: 1;
              width: 0; // 元素自适应超出隐藏
            }
          }

        }
      }
      .is-current > .el-tree-node__content {
        .catalogue-tree-node {
          position: relative;
          flex: 1;
          .radio-box {
            display: block;
          }
          .el-radio {
            font-size: 12px;
            margin-right: 0;
            margin-left: 10px;
          }
          .selector-tree-placeholder {
            display: block;
            position: absolute;
            bottom: -5px;
            left: 0;
            width: 100%;
            height: 2px;
            background-color: #66B1FF;
          }
        }
      }
      .el-tree-node__label {
        font-size: 14px;
        letter-spacing: 1px;
        color: #595959;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
</style>
