<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import { useRoute } from "vue-router";
import { Sticky, Icon, ImagePreview,Popup,Toast,Dialog } from "vant";
import moment from "moment";
import 'moment/dist/locale/zh-cn';
moment.locale('zh-cn');
import _ from "lodash";
import * as priceApi from "@/api/hzyb/pricedriven.js";
import {apiApplyPermission,apiUserInfo} from '@/api/hzyb/user';
import SharePoster from "../components/SharePoster.vue";

document.title = "价格驱动";

const route = useRoute();
localStorage.setItem("hzyb-token", route.query.token);

let userInfo=ref(null)
const getUserInfo=async ()=>{
  const res=await apiUserInfo()
  if(res.code===200){
    userInfo.value=res.data
  }
}
getUserInfo()



const noAuthInfo = ref(null); //无权限信息
/* 分类 */
const varietiesList = ref([]);
const classifyList = ref([]);
const select_classify_first = ref(""); //选中的品种
const select_classify_sub = ref(""); //选中的分类id
const select_classify_subtitle = ref(""); //选中分类名称
/* 获取分类 */
const getClassify = async () => {
  const { code, data } = await priceApi.tabList();
  // const {code, data} = await priceApi.tabTree()
  if (code === 200) {
    //const { permission_list } = data;
    const result = data
    const permission_list = result.map((item,index)=>{
      let obj = {}
      obj.classify_name = item.classify_name
      obj.id = item.classify_id
      obj.list = item.tags.map((i)=>{
        return {tag_id:i.tag_id,tag_name:i.tag_name,pirce_driven_state:i.price_driven_state}
      })
      return obj
    })
    console.log(permission_list);

    permission_list.forEach(_ => {
      _.isShow = _.list ? _.list.some(sub_item => sub_item.pirce_driven_state) : false
    })
    varietiesList.value = permission_list.filter(_ => _.isShow);
    // 分享进入的默认品种
    if (route.query.default_classify_first) {
      let index = varietiesList.value.findIndex(
        (_) => _.id === Number(route.query.default_classify_first)
      );
      index === -1 ? errorLinkHandle() : changeClassify(varietiesList.value[index],'share');
    } else {
      changeClassify(varietiesList.value[0]);
    }
  } else if (code === 403) {
    noAuthInfo.value = data;
  }
};
getClassify();
/* 选择一级分类 */
const changeClassify = (item,type='') => {
  const { id, list } = item;
  select_classify_first.value = id;
  classifyList.value = list.filter(_ => _.pirce_driven_state);

  //分享进入的默认品种
  if (type === 'share') {
    let index = classifyList.value.findIndex(
      (_) => _.tag_id === Number(route.query.default_classify_sub)
    );
    index === -1 ? errorLinkHandle() : changeSubClassify(classifyList.value[index]);
  } else {
    changeSubClassify(classifyList.value[0]);
  }
};
/* 选择二级分类 */
const changeSubClassify = ({ tag_id, tag_name }) => {
  select_classify_subtitle.value = tag_name;
  select_classify_sub.value = tag_id;
  page_no.value = 0;
  handleBackTop();
  getDetail();

};
/* 过期link处理 */
const errorLinkHandle = () => {
  Toast('该价格驱动不存在')

  setTimeout(() => {
    wx.miniProgram.switchTab({ 
      url:"/pages/report/report"
    });
  },1000)
}

//详情信息
const showData = ref(false);
const info = ref({});
/* 获取详情 */
const getDetail = async () => {
  showData.value = false;
  const { code, data } = await priceApi.priceDrivenDetail({
    variety_tag_id: select_classify_sub.value,
  });

  if (code !== 200) return;
  showData.value = true;
  info.value = data;
  splitContentHandle(data.core_content);

   //向小程序发送分享数据
  wx.miniProgram.postMessage({ 
      data: {
          title:`${select_classify_subtitle.value}价格驱动`,
          default_classify_first: select_classify_first.value,
          default_classify_sub: select_classify_sub.value,
      }
  });
  info.value.price_driven_id && visitPriceDrivenLog()
};
const visitPriceDrivenLog = async() => {
  await priceApi.priceDrivenLog({
    price_driven_id: info.value.price_driven_id
  })
}

