<template>
    <page-meta :page-style="showFilter? 'overflow: hidden;' : ''" :scroll-top="pageMetaScrollTop" />
    <view class="chart-page" v-if="hasAuth">
      <van-sticky style="background: #fff">
        <view class="flex search-wrap">
            <van-search
                shape="round"
                :value="searchVal"
                placeholder="图表名称搜索"
                @change="searchValChange"
                @search="onSearch"
                @clear="onClearSearch"
                clear-trigger="always"
                style="flex:1"
            />
            <image
              src="../../static/chart/menu.png"
              mode="widthFix"
              class="menu-icon"
              @click="showFilter=true"
            />
        </view>
      </van-sticky>
      <view class="empty-box" v-if="list.length==0&&finished">
        <image
          :src="globalImgUrls.chartEmpty"
          mode="widthFix"
        />
        <view v-if="searchVal">暂时找不到对应图，试试别的搜索词吧~</view>
        <view v-else>
          <text v-if="myClassifyList.length==0&&pubClassifyList.length==0">暂时没有图分类，请耐心等待</text>
          <text v-else>暂时找不到对应图，试试别的分类吧~</text>
        </view>
      </view>
      <view class="chart-list-wrap" v-else>
        <drag
          v-if="list.length>0"
          ref="chartDragIns"
          generic:item="chart-item"
          :columns="2"
          :list-data="list"
          :itemHeight="400"
          :searchVal="searchVal"
          @sortend="chartSortend"
          @click="chartClick"
          @scroll="chartScroll"
          :scroll-top="scrollTop"
        ></drag>
      </view>
      

      <!-- 分享海报 -->
      <sharePoster 
        :style="{bottom:'250rpx'}" 
        :shareData="{
          type:'chart_list',
          code_page:'pages/chart/chart',
          code_scene:'',
          data:shareParams
        }"
        v-if="showPoster"
      ></sharePoster>
    </view>

    <!-- 无权限 -->
    <noAuth :info="noAuthData" v-else></noAuth>
    
    <!-- 筛选弹窗 -->
      <van-popup 
        :show="showFilter" 
        @close="showFilter=false"
        position="bottom"
        closeable
        round
        z-index="99999"
      >
        <view class="filter-wrap">
          <view class="top">
            <text class="left" @click="goAllTypes">展开</text>
            <text class="center">全部筛选</text>
          </view>
          <view class="filter-list" style="padding-top:200rpx;text-align:center" v-if="myClassifyList.length==0&&pubClassifyList.length==0">
            暂时没有图分类，请耐心等待
          </view>
          <view class="filter-list" v-else>
            <view class="title" v-if="userInfo.is_inner==1">公共图库</view>
            <view 
              :class="['filter-item',selectClassifyId==item.myChartClassifyId?'active':'']" 
              v-for="item in pubClassifyList" 
              :key="item.myChartClassifyName"
              @click="handleSelectClassify(item,true)"
            >{{item.myChartClassifyName}}</view>
            <block v-if="myClassifyList.length>0">
            <view class="title" style="border:none">我的图库</view>
            <dragSorts
              :list="myClassifyList"
              :selectId="selectClassifyId"
              :rowHeight="rowHeight"
              :listHeight="classifyListHeight+20"
              @onclick="myClassifyClick"
              @confirm="myClassifyMoveEnd"
            ></dragSorts>
            </block>
          </view>
        </view>
      </van-popup>

    
</template>

