<template>
  <div class="app-container overview">
    <el-row>
      <el-col :span="18">
        <div class="topions">
          <div class="head_title">客户概览</div>
          <div class="item">
            <div class="icons">
              <router-link to="/custom/customList" tag="a">
                <div class="name">总客户数</div>
                <div class="count">{{statistics.totalCount || '--'}}<span>{{statistics.totalCount ? '个':''}}</span></div>
                <img class="icon_img" src="@/assets/images/project/icon_1.png">
              </router-link>
            </div>
            <div class="icons">
              <router-link to="/custom/customList?type=1" tag="a">
                <div class="name">国企客户</div>
                <div class="count">{{statistics.nationCount || '--'}}<span>{{statistics.nationCount ? '个':''}}</span></div>
                <img class="icon_img" src="@/assets/images/project/icon_2.png">
              </router-link>
            </div>
            <div class="icons">
              <router-link to="/custom/customList?type=2" tag="a">
                <div class="name">央企客户</div>
                <div class="count">{{statistics.centreCount || '--'}}<span>{{statistics.centreCount ? '个':''}}</span></div>
                <img class="icon_img" src="@/assets/images/project/icon_3.png">
              </router-link>
            </div>
            <div class="icons">
              <router-link to="/custom/customList?type=3" tag="a">
                <div class="name">事业单位</div>
                <div class="count">{{statistics.undertakingCount || '--'}}<span>{{statistics.undertakingCount ? '个':''}}</span></div>
                <img class="icon_img" src="@/assets/images/project/icon_4.png">
              </router-link>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="search">
          <div class="head_title">快速查找</div>
          <el-input placeholder="输入企业名称查询" v-model="key">
            <i slot="prefix" class="el-icon-search"></i>
            <el-button slot="append" @click="handleSearch">搜索</el-button>
          </el-input>
          <div class="search_btn" @click="handleAdd"><i class="el-icon-plus"></i>添加客户</div>
        </div>
      </el-col>
    </el-row>
    <div class="content content_wap1">
      <div class="head_title">业主单位合作情况</div>
      <el-row>
        <el-col :span="14" v-if="hzqkTotal != 0">
          <div id="hzqk-echarts" style="height: 300px;"></div>
        </el-col>
        <el-col :span="10" v-if="hzqkTotal != 0">
          <div class="box-right">
            <el-table
              :data="hzqkList"
              border
              max-height="250"
              fit
              highlight-current-row
            >
              <el-table-column prop="companyName" label="业主单位">
                <template slot-scope="scope">
                  <router-link :to="scope.row.uipId?`/enterprise/${encodeStr(scope.row.companyId)}`:`/company/${encodeStr(scope.row.companyId)}`" tag="a" v-if="scope.row.companyId&&scope.row.companyName" v-html="scope.row.companyName"></router-link>
                  <div v-else v-html="scope.row.companyName || '--'"></div>
                </template>
              </el-table-column>
              <el-table-column prop="businessCount" label="合作次数" width="100"/>
              <el-table-column prop="totalAmount" label="合同总额（万元）" width="150"/>
            </el-table>
          </div>
        </el-col>
        <div class="empty" v-if="hzqkTotal === 0">
          <img class="img" src="@/assets/images/project/empty.png">
          <div class="p1">抱歉，没找到相关数据</div>
        </div>
      </el-row>
    </div>
    <div class="content content_wap2">
      <div class="head_title">客户资信评级</div>
      <el-row>
        <el-col :span="14">
          <div id="zxpj-echarts" style="height: 250px;"></div>
        </el-col>
        <el-col :span="10">
          <div class="box-right">
            <el-table
              :data="creditLevel"
              border
              max-height="250"
              fit
              highlight-current-row
            >
              <el-table-column prop="creditLevel" label="评级等级"/>
              <el-table-column prop="customerCount" label="客户数量"/>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="content_wap3">
      <div class="flex-box query-box">
        <div class="flex-box query-params">
          <span class="title">跟进动态</span>
        </div>
        <div class="flex-box time-label">
          <div class="labels">
            <div v-for="(item,index) in timeList" :class="{'on':datatype===index}"  @click="handleClick(item,index)">
              <template v-if="item === '自定义'">
                <div style="position: relative">
                  自定义
                  <el-date-picker
                    ref="picker"
                    :default-value="defaultValue"
                    style="position: absolute;opacity: 0;left: -12px;width: 60px;"
                    v-model="pickerValue"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    @change="changePicker">
                  </el-date-picker>
                </div>
              </template>
              <template v-else>{{item}}</template>
            </div>
          </div>
          <div class="picker-block" ref="picker-block"></div>
        </div>
      </div>
      <div class="trendslist">
        <div class="trends" v-for="item in recordlist">
          <div class="names">{{item.content}}</div>
          <div class="list-content">
            <p class="list-content-text">
              <span>关联企业：</span>
              <span>
                <router-link :to="{path:`/enterprise/${encodeStr(item.companyId)}`,query:{customerId:item.customerId,path:'business'}}" tag="a" class="a-link">{{item.companyName || '--'}}</router-link>
              </span>
            </p>
            <p class="list-content-text" v-if="item.nickName">
              <span>跟进人：</span>
              <span>{{item.nickName || '--'}}</span>
            </p>
            <p class="list-content-text" v-if="item.name">
              <span>拜访对象：</span>
              <span>{{item.name || '--'}}</span>
            </p>
            <p class="list-content-text" v-if="item.visitTime">
              <span>本次拜访时间：</span>
              <span>{{item.visitTime || '--'}}</span>
            </p>
            <p class="list-content-text" v-if="item.nextVisitTime">
              <span>下次拜访时间：</span>
              <span>{{item.nextVisitTime || '--'}}</span>
            </p>
          </div>
        </div>
        <div class="tables" style="width: 100%" v-if="recordlist.length>10">
          <div class="bottems">
            <el-pagination
              background
              :page-size="10"
              :current-page="1"
              @current-change="handleCurrentChange"
              layout="prev, pager, next"
              :total="recordlist.length">
            </el-pagination>
          </div>
        </div>
        <div class="empty" v-if="recordlist.length === 0">
          <img class="img" src="@/assets/images/project/empty.png">
          <div class="p1">抱歉，没找到相关数据</div>
          <div class="p2">建议调整筛选条件，重新搜索</div>
        </div>
      </div>
    </div>
    <AddCustom :data="data" v-if="data.open"></AddCustom>
  </div>