//申请弹窗信息
const pupData = ref({
  show:false,
  content:'',
})
//点击申请
const handleGoApply = async () => {
  if(userInfo.value.is_bind===0){
    Dialog.confirm({
      title:'温馨提示',
      message:'为了优化您的用户体验，\n 请登录后查看更多信息！',
      confirmButtonText:'去登录',
      confirmButtonColor:'#E6B77D',
      cancelButtonColor:'#666'
    }).then(res=>{
      wx.miniProgram.reLaunch({url:'/pages/login'})
    })
    return
  }
  if (noAuthInfo.value.customer_info.has_apply) {
    // 已经申请过
    pupData.value.show = true;
    pupData.value.content = `<p>您已提交过申请，请耐心等待</p>`;
  } else {
    if (
      !noAuthInfo.value.customer_info.status ||
      noAuthInfo.value.customer_info.status !== "流失"||noAuthInfo.value.customer_info.status !== "关闭"
    ) {
      wx.miniProgram.navigateTo({
        url: "/pages-applyPermission/applyPermission?source=6&from_page=价格驱动",
      });
    } else {
      //主动调一次申请权限接口
      const res = await apiApplyPermission({
        company_name: noAuthInfo.value.customer_info.company_name,
        real_name: noAuthInfo.value.customer_info.name,
        source: 6,
        from_page: "价格驱动",
      });
      if (res.code !== 200) return 
      pupData.value.show = true;
      pupData.value.content = `<p>申请已提交</p><p>请等待销售人员与您联系</p>`;
    }
  }
};

/* 内容分页 */
const showToTop = ref(false)
const totalContent = ref([]);
const realContent = ref([]);
const page_no = ref(0);
const pageSize = ref(20); //默认初始加载20个p标签
const total_page = ref(0);
/*内容分割*/
const splitContentHandle = (content) => {
  const arr = content.split("</p>");
  totalContent.value = arr.map((_) => _ + "</p>");
  realContent.value = totalContent.value.slice(0, pageSize.value);
  total_page.value = parseInt(totalContent.value.length / pageSize.value) + 1;
};
/* 加载下一页内容 */
const loadContent = () => {
  realContent.value = realContent.value.concat(
    totalContent.value.slice(
      page_no.value * pageSize.value,
      (page_no.value + 1) * pageSize.value
    )
  );
};
const loadMoreHandle = _.throttle(function () {
  const scrollTop =
    document.documentElement.scrollTop || document.body.scrollTop; // 滚动的高度

    showToTop.value = scrollTop>window.outerHeight ? true :false

  if (page_no.value >= total_page.value) return;

  const clientHeight =
    document.documentElement.clientHeight || document.body.clientHeight; // 可视高度
  const scrollHeight = document.body.scrollHeight; // 总高度
  const bufferHeight = 100;

  if (scrollHeight - scrollTop - clientHeight < bufferHeight) {
    console.log("触底");
    page_no.value = page_no.value + 1;
    loadContent();
    
  }
}, 300);

  //返回顶部
  const handleBackTop = () => {
      document.body.scrollTop=document.documentElement.scrollTop=0
  }


/* 分享海报参数 */
const code_scene = computed(() =>
  JSON.stringify({
    default_classify_first: select_classify_first.value,
    default_classify_sub: select_classify_sub.value,
  })
);
const posterParams = computed(() => ({
  list_title: `${select_classify_subtitle.value}价格驱动`,
  core_driven_type: info.value.core_driven_type ? "空" : "多",
  main_variable: info.value.main_variable,
  update_time: moment(info.value.modify_time).format("YYYY-MM-DD ddd"),
  core_driven_content: info.value.core_driven_content,
}));

let showPreViewImg = ref(false);
let preViewImgs = ref([]);
let preViewImgIndex = ref(0);
const VanImagePreview = ImagePreview.Component;
onMounted(() => {
  $(document).on("click", ".rich-section img", function (event) {
    let imgArray = [];
    let curImageSrc = $(this).attr("src");
    let oParent = $(this).parent();
    if (curImageSrc && !oParent.attr("href")) {
      $(".rich-section img").each(function (index, el) {
        let itemSrc = $(this).attr("src");
        imgArray.push(itemSrc);
      });
      preViewImgs.value = imgArray;
      preViewImgIndex.value = imgArray.indexOf(curImageSrc) || 0;
      showPreViewImg.value = true;
    }
  });
  window.addEventListener("scroll", loadMoreHandle);
});
onUnmounted(() => {
  window.removeEventListener("scroll", loadMoreHandle);
});
</script>

