<template>
  <div class="app-container">
    <div class="app-content">
      <div class="title">
        联系客户统计
      </div>
      <el-form class="search-form" :inline="true" >
        <el-form-item >
          <el-select v-model="value" placeholder="请选择日期">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <treeselect :clearable="false"  v-model="deptId"  :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
        <el-form-item>
          <el-select filterable v-model="userIds" placeholder="请选择员工" clearable size="small">
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.qwId">
            </el-option>
          </el-select>
        </el-form-item>
<!--       <el-form-item label="筛选日期" prop="createTime">-->
<!--                <el-date-picker clearable size="small" style="width: 205.4px"-->
<!--                  v-model="dateRange"-->
<!--                  type="daterange"-->
<!--                  value-format="yyyy-MM-dd"-->
<!--                  start-placeholder="开始日期" end-placeholder="结束日期"-->
<!--                  >-->
<!--                </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search"   @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
      <div class="data-box">
        <div class="echart-box">
          <div id="echart-customer"></div>
        </div>
        <div class="table-box">
          <el-button class="export" size="small"  @click="handleExport"   v-hasPermi="['qw:userBehaviorData:export']">导出</el-button>
          <el-table
            :data="userBehaviorDataList"
            border
            :summary-method="getSummaries"
            show-summary
            max-height="500"
            style="width: 100%;">
            <el-table-column
              prop="nickName"
              label="成员名称">
            </el-table-column>
            <el-table-column
              prop="chatCnt"
              label="聊天总数">
            </el-table-column>
            <el-table-column
              prop="messageCnt"
              label="发消息数">
            </el-table-column>
            <el-table-column
              prop="replyPercentage"
              label="已回复聊天占比">
            </el-table-column>
            <el-table-column
              prop="avgReplyTime"
              label="平均首次回复时长">
            </el-table-column>
            <el-table-column
              prop="negativeFeedbackCnt"
              label="删除/拉黑成员的客户数">
            </el-table-column>
            <el-table-column
              prop="newApplyCnt"
              label="申请客户好友数">
            </el-table-column>
            <el-table-column
              prop="newContactCnt"
              label="新客户数">
            </el-table-column>
            <el-table-column
              prop="convertedDate"
              label="时间"
            >
            </el-table-column>

          </el-table>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import { listUserBehaviorData, getUserBehaviorData, delUserBehaviorData, addUserBehaviorData, updateUserBehaviorData, exportUserBehaviorData } from "@/api/qw/userBehaviorData";