</template>

<script>
  import '@/assets/styles/project.scss'
  import * as echarts from 'echarts'
  import {encodeStr} from "@/assets/js/common"
  import { statistics, cooperationTop, creditLevel,getFollowList } from '@/api/custom/custom'
  import AddCustom from '../component/addCustom'
  export default {
  name: 'Overview',
    components: {
      AddCustom
    },
  data() {
    return {
      encodeStr,
      activeName:'first',
      key:'',
      statistics:{},
      hzqkList:[],
      creditLevel:[],
      chartDom: '',
      myChart: '',
      option: '',
      chartDom1: '',
      myChart1: '',
      option1: '',
      pageNum:1,
      pageSize:10,
      recordlist:[],
      timeList:['今日','近三天','近七天','自定义'],
      datatype:'',
      defaultValue:new Date(),
      pickerValue: [],
      params:{
        startTime:'',
        endTime:'',
      },
      data:{
        open:false
      },
      hzqkTotal:1
    }
  },
  created() {
    this.getData()
    this.getFollowList()
  },
  mounted(){
    this.$nextTick(()=>{
      this.chartDom = document.getElementById("hzqk-echarts")
      this.myChart = echarts.init(this.chartDom)
      this.chartDom1 = document.getElementById("zxpj-echarts")
      this.myChart1 = echarts.init(this.chartDom1)
    })
    window.addEventListener("resize", this.resizeEcharts);
  },
  beforeDestroy(){
    window.removeEventListener("resize", this. resizeEcharts);
  },
  activated() {
    this.resizeEcharts()
  },
  methods: {
    getData(){
      statistics().then(res=>{
        this.statistics=res.data;
      })
      cooperationTop().then(res=>{
        this.hzqkList=res.data;
        let list=[];
        for(let i=0; i<res.data.length; i++){
          if(res.data[i].totalAmount){
            list.push(res.data[i])
          }
        }
        if(list.length > 0){
          this.initChart(list)
        }else {
          this.hzqkTotal=list.length
        }
      })
      creditLevel().then(res=>{
        for(let i=0; i<res.data.length; i++){
          if(res.data[i].creditLevel){
            this.creditLevel.push(res.data[i])
          }
        }
        this.initChart1(this.creditLevel)
      })
    },
    getFollowList(){
      let param = {
        pageNum:this.pageNum,//页码
        pageSize:this.pageSize,
      }
      console.log(this.params)
      if(this.params.startTime){
        param.startTime=this.params.startTime
      }
      if(this.params.endTime){
        param.endTime=this.params.endTime
      }
      getFollowList(param).then(result=>{
        // this.isSkeleton = false
        this.recordlist = result.rows
        this.recordlist.forEach(item=>{
          item.createTime = this.gettime(item.createTime)
          item.visitTime = this.gettime(item.visitTime)
          item.nextVisitTime = this.gettime(item.nextVisitTime)
        })
      })
    },
    resizeEcharts (){
      const self = this
      setTimeout(function(){ //图表跟随页面大小变化宽度
        self.myChart.resize()
        self.myChart1.resize()
      }, 10)
    },
    initChart(list){
      let data=[]
      if(list.length > 10){
        for(var i=0;i<10;i++){
          data.push(list[i])
        }
      }else {
        data=list
      }
      //业主单位合作情况
      this.option ={
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        xAxis: {
          type: 'category',
          axisLabel: { //坐标轴刻度标签的相关设置
            margin: 15, //刻度标签与轴线之间的距离
            color:"#666666"
          },
          axisTick: false, //坐标轴刻度
          axisPointer: {
            type: 'shadow'
          },
          data: data.map(item => item.companyName),
        },
        yAxis: [
          {
            type: 'value',
            axisLabel: { //坐标轴刻度标签的相关设置
              color:"#666666"
            },
            name: '单位：次',
            nameLocation: 'end',
            nameTextStyle: {
              padding: [0, 10, 0, -60],    // 四个数字分别为上右下左与原位置距离
              color: '#666666',
            }
          },
          {
            type: 'value',
            axisLabel: { //坐标轴刻度标签的相关设置
              color:"#666666"
            },
            name: '单位：万元',
            nameLocation: 'end',
            nameTextStyle: {
              padding: [0, 0, 0, 100],    // 四个数字分别为上右下左与原位置距离
              color: '#666666',
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                color: ['#FFFFFF']
              }
            }
          }
        ],
        grid: {
          top:30,
          left:80,
          right:90,
          bottom:30,
        },
        series: [
          {
            name:'合作金额（万元）',
            smooth: false, //平滑
            type:"line",
            symbolSize: 6,
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + '万元'
              }
            },
            itemStyle: {
              normal:{
                color: '#67B3FD',
                lineStyle: {
                  width:3
                },
              }
            },
            data:data.map(item => item.totalAmount),
          },
          {
            name:'合作次数（次）',
            type: 'bar',
            barWidth: 20,
            tooltip: {
              valueFormatter: function (value) {
                return value + '次';
              }
            },
            itemStyle: {
              normal:{
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                  offset: 0,
                  color: '#56A5FF'
                }, {
                  offset: 1,
                  color: '#1B8EFF'
                }]),
                barBorderRadius:[20,20, 0, 0]
              }
            },
            data:data.map(item => item.businessCount),
          }
        ]
      }
      this.option && this.myChart.setOption(this.option)
    },
    initChart1(data){
      //客户资信评级
      this.option1 = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          top:30,
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: data.map(item => item.creditLevel),
            axisTick: {
              alignWithLabel: true,
              show: false
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            splitLine : { //网格线
              lineStyle: {
                type: 'dashed' //设置网格线类型 dotted：虚线 solid:实线
              },
            }
          }
        ],
        series: [
          {
            name: '',
            type: 'bar',
            barWidth: '18px',
            data: data.map(item => item.customerCount),
            tooltip: {
              valueFormatter: function (value) {
                return '客户数量 '+value
              }
            },
            itemStyle:{
              normal: {
                barBorderRadius: [9, 9, 0, 0],
                color: '#165DFF'
              }
            }
          }
        ],

        emphasis: {
          itemStyle: {
            // 高亮时点的颜色。
            color: 'rgb(90,146,247)'
          },
        }
      }
      this.option1 && this.myChart1.setOption(this.option1)
    },
    handleCurrentChange(val) {
      this.pageNum=1;
      this.getFollowList()
    },
    // 时间格式化
    formatDate(timeStr) {
      let date = new Date(Number(timeStr))
      let year = date.getFullYear()
      let month = String(date.getMonth() + 1).padStart(2, 0)
      let day = String(date.getDate()).padStart(2, 0)
      return `${year}-${month}-${day}`
    },
    handleClick(value,key){
      if(key === this.datatype && value != '自定义'){
        this.datatype='';
        this.pageNum=1
        this.params.startTime=''
        this.params.endTime=''
        this.getFollowList()
        return
      }
      this.datatype=key;
      if(value == '自定义') {
        this.$refs.picker && this.$refs.picker.length && this.$refs.picker[0].focus()
        this.$nextTick(() => {
          // this.$refs['picker-block'].appendChild(this.$refs.picker[0].popperElm)
        })
      }else {
        this.pickerValue = []
        let timeStr = []
        let startTime = ''
        let endTime = new Date()
        switch (value) {
          case '今日':
            startTime = new Date()
            timeStr = [this.formatDate(startTime), this.formatDate(endTime)]
            break;
          case '近三天':
            startTime = new Date(endTime.getTime() - 3600 * 1000 * 24 * 3)
            timeStr = [this.formatDate(startTime), this.formatDate(endTime)]
            break;
          case '近七天':
            startTime = new Date(endTime.getTime() - 3600 * 1000 * 24 * 3)
            timeStr = [this.formatDate(startTime), this.formatDate(endTime)]
            break;
          default:
            if(this.pickerValue && this.pickerValue.length) {
              timeStr = this.pickerValue
            }else {
              timeStr = []
            }
            break;
        }
        this.params.startTime=timeStr[0]
        this.params.endTime=timeStr[1]
        this.pageNum=1
        this.getFollowList()
      }
    },
    gettime(time){
      if(time == null || time == "")
        return null
      let times = new Date(time)
      let year = times.getFullYear()
      let month = times.getMonth()+1
      month = month<10?"0"+month:month
      let day = times.getDate()
      day = day<10?"0"+day:day
      return year+'-'+month+'-'+day
    },
    // 时间选择改变后的回调
    changePicker(value) {
      if(value && value.length) {
        this.pageNum=1
        this.params.startTime=this.pickerValue[0]
        this.params.endTime=this.pickerValue[1]
        this.getFollowList()
      }
    },
    handleSearch(){
      this.$router.push({
        path: '/custom/customList',
        query:{
          key:this.key
        }
      })
    },
    handleAdd(){
      this.data.open=true
    },
  }
}
</script>

