<template>
  <div class="fixed-wrap" :style="{ position: basicSet.set.set_top == 1 ? 'relative' : 'fixed' }">
    <div class="welcome" v-if="top_type == 'other'"
      :style="{ marginTop: headOver ? (basicSet.set && basicSet.set.pc_temp == 1 ? '-32px' : '-35px') : '', height: basicSet.set && basicSet.set.pc_temp == 1 ? '32px' : '35px' }">
      <div class="welcome-content flex flex-j-sb flex-a-c"
        :style="{ height: basicSet.set && basicSet.set.pc_temp == 1 ? '32px' : '35px' }">
        <div class="welcome-left flex flex-a-c">
          <div class="tips">您好，欢迎光临{{ basicSet.shop_name }}!</div>
          <div class="flex flex-a-c logo-box" v-if="!basicSet.is_login">
            <span @click="toUrl('login', { select: '1' })">微信扫码登录</span>|<span
              @click="toUrl('login', { select: '0' })">免登陆</span>
          </div>
          <div class="flex flex-a-c logo-box" v-if="basicSet.is_login">
            <span @click="logout">退出登录</span>
          </div>
        </div>
        <div class="welcome-right flex flex-a-c">
          <template v-if="basicSet.set && basicSet.set.pc_temp == 1">
            <!-- 模板样式1 -->
            <div style="margin-right: 15px" @click="toUrl('member-collection')" v-if="basicSet.is_login">我的收藏</div>
            <div @click="toUrl('order')">我的订单/</div>
          </template>
          <template v-if="basicSet.set && basicSet.set.pc_temp == 2">
            <div class="icon-item" @click="toUrl('order')">
              <img src="~/assets/images/icon/my.png">
              <div class="icon-item-text">我的</div>
            </div>
            <div class="icon-item" v-if="basicSet.is_login" @click="toUrl('cart')">
              <img style="width: 16px;height: 16px;" src="~/assets/images/icon/detail_gouwu.png">
              <div class="icon-item-text">购物车</div>
            </div>
            <div class="icon-item" v-if="basicSet.is_login" @click="toUrl('member-collection')">
              <img src="~/assets/images/icon/collect.png">
              <div class="icon-item-text">收藏</div>
            </div>
          </template>
          <div class="flex flex-a-c mobile_version">
            手机版
            <img src="~/assets/images/icon/down.png" style="margin-left:2px;cursor: pointer;">
            <div class="hide_block">
              <div class="mini_code m-auto">
                <!--<img :src="basicSet.qr_code" alt="">-->
                <canvas id="qrccode-canvas"></canvas>
              </div>
              <span>扫一扫进入</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="header flex flex-a-c" :class="{ 'hide-shadow': basicSet.set && basicSet.set.pc_temp == 2 }"
      :style="{ height: basicSet.set && basicSet.set.pc_temp == 1 ? '100px' : '140px' }">
      <div class="top flex flex-a-c flex-j-sb">
        <div class="left" @click="toUrl('home')" v-if="basicSet.set">
          <img :src="basicSet.set.logo_src" style="margin-right:20px;">
          <!--<span class="advert_words overflow-hide">{{basicSet.set.advert_words}}</span>-->
        </div>
        <div class="right-img" v-if="top_type == 'normal'">
          <img :src="basicSet.set.advert_top_img_src" v-if="basicSet.set && basicSet.set.advert_top_img_src" alt="">
        </div>
        <div class="sousuo flex flex-j-c " v-if="top_type == 'other'">
          <div class="input flex flex-a-c" v-if="basicSet.set && basicSet.set.pc_temp == 1">
            <input type="text" v-model="keywords" @keypress="enterSearch"
              :placeholder="basicSet.set && basicSet.set.search_title ? basicSet.set.search_title : '商品名称/规格/型号'">
            <div class="flex flex-a-c flex-j-c button" @click="searchGoods" @keyup.enter="searchGoods">
              <i class="iconfont icon-faxianshebei">
              </i>
            </div>
          </div>
          <div class="input input-template-02 flex flex-a-c" v-else>
            <input type="text" v-model="keywords" @keypress="enterSearch"
              :placeholder="basicSet.set && basicSet.set.search_title ? basicSet.set.search_title : '商品名称/规格/型号'">
            <div class="flex flex-a-c flex-j-c button" @click="searchGoods" @keyup.enter="searchGoods">搜索</div>
          </div>
        </div>
        <div class="myCar flex flex-a-c flex-j-c"
          v-if="top_type == 'other' && basicSet.set && basicSet.set.pc_temp == 1" @click="toUrl('cart')">
          <i class="iconfont icon-htmal5icon29"></i>我的购物车
        </div>
        <div class="top-adimg"
          v-if="top_type == 'other' && basicSet.set && basicSet.set.pc_temp == 2 && basicSet.pc_temp2_set.right_advert_src"
          @click="gotoUrl(basicSet.pc_temp2_set.advert_link)">
          <img :src="basicSet.pc_temp2_set.right_advert_src" alt="">
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import cssText from "~/utils/element_css";
import QRCode from "qrcode";

