<script setup>
import { 
  apiReportIndexPageAuthList, 
  apiReportIndexPageList,
  apiReportIndexNewbanner,
  apiLatestNews,
  apiPublicBannerMark,
  apiPublicBannerList
} from '@/api/report'
import { onActivated, onMounted,onUnmounted, reactive, ref,nextTick} from "vue"
import Search from "@/components/Search.vue"
import SelfList from '@/components/SelfList.vue'
import { onBeforeRouteLeave , useRouter } from "vue-router"
import { ElMessageBox } from 'element-plus'
import moment from 'moment'
import 'moment/dist/locale/zh-cn'
moment.locale('zh-cn')

const router=useRouter()
// 实现头部的适配
const contentRef=ref('')
const headerRef=ref('')
let contentWidth=ref('')
let headerHight=ref('')

// 向小程序发送数据
const handleDataToXcx=()=>{
  const postData={
    path:'/pages/report/report',
    params:{},
    title:'FICC研报',
    shareImg:''
  }
  wx.miniProgram.postMessage({ data: postData })
}

// 获取最新资讯
let latestNewsList=ref([])
const getLatestNews=async ()=>{
  const res=await apiLatestNews({chart_permission_id:Number(selectSubType.value)})
  if(res.code===200){
    latestNewsList.value=res.data||[]
  }
}
//点击最新资讯跳转报告详情
const handleClickNews=item=>{
  router.push({
    path:'/report/detail',
    query:{
      reportId:item.ReportId
    }
  })
}

// 获取顶部权限分类数据
let authData=reactive({
  isBuy:false,
  contactInfo:null
})
let firstTypeList = ref([])//一级分类数据
let subTypeList = ref([])//二级分类数据
let selectFirstType = ref('')//选择的一级分类
let selectSubType = ref('')//选择的二级分类ID
const getTopPermissionList = async () => {
  const res = await apiReportIndexPageAuthList()
  if (res.code === 200) {
    firstTypeList.value = res.data.permission_list.filter(item => item.sort != 100000)
    clickFirstType(firstTypeList.value[0])
  
    authData.isBuy=res.data.check_flag
    authData.contactInfo=res.data.contact_info
  }
}
getTopPermissionList()

// 获取报告列表数据
let reportState = reactive({
  list: [],
  page: 1,
  pageSize: 20,
  finished: false,
  loading: false,
  dateArr: [],//日期数据
})
const getReportList = async () => {
  reportState.loading = true
  const res = await apiReportIndexPageList({
    chart_permission_id: Number(selectSubType.value),
    current_index: reportState.page,
    page_size: reportState.pageSize
  })
  reportState.loading = false
  if (res.code === 200) {
    if (res.data.paging.is_end) {
      reportState.finished = true
    }
    //处理数据
    if (res.data.list) {
      if(reportState.list.length==0){
        // 第一页数据
        reportState.list = res.data.list
        res.data.list.forEach(item => {
          reportState.dateArr.push(item.date)
        })
        document.body.scrollTop=document.documentElement.scrollTop=0
      }else {
        //判断是否前面已经有相同日期数据 有的话添加合并
        let arr = []
        let temTimearr = []
        res.data.list.forEach(item => {
          if (reportState.dateArr.includes(item.date)) {
            reportState.list.forEach(_item => {
              if (item.date === _item.date) {
                _item.sub_list = [..._item.sub_list, ...item.sub_list]
              }
            })
          } else {
            arr.push(item)
            temTimearr.push(item.date)
          }
        });
        reportState.list = [...reportState.list, ...arr]
        reportState.dateArr = [...reportState.dateArr, ...temTimearr]
      }
    }
  }
}

//点击顶部一级分类
const clickFirstType = (item) => {
  selectFirstType.value = item.classify_name
  subTypeList.value = item.list
  // clickSubType({props:{label:item.list[0].chart_permission_name,name:item.list[0].chart_permission_id}})
  clickSubType(item.list[0])
  nextTick(() => {
    resetHeaderWidthHandle();
  });
}
//点击二级分类
// const clickSubType = ({props}) => {
  // let item=null
  // subTypeList.value.forEach(_item=>{
  //   if(_item.chart_permission_id==props.name){
  //     item=_item
  //   }
  // })