<script>
import chartItem from './component/chartItem.vue'
import dragSorts from '../../components/chartClassifyItem/HM-dragSorts.vue'
import noAuth from './component/noAuth.vue'
import sharePoster from '../../components/sharePoster/sharePoster.vue'
import {apiChartList,apiChartClassifyList,apiChartMove,apiClassifyMove} from '@/api/chart'
export default {
    components: {
      'chart-item':chartItem,
      dragSorts,
      noAuth,
      sharePoster
    },
    computed: {
      shareParams(){//生成海报要的数据
        let obj={
          list_title:'ETA图库',
          title_1:'',
          img_1:'',
          title_2:'',
          img_2:'',
        }
        if(this.list[0]){
          obj.title_1=this.list[0].ChartName
          obj.img_1=this.list[0].ChartImage
        }
        if(this.list[1]){
          obj.title_2=this.list[1].ChartName
          obj.img_2=this.list[1].ChartImage
        }
        return obj
      }
    },
    data() {
        return {
          list:[],
          page:1,
          finished:false,
          chartDragIns:null,//图表拖拽实例
          pageMetaScrollTop:0,
          scrollTop:0,

          showFilter:false,//显示筛选弹窗
          pubClassifyList:[],//公共图库分类数据
          myClassifyList:[],//我的图库分类数据
          selectClassifyId:0,//选中的分类id
          isPublic:false,//是否当前显示的列表数据为公共图库数据
          classifyListHeight:0,//我的分类默认高度
          rowHeight:44,

          searchVal:'',//图库搜素关键词

          hasAuth:true,//是否有权限
          noAuthData:null,//没有权限时传给无权限组件的值

          showPoster:true
        }
    },
    onLoad() {
      this.getClassifyList('first')
      this.addEventListenerSelectClassify()
    },
    onShow() {
      this.showPoster=true
      this.getClassifyList()
      // if(!this.hasAuth){
      //   this.getClassifyList()
      // }
    },
    onHide() {
      this.showPoster=false
    },
    onUnload(){
      uni.$off('classifyPageSelect')
    },
    onPullDownRefresh() {
      this.initPage()
      this.getClassifyList('first')
      setTimeout(() => {
        uni.stopPullDownRefresh()
      }, 1500)
    },
    onReachBottom() {
        if (this.finished) return
        this.page++
        this.getList()
    },
    onShareAppMessage(res) {
        return {
            title: 'ETA图库',
            path: ''
        }
    },
    onPageScroll({ scrollTop }) {
      this.scrollTop=scrollTop
    },
    methods: {
      // 获取列表
      async getList(){
        this.scrollTop=0
        this.pageMetaScrollTop=0
        const res=await apiChartList({
          Page:this.page,
          Limit:20,
          ClassifyId:this.selectClassifyId,
          Keywords:this.searchVal
        })
        if(res.code===200){
          this.hasAuth=true
          if(res.data){
            // 公共图库分类下数据不允许拖动
            let arr=res.data.map(item=>{
              return {...item,dragId:item.UniqueCode,fixed: this.isPublic?true:false}
            })
            this.list=[...this.list,...arr]
            setTimeout(() => {
              this.chartDragIns=this.$refs.chartDragIns
              this.chartDragIns.init();// 初始化列表
            }, 100);
          }else{
            this.finished=true
          }
        }else if(res.code===403){//无权限
          this.hasAuth=false
          this.noAuthData=res.data
        }
      },

      //图表移动排序结束
      async chartSortend(e){
        // curIndex 为排序前元素所在位置  listData为排序后的数组
        let {curIndex,listData}=e.detail
        const moveTarget=this.list[curIndex]
        console.log(moveTarget.ChartName);
        // 找到移动后所在位置
        const endIndex=listData.findIndex(item=>item.MyChartId===moveTarget.MyChartId)
        console.log('移动结束后序号：',endIndex);

        const NextMyChartId=listData[endIndex+1]&&listData[endIndex+1].MyChartId||0
        const PrevMyChartId=listData[endIndex-1]&&listData[endIndex-1].MyChartId||0

        const res=await apiChartMove({
          MyChartId:moveTarget.MyChartId,
          MyChartClassifyId:this.selectClassifyId,
          PrevMyChartId:PrevMyChartId,
          NextMyChartId:NextMyChartId,
        })
        if(res.code===200){
          this.list=listData
          setTimeout(() => {
            this.chartDragIns.init();
          }, 100);
        }else{
          uni.showToast({
            title: '移动失败',
            icon: 'none'
          })
        }
      },

      // 图表点击某项
      chartClick(e){
        console.log(e.detail.data);
        const { ChartInfoId,MyChartId,Source } = e.detail.data;
        uni.navigateTo({
          url:`/pages-chart/chartDetail?chartInfoId=${ChartInfoId}&searchVal=${this.searchVal}&MyChartId=${MyChartId}&MyChartClassifyId=${this.selectClassifyId}&chartSource=${Source}`
        })
      },

      // 图表移动时滚动
      chartScroll(e){
        uni.stopPullDownRefresh()
        this.pageMetaScrollTop=e.detail.scrollTop
      },

      // 获取分类数据
      async getClassifyList(no){
        const res=await apiChartClassifyList()
        if(res.code===200){
          this.myClassifyList=res.data.private_classify||[]
          this.pubClassifyList=res.data.public_classify||[]
          this.classifyListHeight=this.rowHeight*this.myClassifyList.length
          if(no=='first'){
            if(res.data.private_classify){
              this.selectClassifyId=res.data.private_classify&&res.data.private_classify[0].myChartClassifyId||''
              this.isPublic=false
            }else{
              this.selectClassifyId=res.data.public_classify&&res.data.public_classify[0].myChartClassifyId||''
              this.isPublic=true 
            }
            this.getList()
          }
          
        }else if(res.code===403){//无权限
          this.hasAuth=false
          this.noAuthData=res.data
        }
        
      },

      // 我的分类点击
      myClassifyClick(e){
        this.handleSelectClassify(e.value,false)
      },

      // 选中分类
      handleSelectClassify(item,isPublic){
        this.initPage()
        this.searchVal=''
        this.selectClassifyId=item.myChartClassifyId
        this.isPublic=isPublic
        this.getList()
        this.showFilter=false
      },

      // 跳转全部分类
      goAllTypes(){
        uni.navigateTo({ 
          url: '/pages-chart/allTypes?selectId='+this.selectClassifyId
        })
        this.showFilter=false
      },

      // 分类移动
      async myClassifyMoveEnd(e){
        const moveTarget=e.moveRow
        const index=e.moveTo// 拖动后的序号
        const list=e.list//拖动后的列表
        // console.log(moveTarget.myChartClassifyId);
        // console.log(index);
        // console.log(list);
        const PrevClassifyId=list[index-1]&&list[index-1].myChartClassifyId||0
        const NextClassifyId=list[index+1]&&list[index+1].myChartClassifyId||0
        const res=await apiClassifyMove({
          MyChartClassifyId:moveTarget.myChartClassifyId,
          PrevClassifyId:PrevClassifyId,
          NextClassifyId:NextClassifyId
        })
        if(res.code===200){
          this.myClassifyList=list
        }else{
          uni.showToast({
            title: '移动失败',
            icon: 'none'
          })
        }
      },

      // 搜索关键词变化
      searchValChange(e){
        this.searchVal=e.detail
      },

      // 确认搜索 搜索图表下的都不允许拖动排序
      onSearch(){
        if(!this.searchVal){
          uni.showToast({
            title:"请输入搜索关键词",
            icon:'none'
          })
          return
        }
        this.initPage()
        this.isPublic=true
        this.getList()
      },

      // 清除搜索内容
      onClearSearch(){
        this.initPage()
        this.searchVal=''
        this.isPublic=false
        this.getClassifyList('first')
      },

      // 初始化页面数据 
      initPage(){
        this.page=1
        this.list=[]
        this.finished=false
        this.selectClassifyId=0
        this.pageMetaScrollTop=0
        this.scrollTop=0
      },

      // 监听分类页面选中分类事件
      addEventListenerSelectClassify(){
        uni.$on('classifyPageSelect',e=>{
            console.log(e);
            this.handleSelectClassify({myChartClassifyId:e.selectId},e.isPublic)
        })
      },
    }
}
</script>

