<template>
  <div style="background: #FAFAFA;height: 100%;">
    <div class="contentAlbunMain">
      <div class="topBox">
        <div>
          <div class="numBox">
            <img src="../../../../image/analysis0.png"/>
            <div>{{format_number(totalData.knowledge)}}</div>
            <div>知识仓库总量</div>
          </div>
        </div >
        <div>
          <div class="numBox">
            <img src="../../../../image/analysis1.png"/>
            <div>{{format_number(totalData.map)}}</div>
            <div>知识地图总量</div>
          </div>
        </div>
        <div>
          <div class="numBox">
            <img src="../../../../image/analysis2.png"/>
            <div>{{format_number(totalData.album)}}</div>
            <div>知识专辑总量</div>
          </div>
        </div>
      </div>
      <div class="middleBox">
        <div class="topTitle" style="width: 240px;">
          <div>搜索访问量分布（pv）</div>
          <div>{{format_number(barTotalNum)}}
          </div>
          <div style="display:none">
            <div class="barNameBox" v-for="(item, index) in NameArr" :key="index">
              <div :style="{'background':colorbarArr[index]}"></div>
              <div>{{ item }}</div>
            </div>
          </div>
        </div>
        <div ref="eCharts0" class="barBox"></div>
      </div>
      <div class="bottomBox">
        <div class="bottomBoxLeft">
          <div class="topTitle textBorder">
            <div>高频搜索词</div>
          </div>
          <div ref="eCharts1" class="wordCloudBox"></div>
        </div>
        <div class="bottomBoxRight">
          <div class="topTitle">
            <div>知识类型分布</div>
            <div>{{format_number(pieTotalNum)}}</div>
          </div>
          <div ref="eCharts2" style="height: 100%;width: 100%;"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {mapState} from "vuex";