const clickSubType = (item) => {
  selectSubType.value = item.chart_permission_id
  reportState.list = []
  reportState.page = 1
  reportState.finished = false
  getReportList()
  handleShowAuthData(item)
  getLatestNews()
}

// 判断是否要为已购用户且点击的品种没有权限
const handleShowAuthData=(e)=>{
  if(authData.isBuy){
    if(!e.auth_ok){
      const  htmlStr=`<p>您暂无该品种权限，若想查看请联系</p>
                      <p>对口销售${authData.contactInfo.name}:<span style="color:#F3A52F">${authData.contactInfo.mobile}</span></p>`
      ElMessageBox({
        title:'温馨提醒',
        message:htmlStr,
        center: true,
        dangerouslyUseHTMLString: true,
        confirmButtonText:'知道了',
        confirmButtonClass:'self-elmessage-confirm-btn'
      })
    }
  }
}

// 列表加载更多
const onLoad=()=>{
  reportState.page++
  getReportList()
}

// 获取上新公告
let newAnnounce=ref(null)
const getNewAnnounce=async ()=>{
  const res=await apiReportIndexNewbanner()
  if(res.code===200){
    newAnnounce.value=res.data
  }
}
// getNewAnnounce()

//跳转至研报分类页
// const handleGoMoreClassify = () => {
//   router.push({ path:'/report/classify' });
// };

//点击上新公告
const handleClickAnnounce=(data)=>{
  //redirect_type 0活动 1专栏
  if(data.redirect_type==0){
    router.push({
      path:'/activity/detail',
      query:{
        id:data.Activity.activityID
      }
    })
  }else{
    router.push({
      path:'/report/specialcolumndetail',
      query:{
        columnId:data.ClassifyIdSecond
      }
    })
  }
}

//格式化上新公告中的活动时间
const formatAnnounceActivityTime=(start,end)=>{
  const day = moment(start).format('YYYY-MM-DD');
  const startTime = moment(start).format('HH:mm');
  const endTime = moment(end).format('HH:mm');
  return `${day} ${startTime}-${endTime}`
}

//跳转报告详情
const handleGoReportDetail=(item)=>{
  if(['晨报','周报'].includes(item.classify_name_first)){
    router.push({
      path:'/report/chapterdetail',
      query:{
        chapterId:item.report_chapter_id
      }
    })
  }else{
    router.push({
      path:'/report/detail',
      query:{
        reportId:item.report_id
      }
    })
  }
  
} 

/* 重绘固定头宽度 */
const resetHeaderWidthHandle = () => {
  contentWidth.value = contentRef.value.offsetWidth+'px'
  headerHight.value = headerRef.value.offsetHeight-10+'px'
}

// banner data
const bannerDataList =ref([])

/* 点击了banner */
const bannerClickHandler = async (item) => {
   if(item.id==9999){
    router.push({
        path:'/report/surveyHistory',
    })
   }else {
    let source = sessionStorage.getItem('platformSource')
    const res = await apiPublicBannerMark({
      first_source: source == 'xcx' ? 2 : 3, //一级来源 1小程序移动 2小程序pc 3研报官网
      second_source: 1 ,//二级来源 1首页 2研报详情页
      id:item.id
    })
    if(res.code ==200){
      router.push({
        path:'/report/disseminatePage',
        query: {
          imgBg:item.jump_url_pc
        }
      })
    }
  }
  // 首页
}


// banner 获取列表
const getBannerlist = async () => {
    const res = await apiPublicBannerList({
      is_homepage:1
    })
    if(res.code ==200){
        bannerDataList.value = res.data
    }
}

let isMounted = ref(false);
onMounted(() => {
  isMounted.value = true;
  handleDataToXcx()
  window.addEventListener('resize',resetHeaderWidthHandle)
  getBannerlist()
});

onUnmounted(() => {
  window.removeEventListener('resize',resetHeaderWidthHandle)
})