<style lang="scss" scoped>
  .overview{
    ::v-deep .el-row{
      .el-col:nth-child(1){
        padding-left: 0 !important;
        padding-right: 0 !important;
      }
      .el-col:nth-child(2){
        padding-left: 16px !important;
        padding-right: 0 !important;
      }
    }
    .head_title{
      font-weight: 700;
      color: #232323;
      font-size: 16px;
      line-height: 24px;
      margin-bottom: 12px;
    }
    .topions{
      padding: 16px;
      background: #ffffff;
      height: 152px;
      margin-bottom: 22px;
      .item{
        display: flex;
        .icons{
          width: calc(24%);
          margin-right: 16px;
          height: 84px;
          background-size: 100% 100%;
          position: relative;
          padding: 16px;
          border-radius: 4px;
          cursor: pointer;
          &:last-child{
            margin-right: 0;
            background: linear-gradient(135deg, #F6F7FF 0%, #EDEDFF 100%);
          }
          &:nth-child(1){
            background: linear-gradient(135deg, #F2F9FE 0%, #E7F4FE 100%);
          }
          &:nth-child(2){
            background: linear-gradient(135deg, #F2FEF1 0%, #E7FEEE 100%);
          }
          &:nth-child(3){
            background: linear-gradient(135deg, #FEFAF2 0%, #FEF8E7 100%);
          }
          &:hover{
            .count{
              color: #0081FF;
              span{
                color: #0081FF;
              }
            }
          }
          .name{
            font-size: 14px;
            color: rgba(35,35,35,0.8);
            line-height: 20px;
          }
          .count{
            font-size: 22px;
            font-weight: 700;
            color: #3D3D3D;
            line-height: 32px;
            span{
              font-weight: 400;
              color: rgba(35,35,35,0.4);
              font-size: 12px;
              margin-left: 2px;
            }
          }
          .icon_img{
            width: 32px;
            height: 32px;
            position: absolute;
            right: 18px;
            bottom: 26px;
          }
        }
      }
    }
    .search{
      padding: 16px;
      background: #ffffff;
      height: 152px;

      ::v-deep .el-input{
        .el-input__inner{
          border-right: 0;
        }
        .el-icon-search{
          font-size: 16px;
          line-height: 36px;
          color:#0081FF;
          margin-left: 6px;
          margin-right: 4px;
        }
        .el-input-group__append{
          background: #F5F5F5;
          color: #0081FF;
        }
        .el-input__inner:focus{
          border-color: #3181fa;
        }
        .el-input__inner:focus ~.el-input-group__append{
          border: 1px solid #0081FF;
          color: #ffffff;
          background: #0081FF;
          /*.el-button{*/
            /*border: 1px solid #0081FF;*/
            /*span{*/
              /*color: #ffffff;*/
              /*background: #0081FF;*/
              /*border: 1px solid #0081FF;*/
            /*}*/
          /*}*/
        }


      }


      .search_btn{
        width: 100%;
        height: 36px;
        background: #0081FF;
        border-radius: 4px;
        line-height: 34px;
        text-align: center;
        color:#FFFFFF;
        font-size: 14px;
        margin-top: 12px;
        cursor: pointer;
        i{
          margin-right: 12px;
        }
      }
    }
    .content{
      background: #ffffff;
      padding: 22px 16px;
      margin-bottom: 12px;
    }
    .box-right{
      width: 90%;
      float: right;
      ::v-deep .el-table{
        .sort-caret.ascending{
          border-bottom-color: rgba(0,129,255,0.5);
        }
        .ascending .sort-caret.ascending{
          border-bottom-color: #0081FF;
        }
        .sort-caret.descending{
          border-top-color: rgba(0,129,255,0.5);
        }
        .descending .sort-caret.descending{
          border-top-color: #0081FF;
        }

        .el-table__header-wrapper{
          background: #F0F3FA;
          th{
            background: #F0F3FA;
            /*text-align: left;*/
          }
        }
        .el-table__footer-wrapper{
          background: #F0F3FA;
        }
        th {
          font-size: 13px !important;
          font-weight: 400 !important;
        }
        .cell {
          padding-right: 12px !important;
          padding-left: 12px !important;
          line-height: 18px;
        }
        .el-table__fixed-header-wrapper{
          th{
            background: #F0F3FA;
          }
        }
        td.el-table__cell{
          border-bottom: 0;
        }
        tr{
          &.current-row>td{
            background-color: initial;
          }
          &:nth-child(2n) {
            background: #F8FBFF;
          }
        }
        .el-table__cell{
          height: 40px;
          padding: 0;
          line-height: 40px;
        }
        .el-table__body tr:hover > td.el-table__cell{
          background: #DCEBFF;
        }
        ::-webkit-scrollbar-track-piece {
          //滚动条凹槽的颜色，还可以设置边框属性
          background-color: #F3F4F5;
          height: 16px;
          padding: 0 4px;
        }
        //滚动条的宽度
        ::-webkit-scrollbar {
          width: 8px;
          height: 8px;
          background-color: #F3F4F5;
          border-radius: 6px;
        }
        //滚动条的滑块
        ::-webkit-scrollbar-thumb {
          border-radius: 8px;
          height: 8px;
          margin: 0 4px;
          background: rgba(98,110,126,0.2);
          border: 4px solid rgba(98,110,126,0.2);;
          &:hover{
            background: #566380;
          }
        }
        .has-gutter{
          tr{
            th:nth-last-child(2){
              border-right:0;
            }
            td:nth-last-child(2){
              border-right:0;
            }
          }
        }
        .el-table__cell.gutter{
          background: #F0F3FA;
        }
        .el-table__row{
          td:last-child{
            .cell{
              padding-right: 12px !important;
            }
          }
        }
      }
    }

    .content_wap1{
      .empty{
        margin: 0 auto;
        height: 300px;
        text-align: center;
        .img{
          width: 108px;
          height: 108px;
          margin-bottom: 24px;
          margin-top: 50px;
        }
        .p1{
          color: #333333;
          font-size: 16px;
        }
        .p2{
          color: #999999;
          font-size: 14px;
          margin-top: 8px;
        }
      }
    }
    .content_wap3{
      background: #ffffff;
      .query-box{
        padding:16px;
      }
      .title{
        font-weight: 700;
        color: #232323;
        font-size: 16px;
        line-height: 24px;
      }
      .time-label{
        .labels{
          width: 240px;
          height: 30px;
          line-height: 30px;
          border-radius: 4px;
          >div{
            height: 100%;
            padding: 0 12px;
            text-align: center;
            float: left;
            opacity: 1;
            border: 1px solid #EFEFEF;
            margin-left: -1px;
            font-weight: 400;
            font-size: 12px;
            color: rgba(35, 35, 35, 0.80);
            cursor: pointer;
            &.on{
              background: #0081FF;
              color: #FFFFFF;
              border-color: #0081FF;
            }
            &:first-child{
              border-radius: 4px 0px 0px 4px;
            }
            &:last-child{
              border-radius: 0px 4px 4px 0px;
            }
          }
        }
      }


      ::v-deep .picker-block {
        position: relative;

        &::after {
          content:"";
          display:block;
          visibility:hidden;
          clear:both;
        }

        .el-picker-panel.el-date-range-picker.el-popper {
          left: -650px !important;
        }

        .popper__arrow {
          left: 30px !important;
        }
      }
    }
  }
  .tables{
    width: calc(100% - 428px);
  }
  .trendslist{
    border-top: 1px solid #EFEFEF;
    .trends{
      position: relative;
      padding: 16px;
      border-bottom: 1px solid #EFEFEF;
      &:hover{
        background: #F6F9FC;
      }
      .names{
        width: calc(100% - 92px);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        height: 23px;
        font-size: 16px;
        font-family: Source Han Sans CN-Bold, Source Han Sans CN;
        font-weight: 700;
        color: #3D3D3D;
        line-height: 23px;
        margin-bottom: 12px;
      }
      .list-content {
        display: flex;
        justify-content: start;
        align-items: center;
        .list-content-text {
          display: flex;
          justify-content: start;
          align-items: center;
          margin-right: 32px;
          font-size: 14px;

          span:first-child {
            font-weight: 400;
            color: rgba(35, 35, 35, 0.4);
            line-height: 15px
          }
          span:last-child {
            font-weight: 400;
            color: rgba(35, 35, 35, 0.8);
            line-height: 15px
          }
          .blue {
            color: #0081FF !important;
            cursor: pointer;

          }

        }
      }
    }
    .empty{
      margin: 0 auto;
      height: 400px;
      text-align: center;
      /*border-top: 1px solid #EFEFEF;*/
      padding-bottom: 50px;
      .img{
        width: 108px;
        height: 108px;
        margin-bottom: 24px;
        margin-top: 50px;
      }
      .p1{
        color: #333333;
        font-size: 16px;
      }
      .p2{
        color: #999999;
        font-size: 14px;
        margin-top: 8px;
      }
    }
  }
</style>