<template>
  <div class="pricedriven-container">
    <Sticky v-if="varietiesList.length">
      <div class="classify-cont">
        <ul class="classsify-frist">
          <li
            :class="[
              'classify-frist-item',
              { act: select_classify_first === item.id },
            ]"
            v-for="(item, index) in varietiesList"
            :key="item.id"
            @click="changeClassify(item, index)"
          >
            {{ item.classify_name }}
          </li>
        </ul>
        <ul class="classsify-sub">
          <li
            :class="[
              'classify-sub-item',
              { act: select_classify_sub === item.tag_id },
            ]"
            v-for="item in classifyList"
            :key="item.tag_id"
            @click="changeSubClassify(item)"
          >
            {{ item.tag_name }}
          </li>
        </ul>
      </div>
    </Sticky>

    <template v-if="showData">
      <!-- 内容 -->
      <div class="richtext-container" v-if="info.core_content">
        <div class="section">
          <h3>更新时间:</h3>
          <p class="time">
            {{ moment(info.modify_time).format('YYYY年MM月DD日 ddd') }}
            <img
              src="@/assets/hzyb/pricedriven/new_ico.png"
              alt=""
              class="new_tag"
              v-if="
                moment(info.modify_time).format('YYYY-MM-DD') ===
                moment().format('YYYY-MM-DD')
              "
            />
          </p>
        </div>
        <div class="section">
          <h3>关键变量:</h3>
          <p>{{ info.main_variable }}</p>
        </div>
        <div class="section">
          <h3 class="flex">
            核心驱动:
            <div :class="['tag flex', info.core_driven_type ? 'down' : 'up']">
              <span style="margin-right: 5px">
                {{ info.core_driven_type ? "空" : "多" }}</span
              >
              <icon :class="info.core_driven_type ? 'down-ico' : 'up-ico'" />
            </div>
          </h3>
          <p
            :class="info.core_driven_type ? 'down' : 'up'"
            style="padding: 20px 17px"
          >
            {{ info.core_driven_content }}
          </p>
        </div>
        <div class="rich-section">
          <h3>核心内容:</h3>
          <div>
            <ul>
              <li v-for="item in realContent" :key="item" v-html="item"></li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 无数据 -->
      <div class="no-auth-wrap" v-else>
        <div class="apply-box">
          <img src="@/assets/hzyb/nodata.png" alt="" class="nodata-img" />
          <div>暂无数据</div>
        </div>
      </div>
    </template>

    <!-- 分享海报 -->
    <Teleport to="body">
      <!-- code_page:'pages/pricedriven/pricedriven', -->
      <SharePoster
        :style="{ bottom: '125px' }"
        :shareData="{
          type: 'price_driven',
          code_page: 'pages/pricedriven/pricedriven',
          code_scene: code_scene,
          data: posterParams,
        }"
        v-if="info.core_content"
      ></SharePoster>
    </Teleport>

    <van-image-preview
      v-model:show="showPreViewImg"
      :start-position="preViewImgIndex"
      :images="preViewImgs"
    />

    <!-- 无权限 -->
    <div class="no-auth-wrap no-auth" v-if="noAuthInfo">
      <div class="apply-box" v-if="noAuthInfo.type === 'contact'">
        <img src="@/assets/hzyb/nodata.png" alt="" class="nodata-img" />
        <div style="margin-bottom: 10px;">您暂无权限查看价格驱动</div>
        <div>若想查看请联系对口销售</div>
        <div>
          {{ noAuthInfo.name }}：
          <a :href="'tel:' + noAuthInfo.mobile" style="color: #e3b377">{{ noAuthInfo.mobile }}</a>
        </div>
      </div>
      <div class="apply-box" v-else>
        <img src="@/assets/hzyb/nodata.png" alt="" class="nodata-img" />
        <div>您暂无权限查看价格驱动，若想查看请申请开通</div>
        <div class="btn" @click="handleGoApply">立即申请</div>
      </div>
    </div>

    <!-- 返回顶部 -->
    <img v-if="showToTop&&info.core_content" @click="handleBackTop" class="back-top-img" src="@/assets/hzyb/report/back-top.png" mode="aspectFill"/>

    <!-- 申请提示弹窗 -->
    <Popup :show="pupData.show" @close="pupData.show=false" :close-on-click-overlay="false">
        <div class="global-pup">
            <div class="content">
                <div v-html="pupData.content"></div>
            </div>
            <div class="flex bot">
                <div @click="pupData.show=false">知道了</div>
            </div>
        </div>
    </Popup>
  </div>
</template>