// 格式化列表日期
const formatDate=(e)=>{
  const isSameYear=moment(e).isSame(new Date(), 'year');
  if(isSameYear){//今年
    return moment(e).format('MM.DD')+' '+ moment(e).format('ddd')
  }else{
    return moment(e).format('YY.MM.DD')+' '+moment(e).format('ddd')
  }
}

//组件激活时
onActivated(()=>{
  handleDataToXcx()
})


</script>
<template>
  <!-- 搜索 -->
  <template v-if="isMounted&&$route.path=='/report/index'">
    <teleport to="#reportIndex-in-head">
      <Search
        style="margin-top: 10px;"
        placeholder="请输入标题/关键词"
        :disabled="true"
        @click="$router.push({path:'/report/search'})"
      ></Search>
    </teleport>
  </template>
  <div class="hasrightaside-box report-index-page">
    <div class="content-box report-main" ref="contentRef">
      <div class="top-nav-wrap" ref="headerRef" :style="{'width':contentWidth}">
        <template v-if="bannerDataList.length > 0">
          <el-carousel height="90px" style="margin-bottom:20px;padding-right: 30px" :interval="4000" :indicator-position="bannerDataList.length==0?'none':''" :arrow="bannerDataList.length==0?'never':''" >
            <el-carousel-item @click="bannerClickHandler(item)" v-for="item in bannerDataList" :key="item.id" >
              <img style="width:100%;height:100%;cursor:pointer;" :src="item.image_url_pc" alt="">
            </el-carousel-item>
          </el-carousel>
        </template>
        <div class="flex first-nav">
          <!-- <div class="nav-move-box move-left"></div>
          <div class="nav-move-box move-right"></div> -->
          <div 
            :class="['item', item.classify_name == selectFirstType && 'item-active']" 
            v-for="item in firstTypeList" 
            :key="item.classify_name" 
            @click="clickFirstType(item)"
          >{{ item.classify_name }}</div>
          <!-- 查看更多 2022-10-17 研报和首页分开，不显示查看更多按钮 https://share.lanhuapp.com/#/invite?sid=lxeTdwAa -->
          <!-- <div class="see-more" @click="handleGoMoreClassify">查看更多</div> -->
        </div>
        <div class="sub-nav">
            <span 
              :class="['sub-item', item.chart_permission_id == selectSubType && 'sub-active']" 
              v-for="item in subTypeList" 
              :key="item.chart_permission_id" 
              @click="clickSubType(item)"
            >{{ item.chart_permission_name }}</span>
            <!-- <el-popover
              :width="500"
              trigger="click"
            >
              <template #reference>
                <img v-if="subTypeList.length>6" style="width:16px;transform: rotate(90deg);cursor: pointer" src="@/assets/icon-more.png" alt="">
              </template>
              <template #default>
                <div class="flex top-nav-filter-box">
                  <div 
                      :class="['item',item.chart_permission_id == selectSubType&&'active']" 
                      v-for="item in subTypeList.slice(6)" 
                      :key="item.chart_permission_id"
                      @click="clickSubType(item)"
                  >{{item.chart_permission_name}}</div>
                </div>
              </template>
            </el-popover> -->
          <!-- <el-tabs v-model="selectSubType" class="tabs-wrap" @tab-click="clickSubType">
            <el-tab-pane 
                :label="item.chart_permission_name" 
                :name="item.chart_permission_id"
                v-for="item in subTypeList" 
                :key="item.chart_permission_id"
            ></el-tab-pane>
          </el-tabs> -->
        </div>
      </div>
      <!-- 报告列表 -->
      <SelfList 
        :finished="reportState.finished" 
        :isEmpty="reportState.list.length === 0 && reportState.finished" 
        :loading="reportState.loading" 
        :count="reportState.list.length"
        @listOnload="onLoad"
      >
        <div class="report-list-wrap" :style="{'margin-top':headerHight}">
          <div class="item" v-for="item in reportState.list" :key="item.date">
            <div class="item-time">{{ formatDate(item.date) }}</div>
            <div class="content-list">
              <div class="content-item" v-for="citem in item.sub_list" :key="citem.report_id">
                <div class="content-box" @click="handleGoReportDetail(citem)">
                  <div class="all-btn">查看全部</div>
                  <div class="c-time">{{ moment(citem.publish_time).format('HH:mm:ss')  }}</div>
                  <div class="c-title">{{ citem.title }}</div>
                  <div class="desc" v-html="citem.content_sub"></div>
                  <div class="tags">
                    <span style="margin-right:30px" v-if="citem.classify_name_first">#{{ citem.classify_name_first }}</span>
                    <span v-if="citem.classify_name_second">#{{ citem.classify_name_second }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </SelfList>

    </div>
    <div class="right-aside-box" style="position: relative;z-index: 100;">
      <div class="fix-top" style="z-index: 100;">
        <div class="recmd-box">
          <div class="label">最新资讯</div>
          <div 
            class="recmd-item" 
            v-for="item in latestNewsList" 
            :key="item.report_id"
            @click="handleClickNews(item)"
          >
            <div class="title">{{item.classify_name_second}}</div>
            <div>{{item.stage}} | {{item.title}}</div>
          </div>
        </div>
        <!-- <div class="hot-box" style="margin-top: 60px;">
          <div class="label">上新公告</div>
          <div class="img-con" :style="'background-image:url('+newAnnounce.ImgUrl+')'" v-if="newAnnounce" @click="handleClickAnnounce(newAnnounce)">
            //活动的话要手搓文字上去 
            <div class="activity-con" v-if="newAnnounce.redirect_type==0">
              <div class="multi-ellipsis title">{{newAnnounce.Activity.activityTypeName}}</div>
              <div class="user-name">主讲人: {{newAnnounce.Activity.speaker}}</div>
              <div class="time">{{formatAnnounceActivityTime(newAnnounce.Activity.startTime,newAnnounce.Activity.endTime)}}</div>
            </div>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.top-nav-filter-box{
          flex-wrap: wrap;
          .item{
              margin: 5px 10px;
              width: 113px;
              height: 40px;
              display: flex;
              justify-content: center;
              align-items: center;
              background-color: #f6f6f6;
              border-radius: 4px;
              font-size: 16px;
              cursor: pointer;
              :hover{
                  color: #fff;
                  background-color: #F3A52F;
              }
          }
          .active{
              color: #fff;
              background-color: #F3A52F;
          }
}