<style lang="scss" scoped>
.chart-page {
    min-height: calc(100vh - calc(50px + constant(safe-area-inset-bottom)));
    min-height: calc(100vh - calc(50px + env(safe-area-inset-bottom)));
    background-color: #f9f9f9;
    position: relative;
}
.search-wrap {
    background-color: #fff;
    padding: 30rpx 34rpx;
    align-items: center;
    .menu-icon{
      width: 52rpx;
      height: 40rpx;
      display: block;
      flex-shrink: 0;
      margin-left: 30rpx;
    }
    .van-search{
      padding: 0;
    }
}
.chart-list-wrap{
  padding: 24rpx 15rpx;
}

.filter-wrap{
  .top{
    height: 105rpx;
    background: #FFFFFF;
    box-shadow: 0px 3rpx 6rpx rgba(206, 206, 206, 0.16);
    position: relative;
    .left{
      position: absolute;
      left: 34rpx;
      top: 50%;
      transform: translateY(-50%);
      font-size: 16px;
      color: #E3B377;
    }
    .center{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      font-size: 16px;
      color: #1F243A;
    }
  }
  .filter-list{
    height: 60vh;
    overflow-y: auto;
    .title{
      font-size: 16px;
      font-weight: bold;
      color: #1F243A;
      padding: 60rpx 0 30rpx 34rpx;
      border-bottom: 1px solid #E5E5E5;
    }
    .filter-item{
      padding: 20rpx 34rpx;
      border-bottom: 1px solid #E5E5E5;
      font-size: 14px;
      color: #1F243A;
    }
    .active{
      color: #E3B377;
    }
  }
}

.empty-box{
  text-align: center;
  font-size: 32rpx;
  color: #999;
  padding-top: 150rpx;
  image{
    width: 346rpx;
    margin-bottom: 57rpx;
  }
}
</style>