import { getUserListByDeptId, getUserListByDeptIdToQwId } from '@/api/company/companyUser'
import echarts from 'echarts'
import resize from '../../dashboard/mixins/resize'
import { treeselect } from "@/api/company/companyDept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: 'Index',
  mixins: [resize],
  components: { Treeselect },
  watch: {
// 监听deptId
    'deptId': 'currDeptChange'
  },
  data() {
    return {
      deptOptions:[],
      deptId:undefined,
      userIds:undefined,
      userList:[],
      dateRange:[],
      chart: null,
      options: [{
        value: '2',
        label: '昨天'
      }, {
        value: '3',
        label: '本周'
      }, {
        value: '4',
        label: '上周'
      }, {
        value: '5',
        label: '本月'
      }
      , {
        value: '6',
        label: '上月'
      }
      , {
        value: '7',
        label: '本季度'
      }
      , {
        value: '8',
        label: '上季度'
      }
      , {
        value: '9',
        label: '本年'
      }
      , {
        value: '10',
        label: '上年'
      }],
      value: '5',
      userBehaviorDataList:[],
      dates:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userid: null,
        statTime: null,
        chatCnt: null,
        messageCnt: null,
        replyPercentage: null,
        avgReplyTime: null,
        negativeFeedbackCnt: null,
        newApplyCnt: null,
        newContactCnt: null,
        companyid: null,
        type:null,
        userIds:null,
        deptId:null,
        startTime:null,
        endTime:null,
      },
       avgReplyTimeAll:[],
       chatCntAll:[],
       messageCntAll :[],
       negativeFeedbackCntAll :[],
       newApplyCntAll :[],
       replyPercentageAll :[],
       newContactCntAll :[],
       time:[],
    }


  },
  created() {
    this.getTreeselect();
  },
  methods: {
    currDeptChange(val){
      this.deptId=val;
      this.getUserListByDeptId();
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      var that=this;
      treeselect().then((response) => {
        this.deptOptions = response.data;

        if(response.data!=null&&response.data.length>0){
          this.deptId=response.data[0].id;
          that.handleQuery()
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有企微联系客户统计数据数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportUserBehaviorData(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },

    //获取用户列表
    getUserListByDeptId() {
      this.userIds=undefined;
      var data={deptId:this.deptId};
      getUserListByDeptIdToQwId(data).then(response => {
        this.userList = response.data;

      });
    },

    handleQuery(){

      if(this.userIds!=undefined){
        this.queryParams.type=this.value;
        this.queryParams.userIds=this.userIds+"";
        this.queryParams.deptId=this.deptId;
      }
      else{
        this.queryParams.type=this.value;
        this.queryParams.deptId=this.deptId;
      }
      listUserBehaviorData(this.queryParams).then((response) => {
        this.avgReplyTimeAll = response.charts.map(item => item.avgReplyTimeAll);
        this.chatCntAll = response.charts.map(item => item.chatCntAll);
        this.messageCntAll = response.charts.map(item => item.messageCntAll);
        this.negativeFeedbackCntAll = response.charts.map(item => item.negativeFeedbackCntAll);
        this.newApplyCntAll = response.charts.map(item => item.newApplyCntAll);
        this.replyPercentageAll = response.charts.map(item => item.replyPercentageAll);
        this.newContactCntAll = response.charts.map(item => item.newContactCntAll);
        this.time = response.charts.map(item => item.time);
        this.userBehaviorDataList=response.list;
        setTimeout(() => {
          this.initEchart();
        }, 500);
      });
    },
    initEchart(){
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ['聊天总数', '发消息数','已回复聊天占比', '平均首次回复时长', '删除/拉黑成员的客户数', '申请客户好友数', '新客户数' ]
          // data: ['聊天总数', '发消息数', '删除/拉黑成员的客户数', '申请客户好友数', '新客户数' ]
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.time
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel:{
              formatter:'{value}'
            }
          }
        ],
        series: [
          {

            name: '聊天总数',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: this.chatCntAll
          },
          {
            name: '发消息数',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: this.messageCntAll
          },
          {

            name: '已回复聊天占比',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: this.replyPercentageAll
          },
          {
            name: '平均首次回复时长',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: this.avgReplyTimeAll
          },
          {

            name: '删除/拉黑成员的客户数',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: this.negativeFeedbackCntAll
          },
          {

            name: '申请客户好友数',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: this.newApplyCntAll
          },
          {

            name: '新客户数',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: this.newContactCntAll
          }

        ]
      };
      this.chart=echarts.init(document.getElementById("echart-customer"));
      this.chart.setOption(option,true);
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {

        if (index === 0) {
          sums[index] = '总计';
          return;
        }

        const values = data.map(item => Number(item[column.property]));
        //已回复聊天占比/平均首次回复时长算平均值
        if (index === 3 || index === 4) {
          const validValues = values.filter(value => !isNaN(value));
          if (validValues.length > 0) {
            const sum = validValues.reduce((prev, curr) => prev + curr, 0);
            const avg = sum / validValues.length;
            sums[index] = avg.toFixed(2) + ' ';
          } else {
            sums[index] = '';
          }
        } else {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += ' ';
          } else {
            sums[index] = '';
          }
        }
      });

      return sums;
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  border: 1px solid #e6e6e6;
  padding: 12px;

  .app-content{
    background-color: white;
    .title{
      padding: 20px 30px 0px 30px;
      font-size: 18px;
      font-weight: bold;
      color: black;

    }
    .search-form{
      margin: 20px 30px 0px 30px;
    }
    .data-box{
      padding: 30px;
      background-color:  rgb(255, 255, 255);
      height: 100%;

      .echart-box{
        margin: 0 auto;
        text-align: center;
      }
      .el-select{
        margin: 5px 10px;
      }
      .table-box{
        margin-top: 15px;
        .export{
          float: right;
          margin: 10px 0px;
        }
      }
    }
  }
}
#echart-customer{
  width:100%;
  height:320px
}
.vue-treeselect{
  width: 217px;
  height: 36px;
}

</style>
<style>
.vue-treeselect__control{
  display: block;
}
</style>