<style lang="scss" scoped>
.pricedriven-container {
  padding-bottom: calc(60px + constant(safe-area-inset-bottom));
  padding-bottom: calc(60px + env(safe-area-inset-bottom));
  .flex {
    display: flex;
  }
  .classify-cont {
    padding: 40px 34px 16px;
    color: #666;
    box-shadow: 0px 4px 4px 1px rgba(198, 198, 198, 0.25);
    background: #fff;
    .classsify-frist {
      display: flex;
      align-items: center;
      .classify-frist-item {
        min-width: 100px;
        text-align: center;
        padding: 14px;
        background: #f5f5f5;
        border-radius: 4px;
        margin-right: 30px;
        &:last-child {
          margin-right: 0;
        }
        &.act {
          background: #fdf8f2;
          color: #e3b377;
        }
      }
    }
    .classsify-sub {
      margin-top: 30px;
      overflow-x: auto;
      display: flex;
      align-items: center;
      &::-webkit-scrollbar {
        display: none;
      }
      .classify-sub-item {
        margin-right: 50px;
        flex-shrink: 0;
        position: relative;
        padding-bottom: 8px;
        border-bottom: 6px solid transparent;
        &.act {
          color: #e3b377;
          border-color: #e3b377;
        }
      }
    }
  }
  .richtext-container {
    line-height: 1.8;
    .section {
      font-size: 28px;
      padding: 40px 0;
      border-bottom: 1px solid #f1f1f1;
      > h3 {
        font-size: 32px;
        padding: 0 34px;
      }
      > p {
        color: #666;
        margin-top: 20px;
        padding: 0 34px;
      }
      .time {
        display: flex;
        align-items: center;
        .new_tag {
          width: 37px;
          height: 39px;
          margin-left: 20px;
        }
      }
      .tag {
        font-size: 28px;
        padding: 0 8px;
        border: 1px solid transparent;
        border-radius: 4px;
        margin-left: 20px;
        align-items: center;
      }
      .up {
        background: #feefef;
        color: #d64c4c;
      }
      .down {
        background: #ebfff0;
        color: #4fc08d;
      }
      .down-ico {
        width: 30px;
        height: 30px;
        background: url("@/assets/hzyb/pricedriven/arrow_down.png") no-repeat
          center;
        background-size: cover;
      }
      .up-ico {
        width: 30px;
        height: 30px;
        background: url("@/assets/hzyb/pricedriven/arrow_up.png") no-repeat
          center;
        background-size: cover;
      }
    }
    .rich-section {
      padding: 40px 34px;
      ::v-deep(img) {
        width: 100% !important;
      }
      ::v-deep(span) {
        font-size: 36px !important;
        line-height: 1.8 !important;
      }
      ::v-deep(p) {
        font-size: 36px !important;
        line-height: 1.8 !important;
      }
      ::deep(iframe){
        width: 1000% !important;
      }
    }
  }

  .no-auth-wrap {
    min-height: 200px;
    padding: 0 34px 50px 34px;
    background: linear-gradient(
      360deg,
      #ffffff 60%,
      rgba(255, 255, 255, 0) 88%
    );
    position: fixed;
    left: 0;
    right: 0;
    top: 15%;
    z-index: 99;
    text-align: center;
    font-size: 32px;
    color: #999;
    &.no-auth {
      top: 0;
    }
    .apply-box {
      padding-top: 30px;
    }
    .nodata-img {
      width: 682px;
      height: 558px;
    }
    .btn {
      width: 60%;
      margin-left: auto;
      margin-right: auto;
      line-height: 80px;
      background-color: #e6b77d;
      border-radius: 80px;
      color: #fff;
      font-size: 28px;
      margin-top: 100px;
      display: block;
    }
  }

  .global-pup{
    background-color: #fff;
    width: 90vw;
    min-height: 200px;
    font-size: 32px;
    .content{
        padding: 34px;
        text-align: center;
        min-height: 250px;
        display: flex;
        align-items: center;
        text-align: center;
        line-height: 1.7;
        div{
            flex: 1;
        }
    }
    .bot{
        border-top: 1px solid #dedede;
        div{
            line-height: 96px;
            flex: 1;
            text-align: center;
            border-right: 1px solid #dedede;
            color:#E3B377;
        }
        div:last-child {
            border: none;
        }
    }
  }
  .back-top-img{
    position: fixed;
    z-index: 99;
    width: 76px;
    height: 76px;
    right: 34px;
    bottom: 150px;
  }
}
</style>

<style lang="scss">
  p[data-f-id="pbf"] {
    display: none !important;
  }
</style>