import analysis from '@/api/knowledge/analysis'
import * as echarts from 'echarts'
import 'echarts-wordcloud'
export default {
  name: 'albumIndex',
  components: {
  },
  computed: {
    ...mapState({
        user: (state) => state.appSetting.user,
    })
  },
  data() {
    return {
      pieTotalNum:0,
      barTotalNum:0,
      totalData:{},
      textData:[{
          "name": "花鸟市场",
          "value": 1446
      }],
      colorbarArr:['#406cc4','#00c8dc','#f84e4c','#ff900d','#ffbe00','#cacd96','#31339a','#67ce97','#cc9b97','#99ce64','#ccce00','#fb012e','#cb9b97','#003263','#2e3699','#cbfe65','#cb9bcb'],
      NameArr:[],
      delId:'',
      delVisible:false,
      scope:2,//1-我的专辑  2-全部专辑  3-我的点评
      searchName:'',
      categoryId:'',
      pageSize:6,
      total:18,
      pageNum:1,
      dataList:[],
      imgUrl: require('@img/avatar2.jpg'),
      menuArr:['知识地图','新人地图','岗位地图','制度地图'],
      actionMenu:0,
      level1Action:-1,
      level2Action:-1,
      showLevel1Num:-1,
      classifyArr:[],
      colorArr:['#1890ff','#3e4c84','#379eff','#379eff','#69d289','#facd1b']
    }
  },
  
  created() {
    if (this.user.photo && this.user.photo != '') {
      this.imgUrl = '/api/api-system/system/core/sysFile/previewFile?fileId='+this.user.photo
    }
    if(this.$router.query){
      if(this.$router.query.scope) {
        this.scope = this.$router.query.scope
      }
    }
  },
  mounted(){
    this.getTotalAmount();
    this.getSearchVisitHistogram();
    this.getKnowledgeTypeAmount();
    this.getSearchParticipleWordCloud();
  },
  methods: {
    //获取数量
    getTotalAmount(){
      analysis.totalAmount().then((res) => {
        this.totalData=res.data
      })
    },
    //搜索访问量分布
    getSearchVisitHistogram(){
      let that = this
      analysis.searchVisitHistogram().then((res) => {
        let barData=res.data
        that.barTotalNum=barData.total
        let xAxisData=barData.lables.map(item=>{return item.name})
        let seriesData=[]
        barData.lables.forEach((el, index) => {
          el.values.forEach((item,num) =>{
            if(index==0){
              that.NameArr.push(item.legend)
              let tempData={
                color:that.colorbarArr[num],
                name: item.legend,
                type: 'bar',
                barGap:'0%',
                barCategoryGap:'40%',
                stack: 'AllData',
                dataGroupId:11,
                stackStrategy:'all',
                emphasis: {
                  focus: 'series'
                },
                data: [{value:item.value,itemStyle:{ barBorderRadius: [0, 0, 0, 0] }}],
                percentage:[item.percentage]
              }
              /*if(num==(el.values.length-1)){
                tempData.itemStyle={
                  normal: {
                    //这里设置柱形图圆角 [左上角，右上角，右下角，左下角]
                    barBorderRadius:[6, 6, 0, 0]
                  }
                }
              }*/
              seriesData.push(tempData)
            }else{
              seriesData[num].data.push({value:item.value,itemStyle:{ barBorderRadius: [0, 0, 0, 0] }})
              seriesData[num].percentage.push(item.percentage)
            }
          })
        });
        //for (let i=(seriesData[0].data.length-1);i>-1;i--) { // 遍历所有的x轴数据(总数为n),为单根柱条提供data下标（0 ~ n-1）
        for (let i in seriesData[0].data) {
          for (let j=(seriesData.length-1);j>-1;j--) {
            if (seriesData[j].data[i].value != 0) { // 找到第一个不为0的值，为该项添加itemStyle
              seriesData[j].data[i]['itemStyle'] = { barBorderRadius: [4, 4, 0, 0] };
              break;  //退出该柱条的循环
            }
          }
        }
        let offsetX = window.innerWidth/150
        let fontSize = 19.2*window.innerWidth/1920
        let boxSize = 14*window.innerWidth/1920
        let paddingSize = 8*window.innerWidth/1920
        var option0 = {
          legend:{
            show:true,
            itemWidth:boxSize,
            itemHeight:boxSize,
            itemGap:fontSize,
            textStyle:{
              color:'#202124',
              fontSize:fontSize+'px',
              padding:[0,fontSize,0,paddingSize]
            }
          },
          tooltip: {
            backgroundColor:'#999999',
            borderColor:'rgba(0,0,0,0.0)',
            textStyle:{
              'color':'#FAFAFB',
              'lineHeight': 14,
              'fontSize':14
            },
            position: 'top',
            formatter: params => {
              let dataIndex = params.dataIndex
              let resStr = ''
              for (let i=0;i<seriesData.length;i++) {
                if(i==0){
                  resStr=resStr+"<div class='tooltipBox' style='margin-top:0px'><div class='tooltipLeft' style='background:"+that.colorbarArr[i]+"'></div>&nbsp;&nbsp;&nbsp;&nbsp;"+that.format_number(seriesData[i].data[dataIndex].value)+"&nbsp;&nbsp;&nbsp;&nbsp;"+seriesData[i].percentage[dataIndex]*100+"%</div>"
                }else{
                  resStr=resStr+"<div class='tooltipBox'><div class='tooltipLeft' style='background:"+that.colorbarArr[i]+"'></div>&nbsp;&nbsp;&nbsp;&nbsp;"+that.format_number(seriesData[i].data[dataIndex].value)+"&nbsp;&nbsp;&nbsp;&nbsp;"+seriesData[i].percentage[dataIndex]*100+"%</div>"
                }
              }
              //const { name, value } = params
              return resStr
            }
          },
         /* tooltip: {
            position: function (point, params, dom, rect, size) {
              console.log(dom.clientWidth)
              let dataIndex = params[0].dataIndex
              let basNum = window.innerWidth/1920
              //let marginNum = (dom.clientWidth-126-basNum*100)/2
              let marginNum = 0
              return {left: 10+(70+110*dataIndex)*basNum-marginNum, top: point[1]};
             // return {left: 1300, top: point[1]};
            },
            backgroundColor:'rgba(0,0,0,0.5)',
            borderWidth:'0',
            textStyle:{
              'color':'#FAFAFB',
              'lineHeight': 14,
              'fontSize':14
            },
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: params => {
              let dataIndex = params[0].dataIndex
              let resStr = ''
              for (let i=0;i<seriesData.length;i++) {
                if(i==0){
                  resStr=resStr+"<div class='tooltipBox' style='margin-top:0px'><div class='tooltipLeft' style='background:"+that.colorbarArr[i]+"'></div>&nbsp;&nbsp;&nbsp;&nbsp;"+seriesData[i].data[dataIndex].value+"&nbsp;&nbsp;&nbsp;&nbsp;"+seriesData[i].percentage[dataIndex]*100+"%</div>"
                }else{
                  resStr=resStr+"<div class='tooltipBox'><div class='tooltipLeft' style='background:"+that.colorbarArr[i]+"'></div>&nbsp;&nbsp;&nbsp;&nbsp;"+seriesData[i].data[dataIndex].value+"&nbsp;&nbsp;&nbsp;&nbsp;"+seriesData[i].percentage[dataIndex]*100+"%</div>"
                }
              }
              //const { name, value } = params
              return resStr
            }
          },*/
          /*tooltip: {
            position: function (point, params, dom, rect, size) {
                // 固定在顶部
                return [point[0], '10%'];
            },
            trigger: 'item',
            formatter: params => {
              const { name, value } = params
              return `${name} <br/>数量：${value}`
            }
          },*/
          grid: {
            top:'20%',
            left: '2%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              show: true,
              type: 'category',
              data: xAxisData,
              offset:offsetX,
               // 坐标 轴线
              axisLine: {
                show: true,
                lineStyle: {
                  type: 'solid',
                  color: '#F1F1F5',
                  width: 1
                },
              },
              axisTick:{
                show:false
              },
              axisLabel:{
                color:'#92929D',
                fontSize:14
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              splitLine:{
                lineStyle: {
                  type: 'solid',
                  color: '#F1F1F5',
                  width: 1
                }
              }, 
              axisLabel:{
                color:'#92929D',
                fontSize:14
              }
            }
          ],
          series: seriesData
        };
        var pieEl0=this.$refs.eCharts0;
        var pieChart0=echarts.init(pieEl0);
        pieChart0.setOption(option0);
      })
    },
    // 饼状图
    getKnowledgeTypeAmount(){
      let that = this
      analysis.knowledgeTypeAmount().then((res) => {
        let pieData=res.data
        that.pieTotalNum=pieData.total
        var option2 = {
          tooltip: {
            trigger: 'item',
            backgroundColor:'rgba(0,0,0,0.5)',
            borderWidth:'0',
            textStyle:{
              'color':'#FAFAFB'
            },
            formatter: params => {
              //console.log(params.data.name)
              //const { name, value } = params
              return params.data.name
            }
          },
          grid: {
            left: '3%',
            top: '20%',
            bottom: '3%',
            containLabel: true
          },
          series: [
            {
              roseType: 'radius',
              top:'10%',
              name: '知识类型分布',
              type: 'pie',
              radius: '60%',
              data: [
                { value: pieData.wiki, name: '维基知识\n'+pieData.wiki, itemStyle:{color:'#406cc4'}},
                { value: pieData.archive, name: '文档知识\n'+pieData.archive, itemStyle:{color:'#aebfee'},selected:true}
              ],
              selectedOffset:100,
              labelLayout(params) {
                  return {
                      x: params.labelLinePoints[2][0]<params.rect.x?params.labelLinePoints[2][0]-params.labelRect.width:params.labelLinePoints[2][0],
                      verticalAlign: 'middle',
                      align: 'left'
                  }
              },
              label:{
                fontSize:window.innerWidth/100,
                lineHeight:window.innerWidth/100
              },
              labelLine:{
                
                lineStyle:{
                  color:'#000'
                },
                length:window.innerWidth/100,
                length2:0
              },
              emphasis: {
                scaleSize:10,
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        };
        var pieEl2=that.$refs.eCharts2;
        var pieChart2=echarts.init(pieEl2);
        pieChart2.setOption(option2);
      })
    },
    //高频搜索词
    getSearchParticipleWordCloud(){
      let that = this
      analysis.searchParticipleWordCloud().then((res) => {
        let textData=[]
        res.data.forEach(item => {
          let tempData={
            name:item.participle,
            value:item.frequency
          }
          textData.push(tempData)
        })
        var option1={
          backgroundColor:'#fff',
          tooltip: {
            trigger: 'item',
            backgroundColor:'rgba(0,0,0,0.5)',
            borderWidth:'0',
            textStyle:{
              'color':'#FAFAFB'
            },
            formatter: params => {
              const { name, value } = params
              return `${name} <br/>数量：${value}`
            }
          },
          series: [{
            type: 'wordCloud',
        // shape这个属性虽然可配置，但是在词的数量不太多的时候，效果不明显，它会趋向于画一个椭圆
            shape: 'line',
            // 这个功能还没用过
            keepAspect: false,
            // 下面就是位置的配置
            left: '0',
            top: '0',
            width: '100%',
            height: '100%',
            // 词的大小，最小12px，最大60px，可以在这个范围调整词的大小
            sizeRange: [window.innerWidth/100, window.innerWidth/30],
            // 每个词旋转的角度范围和旋转的步进
            rotationRange: [0, 90],
            rotationStep: 90,
            // 词间距，数值越小，间距越小，这里间距太小的话，会出现大词把小词套住的情况，比如一个大的口字，中间会有比较大的空隙，这时候他会把一些很小的字放在口字里面，这样的话，鼠标就无法选中里面的那个小字，这里可以用函数根据词云的数量动态返回间距
            gridSize: 12,
        // 允许词太大的时候，超出画布的范围
            drawOutOfBound: false,
        // 布局的时候是否有动画
            layoutAnimation: true,
            // 这是全局的文字样式，相对应的还可以对每个词设置字体样式
            textStyle: {
                fontFamily: 'sans-serif',
                fontWeight: 'bold',
                // 颜色可以用一个函数来返回字符串，这里是随机色
                color: function () {
                    // Random color
                    return that.colorArr[Math.floor(Math.random()*6)]
                
                }
            },
            emphasis: {
              shadowBlur: 10,
              shadowColor: '#333'
            },
            // 数据必须是一个数组，数组是对象，对象必须有name和value属性
            data: textData
          }]
        }
        var pieEl1=that.$refs.eCharts1;
        var pieChart1=echarts.init(pieEl1);
        pieChart1.setOption(option1);
      })
    },
    //数字分隔符
    format_number(n) { 
      var b = parseInt(n).toString();
      var len = b.length;
      if (len <= 3) { return b; }
      var r = len % 3;
      return r > 0 ? b.slice(0, r) + "," + b.slice(r, len).match(/\d{3}/g).join(",") : b.slice(r, len).match(/\d{3}/g).join(",");
    },
    //搜索
    searchResult(data){
      this.searchName = decodeURI(data.keyword)
      this.getData()
    },
    //删除start
    del(id){
      this.delId = id
      this.delVisible = true
    },
    //删除确认
    confirmOk(){
      let postData = {ids:this.delId}
      album.del(postData).then((res) => {
        if(res.code == 200) {
          this.delVisible = false
          this.$message.success("删除成功!");
          this.getData()
        }
      })
    },
    closeDel(){
      this.delVisible = false
    },
    //删除end
    changeScope(num){
      this.scope = num
      this.pageNum = 1
      this.getData()
    },
    //查询数据
    getData(){
    
    },
    //新增专辑
    goCreatData(){
      this.$router.push({
        name: "albumDetail",
        query: {
          isAdd: 1,
          scope: this.scope
        }
      })
    },
    //修改页码
    pageChange(num){
      this.pageNum = num
      this.getData()
    },
    //查看2级分类
    showMore(num){
      if(this.classifyArr[num].children.length!=0){
        this.showLevel1Num = num
      }
    },
    //关闭所有分类
    clearAllLevel(){
      if(this.level2Action==-1){
        this.showLevel1Num = -1
      }
    },
    //选择分类1级
    selectLevel(num,pkId){
      this.level2Action = -1
      if(this.level1Action == num){
        this.level1Action = -1
        this.categoryId = ''
      }else{
        this.level1Action = num
        this.categoryId = pkId
      }
      this.getData()
    },
    //选择分类2级
    selectLevel2(num,pkId){
      this.level1Action = -1
      if(this.level2Action == num){
        this.level2Action = -1
      }else{
        this.level2Action = num
        this.categoryId = pkId
        this.getData()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.contentAlbunMain{
  overflow: scroll;
  padding: 0vw 10.93vw;
  width: 100%;
  display: flex;
  background: #FAFAFA;
  flex-direction: column;
  padding-bottom: 2vw;
}
.numBox{
  width: 24.73vw;
  height: 11.51vw;
  background: #fff;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top:3.6465vw;
}
.topBox{
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.middleBox{
  width: 100%;
  background: #fff;
  border-radius: 10px;
  height: 24.896vw;
  margin-top: 1.25vw;
}
.bottomBox{
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 1.4vw;
}
.bottomBoxLeft{
  height: 20vw;
  background: #fff;
  border-radius: 10px;
  width: 49.6vw;
}
.bottomBoxRight{
  height: 20vw;
  background: #fff;
  border-radius: 10px;
  width: 26vw;
}
.numBox img{
  width: 5.15625vw;
  height: 5.15625vw;
  margin-top: -2.135vw;
}
.numBox div:nth-child(2){
  font-size: 1.5625vw;
  width: 100%;
  word-break: break-all;
  color: #202124;
  margin-top: 1.2vw;
  text-align: center;
}
.numBox div:last-child{
  font-size: 0.9375vw;
  width: 100%;
  color: #92929D;
  margin-top: 1.2vw;
  text-align: center;
}
.topTitle{
  width: 15.625vw;
  margin-top: 1.5625vw;
  margin-left: 1.5625vw;
  position: absolute;
}
.topTitle div:nth-child(2){
  color: #202124;
  font-size: 1.5625vw;
  word-break: break-all;
}
.topTitle div:first-child{
  color: rgb(146, 146, 157);
  font-size: 0.9375vw;
}
.topTitle div:nth-child(3){
  color: #202124;
  width: 74vw;
  display: flex;
  justify-content: center;
  margin-top: -1.8vw;
}
.barBox{
  height: 80%;
  margin-top: 3.6vw;
}
.wordCloudBox{
  height: 73%;
  margin-top: 4.2vw;
  width: 46vw;
  margin-left: 30px;
}
.barNameBox{
  display: flex;
  flex-direction: row;
  align-items: end;
  width: auto!important;
  margin-right: 0.8333vw;
  font-size: 0.9375;
}
.barNameBox div:nth-child(1){
  width: 0.72vw;
  height: 0.72vw;
  margin-right: 0.52vw;
  margin-bottom: 0.3vw;
  border-radius: 2px;
}
.barNameBox div:nth-child(2){
  font-size: 1vw;
}

</style>
<style>
.tooltipLeft{
  width: 0.6vw;
  height: 0.6vw;
  border-radius: 2px;
  display: inline-block;
}
.tooltipBox{
  margin-left: 16px;
  margin-right: 16px;
  margin-top:8px;
}
.textBorder{
  width: 46vw!important;
  padding-bottom: 1vw;
  border-bottom: 1px solid rgb(244, 246, 249);
}
</style>