.el-backtop{
  z-index: 1000;
}

.report-index-page {
  position: relative;
  .report-main {
    .top-nav-wrap {
      position: fixed;
      top: 60px;
      z-index: 99;
      background-color: #fff;
      padding-top: 30px;
      padding-bottom: 12px;
      // width: 100%;
      width: 1000px;
      .first-nav {
        // width: calc(100vw - 500px);
        width: 100%;
        overflow-x: auto;
        overflow-y: hidden;
        position: relative;
        &::-webkit-scrollbar{
          // height: 5px;
          display: none;
        }
        .item {
          width: 140px;
          height: 40px;
          flex-shrink: 0;
          background: #F6F6F6;
          border-radius: 20px;
          text-align: center;
          line-height: 40px;
          font-size: 16px;
          margin-right: 30px;
          cursor: pointer;
          &:hover {
            background: #FFFBF5;
            color: #F3A52F;
            border: 1px solid #F3A52F;
            box-shadow: 0px 6px 7px 1px #FFF7EB;
          }
        }
        .item-active {
          background: #FFFBF5;
          color: #F3A52F;
          border: 1px solid #F3A52F;
          box-shadow: 0px 6px 7px 1px #FFF7EB;
        }
        .see-more{
          height: 20px;
          flex-shrink: 0;
          color: #f3a52f;
          font-size: 16px;
          position: relative;
          top: 10px;
          margin-left: 30px;
          cursor: pointer;
          z-index: 1;
          &::after{
            content: '';
            display: inline-block;
            width: 16px;
            height: 16px;
            background-image: url('../../assets/icon-more.png');
            background-size: cover;
            position: relative;
            top: 2px;
            left: 5px;
          }
        }
        @media screen and (max-width: 1350px){
          .item{
            width: 90px;
            height: 30px;
            line-height: 30px;
            margin-right: 15px;
            font-size: 14px;
          }
          .see-more{
            font-size: 14px;
            margin-left: 10px;
            top: 5px;
          }
        }
      }

      .sub-nav {
        margin-top: 30px;
        // overflow-x: auto;
        overflow-y: hidden;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        // &::-webkit-scrollbar {
        //   display: none;
        // }
        // width: calc(100vw - 500px);
        .sub-item {
          flex-shrink: 0;
          margin-right: 30px;
          font-size: 16px;
          margin-bottom: 8px;
          color: #666666;
          cursor: pointer;
        }
        .sub-active {
          color: #F3A52F;
        }
        // :deep(.el-tabs__header){
        //   margin-bottom: 0;
        // }
        // :deep(.el-tabs__active-bar){
        //   display: none;
        // }
        // :deep(.el-tabs__nav-wrap::after){
        //     display: none;
        // }
        // :deep(.el-tabs__item.is-active){
        //     color: #F3A52F;
        // }
        // :deep(.el-tabs__item){
        //     font-size: 16px;
        //     // height: 22px;
        //     &:hover{
        //         color: #F3A52F;
        //     }
        // }
        // :deep(.el-tabs__nav-next){
        //     width: 20px;
        //     height: 20px;
        //     background-image: url('@/assets/icon-more.png');
        //     background-size: cover;
        //     top: 10px;
        //     .el-icon{
        //         display: none;
        //     }
        // }
        // :deep(.el-tabs__nav-prev){
        //     width: 20px;
        //     height: 20px;
        //     background-image: url('@/assets/icon-more.png');
        //     background-size: cover;
        //     top: 10px;
        //     transform: rotate(180deg);
        //     .el-icon{
        //         display: none;
        //     }
        // }
        // :deep(.el-tabs__nav-wrap.is-scrollable){
        //     padding: 0 25px;
        // }

      }
      
    }

    .report-list-wrap {
      margin-top: 130px;
      .item{
        margin-bottom: 30px;
      }
      .item-time {
        font-size: 16px;
        margin-bottom: 20px;
      }

      .content-list {
        padding-left: 20px;
        .content-box {
          padding: 0 0px 10px 14px;
          position: relative;
          .all-btn {
            position: absolute;
            right: 20px;
            bottom: 10px;
            width: 88px;
            height: 30px;
            line-height: 30px;
            background: #FFFBF5;
            border-radius: 15px;
            border: 1px solid #F3A52F;
            color: #F3A52F;
            font-size: 14px;
            text-align: center;
            cursor: pointer;
          }
        }

        .content-item {
          padding: 0 0 30px 20px;
          border-left: 1px solid #F3A52F;
          position: relative;

          &:last-child {
            border-bottom: none;
            padding-bottom: 0px;
          }

          &::before {
            content: '';
            display: block;
            box-sizing: border-box;
            width: 14px;
            height: 14px;
            border-radius: 50%;
            border: 3px solid #FADBAC;
            position: absolute;
            left: 0;
            top: 0;
            background: #F3A52F;
            transform: translate(-50%, -50%);
            z-index: 2;
          }

          &::after {
            content: '';
            display: block;
            width: 20px;
            height: 1px;
            background-color: #F3A52F;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1;
          }

          .c-time {
            position: relative;
            top: -8px;
            font-size: 14px;
            color: #666;
          }

          .c-title {
            font-size: 16px;
            font-weight: bold;
            word-wrap: break-word;
            white-space: normal;
            word-break: break-all;
            margin-top: 5px;
          }

          .desc {
            line-height: 1.5;
            margin-top: 10px;
            color: #666666;
            font-size: 14px;
            :deep(div){
              word-wrap: break-word;
              word-break: break-all;
            }
            word-wrap: break-word;
            word-break: break-all;
          }

          .tags {
            margin-top: 14px;
            color: #F3A52F;
            min-height: 30px;
          }
        }
      }
    }

  }
  .right-aside-box{
    .activity-con{
      padding: 17px 10px;
      .title{
        color: #fff;
        font-size: 16px;
        font-weight: bold;
      }
      .user-name{
        margin: 5px 0;
        font-size: 14px;
        color: #fff;
      }
      .time{
        font-size: 12px;
        color: #F3A52F;
      }
    }
  }
}
</style>