var canvas = "";
const version = require('element-ui/package.json').version
const ORIGINAL_THEME = '#409EFF'

export default {
  name: 'LHeader',
  props: {
    top_type: String
  },
  data() {
    return {
      url: "",
      keywords: '',
      headOver: false,
      template: '02'
    };
  },
  computed: {
    ...mapState(['basicSet', 'basicCategory'])
  },
  watch: {
    "$store.state.keywords": function (v) {
      this.keywords = v;
    },
    keywords(v) {
     if(v && v !== 'null'){
      this.$store.commit("setKeywords", v);
     }else{
      this.$store.commit("setKeywords", '');
     }
    },
    '$route'(res) {
      // 浏览足迹  页面切换时更新new_page_comeIn
      window.new_page_comeIn = 1;

      if (res.name !== 'search') {
        console.log(res.name, "res.name")
        this.keywords = "";
        this.$store.commit("setKeywords", this.keywords);
      }

      if (this.top_type == 'other') {
        this.url = this.fun.redirectH5(this.$route.path, this.$route.fullPath);

        setTimeout(() => {
          this.createQrc(this.url);
        }, 200);

      }
    }
  },
  mounted() {
    //监听滚动条
    window.addEventListener('scroll', this.handleScroll);

    // 浏览足迹  页面切换时更新new_page_comeIn
    window.new_page_comeIn = 1;

    // PC跳转移动端
    this.url = this.fun.redirectH5(this.$route.path, this.$route.fullPath);
    // PC跳转移动端end

    if (this.top_type == 'other') {
      this.createQrc(this.url);
    }

    let color = this.basicSet.set && this.basicSet.set.theme_color ? this.basicSet.set.theme_color : '#29ba9c';

    this.theme(color, ORIGINAL_THEME);

    // 静态化部署使用
    // this.getBasic();
    // this.getBasicCategory();

    if (window.location.href.includes("search")) {
      this.keywords = this.$store.state.keywords || localStorage.getItem('keywords');
    }
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    getBasic() {
      if (this.basicSet.qr_code) {
        return
      }
      this.fun.$post('plugin.pc-terminal.api.set.get-set', { basic_info: 1 }, '正在获取').then(res => {
        if (res.result === 1) {
          this.$store.commit("setBasicInfo", res.basic_info);
          this.$store.commit("setBasicSet", res.data);
        }
      })
    },
    getBasicCategory() {
      if (this.basicCategory.current_page) {
        return
      }
      this.fun.$post('plugin.pc-terminal.api.goods.get-home-category', {}, '正在获取').then(res => {
        if (res.result === 1) {
          if (res.data.total > 10) {
            // 超过10个要显示查看更多
            res.data.data = res.data.data.splice(0, 9)
          }
          this.$store.commit("setBasicCategory", res.data);
        }
      })
    },

    createQrc(url) {
      this.$nextTick(function () {
        // DOM操作
        canvas = document.getElementById("qrccode-canvas");
        QRCode.toCanvas(canvas, url, error => {
          if (error) {
            console.log(error);
          }
        });
      });
    },
    theme(val, oldVal) {
      if (typeof val !== 'string') return
      const themeCluster = this.getThemeCluster(val.replace('#', ''))
      const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
      const getHandler = (variable, id) => {
        return () => {
          const originalCluster = this.getThemeCluster(ORIGINAL_THEME.replace('#', ''))
          const newStyle = this.updateStyle(this[variable], originalCluster, themeCluster)

          let styleTag = document.getElementById(id)
          if (!styleTag) {
            styleTag = document.createElement('style')
            styleTag.setAttribute('id', id)
            document.head.appendChild(styleTag)
          }
          styleTag.innerText = newStyle
        }
      }

      const chalkHandler = getHandler('chalk', 'chalk-style')

      if (!this.chalk) {
        // 改成下载到本地不请求
        // const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
        this['chalk'] = cssText.cssText;
        chalkHandler();
        // this.getCSSString(url, chalkHandler, 'chalk')
      } else {
        chalkHandler()
      }

      const styles = [].slice.call(document.querySelectorAll('style'))
        .filter(style => {
          const text = style.innerText
          return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)
        })
      styles.forEach(style => {
        const { innerText } = style
        if (typeof innerText !== 'string') return
        style.innerText = this.updateStyle(innerText, originalCluster, themeCluster)
      })

      // 响应外部操作
      // this.$emit('onThemeChange', val)

    },
    updateStyle(style, oldCluster, newCluster) {
      let newStyle = style
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
      })
      return newStyle
    },

    getCSSString(url, callback, variable) {
      const xhr = new XMLHttpRequest()
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
          this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '')
          callback()
        }
      }
      xhr.open('GET', url)
      xhr.send()
    },

    getThemeCluster(theme) {
      const tintColor = (color, tint) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)

        if (tint === 0) {
          return [red, green, blue].join(',')
        } else {
          red += Math.round(tint * (255 - red))
          green += Math.round(tint * (255 - green))
          blue += Math.round(tint * (255 - blue))

          red = red.toString(16)
          green = green.toString(16)
          blue = blue.toString(16)

          return `#${red}${green}${blue}`
        }
      }

      const shadeColor = (color, shade) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)

        red = Math.round((1 - shade) * red)
        green = Math.round((1 - shade) * green)
        blue = Math.round((1 - shade) * blue)

        red = red.toString(16)
        green = green.toString(16)
        blue = blue.toString(16)

        return `#${red}${green}${blue}`
      }

      const clusters = [theme]
      for (let i = 0; i <= 9; i++) {
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
      }
      clusters.push(shadeColor(theme, 0.1))
      return clusters
    },
    logout() {
      this.fun.$get("member.logout.index").then(
        response => {
          if (response.result == 1) {
            // localStorage.setItem("isWxLogin", -1);
            // localStorage.setItem("loginUid", "");
            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);
        }
      );
    },
    enterSearch(event) {
      if (event.keyCode === 13) {
        //如果按的是enter键
        event.preventDefault();
        this.searchGoods()
      }
    },
    searchGoods() {
      this.$store.commit("setKeywords", this.keywords);
      this.getSearchData();
      if(this.$route.name!=='search'){
        this.$router.push(this.fun.getUrl('search'));
      }
    },
    getSearchData() {
      let index = localStorage.getItem("search_index") || '';
      let url = {
        0:'goods.goods.search-goods',
        1:'plugin.article.api.pc.article.get-articles',
        2:'plugin.message-base.frontend.article.index',
        3:'plugin.micro-communities.api.pc.index.getStick',
        4:'plugin.video-share.frontend.video.getList'
      }
      if (index) {
        if (index == 0) {
          this.getSeatchContent(url[index], 'post');
        } else if (index == 1) {
          this.getSeatchContent(url[index], 'get', index)
        } else if (index == 2) {
          this.getSeatchContent(url[index],'get',index)
        } else if (index == 3) {
          this.getSeatchContent(url[index],'get',index);
        } else if (index == 4) {
          this.getSeatchContent(url[index],'post',index);
        }
      }else{
        let type='get';
        if (this.basicSet && this.basicSet.set.search_module_config) {
        this.basicSet.set.search_module_config.forEach((item, index) => {
          if (item.is_default && item.is_default == 'true') {
            if(item.key == 'goods'){
              index=0;
              type='post';
            }else if(item.key == "article"){
              index=1;
            }else if(item.key=="knowledge"){
              index=2;
            }else if(item.key=="post"){
              index=3;
            }else if(item.key=="video"){
              index=4;
              type='post';
            }
            this.getSeatchContent(url[index],type,index)
          }
        })
      }
      }
    },
    getSeatchContent(url, type, index) {
      let json = {
        search: { keyword: this.keywords },
        page: 1,
      }
      if (type == 'post') {
        if(index==3){//微帖
            delete json.search;
            json.title = this.keywords;
        }
        if(index==4){
          delete json.search;
          json.search.title = this.keywords;
        }

        this.fun.$post(url, json, '正在获取').then(res => {
          if (res.result == 1) {
            if(index==4){
              this.$store.commit("setSearchGoods",res.data.list);
              return;
            }
            this.$store.commit("setSearchGoods", res.data);
          } else {
            this.$store.commit("setSearchGoods",'');
            this.$message.error(res.msg);
          }
        })
      }
      if (type == 'get') {
        if (index == 1) { //文章
          json.category_id = 0;
          json.pageSize = 12
        }
        if(index==2){ //知识库
          delete json.search;
          json.keyword = this.keywords;
          json.show_type==1;
        }
        this.fun
          .$get(url,json,"正在获取").then(res => {
            if (res.result === 1) {
              if(index==1){//文章
                this.$store.commit("setSearchGoods", res.data.articles);
              }
              if(index==2){ //知识库
                let data = this.filterList(res.data.data)
                console.log(data,"data===");
                this.$store.commit("setSearchGoods",{
                  data,
                  total:res.data.total,
                  page:res.data.current_page,
                  per_page : res.data.per_page
                })
              }
            } else {
              this.$store.commit("setSearchGoods",'');
              this.$message.error(res.msg);
            }
          })
      }
    },

    filterList(list) {
      if (!Array.isArray(list)) {
        return [];
      }
      if (!this.keywords) return list;
      let str = new RegExp(this.keywords, 'g');
      let replaceStr = `<span style="color:#eb8383">${this.keywords}</span>`
      let mapList = list.map((item) => {
        item.article_name = item.article_name.replace(str, replaceStr);
        item.article = item.article.replace(str, replaceStr);
        return item;
      });
      return mapList;
    },

    toUrl(url, params) {
      if (url == 'login') {
        sessionStorage.setItem("yz_redirect", document.location.href);
      }
      this.$router.push(this.fun.getUrl(url, params));
    },
    handleScroll() {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop > 33 && this.top_type == 'other') {
        this.headOver = true;
      } else {
        this.headOver = false;
      }
    },
    gotoUrl(_url) {
      if (_url) {
        window.location.href = _url;
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.fixed-wrap {
  width: 100%;
  /*position: fixed;*/
  z-index: 999;
  min-width: 1200px;

  .welcome {
    height: 32px;
    background-color: #e9e8e8;
    transition: all 0.35s linear;

    .welcome-content {
      width: 1200px;
      margin: 0 auto;
      box-sizing: border-box;
      height: 32px;

      .welcome-left {
        font-size: 14px;
        color: $red;

        .tips {
          color: #666666;
          margin-right: 40px;
        }

        .logo-box {
          cursor: pointer;

          span {
            margin: 0 5px;
          }
        }
      }

      .welcome-right {
        font-size: 14px;
        margin-right: 10px;
        color: #333;

        .mobile_version {
          position: relative;

          .hide_block {
            display: none;
            text-align: center;
            position: absolute;
            left: -30px;
            top: 35px;
            width: 150px;
            height: 167px;
            padding-bottom: 18px;
            padding-top: 25px;
            background-color: #ffffff;
            box-shadow: 0px 2px 10px 0px rgba(171, 171, 171, 0.28);
            box-sizing: border-box;

            .mini_code {
              width: 90px;
              height: 90px;
              background-color: #c5c5c5;
              margin-bottom: 17px;

              #qrccode-canvas {
                width: 90px !important;
                height: 90px !important;
              }

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

            &::after {
              content: "";
              position: absolute;
              left: 50%;
              transform: translate(-50%, -100%);
              top: 0;
              width: 0;
              height: 0;
              border-left: 10px solid transparent;
              border-right: 10px solid transparent;
              border-bottom: 10px solid $white;
            }
          }

          &:hover .hide_block {
            display: block;
          }
        }

        div {
          cursor: pointer;
        }

        .icon-item {
          display: flex;
          align-items: center;
          margin-right: 12px;

          img {
            width: 16px;
            height: 16px;
            margin-right: 12px;
          }

          .icon-item-text {
            height: 14px;
            font-size: 14px;
            line-height: 14px;
            padding-right: 12px;
            border-right: 1px solid #999;
          }
        }
      }
    }
  }

  .header {
    height: 100px;
    background-color: #fff;
    box-shadow: 0px 2px 10px 0px rgba(171, 171, 171, 0.28);

    .top {
      width: 1200px;
      margin: 0 auto;
      // padding: 0 0 0 30px;
      box-sizing: border-box;

      .myCar {
        width: 150px;
        height: 40px;
        background-color: #e8e8e8;
        border-radius: 25px;
        font-size: 15px;
        color: #333;
        cursor: pointer;

        .icon-htmal5icon29 {
          font-size: 24px;
          color: $red;
          margin-right: 8px;
        }
      }

      .sousuo {
        flex: 1;
        margin-right: 20px;
        justify-content: flex-start;

        .input {
          width: 400px;
          height: 40px;
          border-radius: 25px;
          border: solid 1px #c9c9c9;
          font-size: 15px;
          overflow: hidden;

          input {
            border: none;
            outline: none;
            padding: 0 10px 0 30px;
            color: #666666;
            font-size: 15px;
            width: 80%;
            box-sizing: border-box;
          }

          .button {
            flex: 1;
            height: 100%;
            background-color: var(--color);
            cursor: pointer;
            color: $white;
            font-size: 18px;

            i {
              font-size: 28px;
            }
          }
        }

        .input-template-02 {
          width: 460px;
          height: 60px;
          background-color: #eeeeee;
          border-radius: 6px;
          border: none;

          input {
            height: 100%;
            background-color: #eeeeee;
          }

          .button {
            background: var(--color);
          }
        }
      }

      .left {
        display: flex;
        cursor: pointer;

        img {
          width: 480px;
          align-self: center;
          height: 70px;
        }

        span {
          font-weight: 900;
          font-size: 18px;
          display: inline-block;
          align-self: flex-end;
        }

        .advert_words {
          display: inline-block;
          width: 300px;
        }
      }

      .right {
        margin-left: 273px;
        flex: 1;

        .icon:last-child {
          margin-right: 0;
        }

        .icon {
          img {
            margin-right: 7px;
            width: 20px;
            height: 20px;
          }

          span {
            font-size: 18px;
            color: #333333;
            font-weight: normal;
          }
        }
      }

      .top-adimg {
        width: 268px;
        height: 82px;

        img {
          display: block;
          width: 100%;
          height: 100%;
          object-fit: contain;
        }

        &:hover {
          cursor: pointer;
        }
      }
    }

    .right-img {
      width: 500px;
      height: 70px;

      img {
        width: 500px;
        height: 70px;
      }
    }
  }

  .hide-shadow {
    box-shadow: none;
  }
}
</style>
