<template>
  <div class="aiCall">
    <div class="radioButton">
      <el-radio-group class="customize" v-model="dimension" @change="radioChange">
        <el-radio-button label="门店维度"></el-radio-button>
        <el-radio-button label="分组维度"></el-radio-button>
      </el-radio-group>
      <div class="tips ml10">
        数据每天更新一次，按营销触发时客户所在服务门店进行统计
      </div>
    </div>
    <div class="searchWarp">
      <div class="pb20 clearfix" v-show="dimension == '门店维度'">
        <el-input placeholder="请输入门店名称/code" v-model="form.search" class="w260" @change="handleSearch" clearable> </el-input>
        <vue-gic-select-tree class="inline" :options="options" v-if="dimension == '门店维度'" @change="onChange" ref="selectTree"></vue-gic-select-tree>
        <el-button icon="iconfont fz14 icon-cp-xiazai" v-if="$getButtonLimit($buttonCode.marketingAiExport)" :limit-code="$buttonCode.marketingAiExport" type="primary" class="fr" @click="handleExport" size="small" :disabled="!total"> 查询结果导出</el-button>
      </div>
      <el-form inline="true" class="table-page-search-wrapper" size="small" v-show="dimension == '分组维度'">
        <el-form-item>
          <el-select v-model="selectVal" class="w100" @change="groupSelectChange">
            <el-option label="分组层级" :value="1"></el-option>
            <el-option label="分组名称" :value="2"></el-option>
          </el-select>
          <el-select v-model="form.storeGroupLevel" @change="handleSearch" v-if="selectVal == 1" class="w260">
            <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
          <vue-gic-select-tree :options="options" v-if="selectVal == 2" @change="onChange"></vue-gic-select-tree>
        </el-form-item>
        <el-button icon="iconfont icon-cp-xiazai" class="fr" type="primary" @click="handleExport" :disabled="!total"> 查询结果导出</el-button>
      </el-form>
    </div>
    <div class="cardContent">
      <el-row :gutter="20" v-loading="cardLoading">
        <el-col :span="6" v-for="(el, index) in targetList" :key="index">
          <target-group :data-list="el"></target-group>
        </el-col>
      </el-row>
    </div>
    <el-table :data="tableData" style="width:100%" v-loading="loading" @sort-change="handleSortChange" :key="dimension">
      <el-table-column align="center" prop="date" label="排名" width="80px" fixed="left">
        <template slot-scope="scope">
          <div style="line-height:1">
            <!-- 排名变化 上升 +  下降 - 不变0 -->
            <div class="rank-icon" v-show="scope.row.numSort">
              <span :class="`${scope.row.numSort < 4 ? 'rank1' : 'rank2'}`">{{ scope.row.numSort || '-' }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-for="v in tableHeader" :show-overflow-tooltip="v.tooltip" :width="v.width" :min-width="v.minWidth" :align="v.align" :key="v.prop" :prop="v.prop" :label="v.label" :formatter="v.formatter" :sortable="v.sortable" :fixed="v.fixed">
        <template slot-scope="scope">
          <span v-if="v.formatter" v-html="v.formatter(scope.row)"></span>
          <span v-else>{{ scope.row[v.prop] }}</span>
        </template>
      </el-table-column>
    </el-table>
    <dm-pagination v-show="tableData.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="getListData" :current-page.sync="form.pageNum" :page-sizes="[20, 40, 60, 80]" :page-size.sync="form.pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
    <vue-gic-export-excel :dialogVisible.sync="dialogVisible" :dataArr="tableData" :type="2" :excelUrl="excelUrl" :params="exportParams" projectName="marketing"></vue-gic-export-excel>
  </div>
</template>

<script>
import { aiOutboundStoreGroupSplit, getActivityDetail, aiStoreOutboundRank, aiStoreOutboundRankNoBelong, aiStoreOutboundStatistics, exportAiStoreOutbound, aiStoreGroupOutboundRank, aiStoreGroupOutboundStatistics, exportAiStoreGroupOutbound } from '@/service/api/aiApi.js';
import TargetGroup from '@/components/target-group.vue';
import { numFormat } from '@/utils/index.js';

let tableHead = [
  {
    label: '上级分组',
    prop: 'storeGroupName',
    minWidth: '180',
    formatter: function(row) {
      return `<span class="ellipsis-l2">${row.storeGroupName ? row.storeGroupName : '- -'}</span>`;
    }
  },
  {
    label: '营销人数',
    prop: 'marketingNumber',
    width: '100',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.marketingNumber) ? row.marketingNumber.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '已外呼数',
    prop: 'outboundNumber',
    width: '100',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.outboundNumber) ? row.outboundNumber.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '总接通数',
    prop: 'totalConnectionNumber',
    width: '100',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.totalConnectionNumber) ? row.totalConnectionNumber.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '接通率',
    prop: 'telephoneConnectionRate',
    width: '120',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.telephoneConnectionRate) ? row.telephoneConnectionRate + '%' : '- -'}</span>`;
    }
  },
  {
    label: 'A/B类客户意向数',
    prop: 'customerIntentionsNumber',
    width: '160',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.customerIntentionsNumber) ? row.customerIntentionsNumber.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '接通意向率',
    prop: 'connectionIntentionRate',
    width: '120',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.connectionIntentionRate) ? row.connectionIntentionRate + '%' : '- -'}</span>`;
    }
  }
];
let smsFlagHead = [
  {
    label: '短信发送总数',
    prop: 'sentMessagesNumber',
    width: '160',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.sentMessagesNumber) ? row.sentMessagesNumber.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '发送成功数',
    prop: 'sentSuccessfullyNumber',
    width: '120',
    sortable: 'custom',
    formatter: function(row) {
      return `<span>${!isNaN(row.sentSuccessfullyNumber) ? row.sentSuccessfullyNumber.toLocaleString() : '- -'}</span>`;
    },
    fixed: 'right'
  }
];
export default {
  data() {
    return {
      numFormat,
      form: {
        search: '',
        storeGroupId: '',
        storeGroupLevel: '',
        orderBy: '',
        activityId: this.$route.params.id,
        pageNum: 1,
        pageSize: 20
      },
      dimension: '门店维度',
      selectVal: 1,
      tableData: [],
      selectOptions: [
        {
          label: '第一层级',
          value: 1
        },
        {
          label: '第二层级',
          value: 2
        },
        {
          label: '第三层级',
          value: 3
        },
        {
          label: '第四层级',
          value: 4
        },
        {
          label: '第五层级',
          value: 5
        }
      ],
      options: {
        selectOptions: {
          allCheckText: '全部选中111',
          width: 260,
          placeholder: '请选择',
          clearable: true,
          data: []
        },
        treeOptions: {
          data: [],
          isDefalutExpandAll: true,
          nodeClickRule: {
            leafOnly: true,
            includeHalfChecked: false
          },
          props: {
            label: 'storeGroupName',
            value: 'storeGroupId',
            children: 'children'
          },
          filter(value, data, node) {
            return node.label.indexOf(value) > -1;
          }
        },
        searchAble: true
      },
      fixedTableData: [],
      total: 0,
      loading: false,
      cardLoading: false,
      dialogVisible: false,
      excelUrl: '',
      originTargetList: [
        [
          {
            label: '营销人数',
            tips: '根据每天外呼人数累加',
            value: '',
            key: 'marketingNumber',
            type: 'number'
          },
          {
            label: '已外呼数',
            value: '',
            key: 'outboundNumber',
            type: 'number'
          }
        ],
        [
          {
            label: '总接通数',
            value: '',
            key: 'totalConnectionNumber',
            type: 'number'
          },
          {
            label: '电话接通率',
            tips: '电话接通率：表示任务中接通号码的占比<br/>计算公式为：接通的电话通数/已经外呼的电话通数',
            value: '',
            key: 'telephoneConnectionRate',
            type: 'rate'
          }
        ],
        [
          {
            label: 'A/B类客户意向数',
            value: '',
            key: 'customerIntentionsNumber',
            type: 'number'
          },
          {
            label: '接通意向率',
            tips: '接通意向率：表示所有已接通的通话中意向客户占比，其中A类和B类客户为意向客户<br/>计算公式为：A/B类客户意向数/已接通的电话数',
            value: '',
            key: 'connectionIntentionRate',
            type: 'rate'
          }
        ],
        [
          {
            label: '短信发送总数',
            value: '',
            key: 'sentMessagesNumber',
            type: 'number'
          },
          {
            label: '发送成功数',
            value: '',
            key: 'sentSuccessfullyNumber',
            type: 'number'
          }
        ]
      ],
      activityData: {},
      targetData: {},
      tableHeader: []
    };
  },
  components: {
    TargetGroup
  },
  mounted() {
    this.aiStoreOutboundStatistics();

    this.getActivityDetail();
  },
  computed: {
    targetList() {
      return this.originTargetList
        .map(el => {
          return el.filter(item => {
            const value = this.targetData[item.key];
            switch (item.type) {
              case 'number':
                item.value = numFormat(value);
                break;
              case 'time':
                item.value = '--';
                if (typeof value == 'number') {
                  const h = Math.floor(value / 3600);
                  const m = Math.floor((value % 3600) / 60);
                  const s = value % 60;
                  item.value = `${h}:${m}:${s}`;
                }
                break;
              case 'amount':
                item.value = numFormat(value);
                break;
              case 'rate':
                item.value = !isNaN(value) ? value + '%' : '- -';
                break;
            }
            // 活动不发送挂机短信时，数据指标不展示短信发送总数和发送成功数的字段
            // 活动未开启活动分析时，数据指标展示活动费用
            return !((this.activityData.smsFlag == 0 && item.key == 'sentMessagesNumber') || (this.activityData.smsFlag == 0 && item.key == 'sentSuccessfullyNumber'));
          });
        })
        .filter(el => el.length > 0);
    },
    exportParams() {
      const { search, storeGroupId, storeGroupLevel, orderBy } = this.form;
      let params = {};
      if (this.dimension == '分组维度') {
        if (this.selectVal == 1) {
          params = { ...this.activityData, storeGroupLevel, orderBy };
        } else {
          params = { ...this.activityData, storeGroupId, orderBy };
        }
      } else {
        params = { ...this.activityData, search, storeGroupId, orderBy };
      }
      return { ...this.activityData, ...params };
    }
  },
  methods: {
    async aiStoreOutboundRank() {
      // 门店维度列表
      const head = {
        label: '门店名称',
        prop: 'storeName',
        width: '250',
        tooltip: true,
        fixed: 'left',
        formatter: function(row) {
          return `<span>${row.storeName ? row.storeName : '- -'}</span>`;
        }
      };
      this.tableHeader = [...tableHead];
      this.tableHeader.unshift(head);
      if (this.activityData.smsFlag) {
        this.tableHeader = this.tableHeader.concat(smsFlagHead);
      }
      this.loading = true;
      const { activityId, search, storeGroupId, pageNum, pageSize, orderBy } = this.form;
      try {
        const { result } = await aiStoreOutboundRank({ activityId, search, storeGroupId, orderBy }, `&pageNum=${pageNum}&pageSize=${pageSize}`);
        if (!result) return;
        this.tableData = result.result || [];
        this.total = result.totalCount;
        if (!storeGroupId && !search) {
          this.aiStoreOutboundRankNoBelong();
        }
      } finally {
        this.loading = false;
      }
    },
    async aiStoreOutboundRankNoBelong() {
      // 门店维度列表-无归属客户
      try {
        const { result } = await aiStoreOutboundRankNoBelong({ activityId: this.$route.params.id });
        if (!result) return;
        result.numSort = 0;
        this.tableData.unshift(result);
        // this.fixedTableData = [result];
      } finally {
        this.loading = false;
      }
    },
    async aiStoreOutboundStatistics() {
      // 门店维度列表-统计数据
      try {
        this.cardLoading = true;
        const { activityId, search, storeGroupId } = this.form;
        const { result } = await aiStoreOutboundStatistics({ activityId, search, storeGroupId });
        if (!result) return;
        this.targetData = result;
      } finally {
        this.cardLoading = false;
      }
    },
    async aiStoreGroupOutboundRank() {
      // 分组维度列表
      const head = {
        label: '分组名称',
        prop: 'name',
        width: '150',
        tooltip: true,
        fixed: 'left',
        formatter: function(row) {
          return `<span>${row.name ? row.name : '- -'}</span>`;
        }
      };
      this.tableHeader = [...tableHead];
      this.tableHeader.unshift(head);
      if (this.activityData.smsFlag) {
        this.tableHeader = this.tableHeader.concat(smsFlagHead);
      }
      this.loading = true;
      const { activityId, storeGroupLevel, storeGroupId, pageNum, pageSize, orderBy } = this.form;
      let params = {};
      if (this.selectVal == 1) {
        params = { activityId, storeGroupLevel, orderBy };
      } else {
        params = { activityId, storeGroupId, orderBy };
      }
      try {
        const { result } = await aiStoreGroupOutboundRank(params, `&pageNum=${pageNum}&pageSize=${pageSize}`);
        if (!result) return;
        this.tableData = result.result || [];
        this.total = result.totalCount;
      } finally {
        this.loading = false;
      }
    },
    async aiStoreGroupOutboundStatistics() {
      // 分组维度列表-统计数据
      try {
        this.cardLoading = true;
        const { activityId, storeGroupLevel, storeGroupId } = this.form;
        let params = {};
        if (this.selectVal == 1) {
          params = { activityId, storeGroupLevel };
        } else {
          params = { activityId, storeGroupId };
        }
        const { result } = await aiStoreGroupOutboundStatistics(params);
        if (!result) return;
        this.targetData = result;
      } finally {
        this.cardLoading = false;
      }
    },
    async aiOutboundStoreGroupSplit() {
      const { activityId, planId } = this.activityData;
      let res = await aiOutboundStoreGroupSplit({ activityId, planId });
      this.options.treeOptions.data = res.result || [];
    },
    async getActivityDetail() {
      try {
        const { result } = await getActivityDetail({ activityId: this.$route.params.id });
        if (!result) return;
        const { startDate, endDate, activityName, activityId } = result;
        const smsFlag = result.activityPlanList[0].activityEventList[0].smsFlag;
        const planId = result.activityPlanList[0].planId;
        this.activityData = { startTime: startDate, endTime: endDate, smsFlag, activityName, activityId, planId };
        this.aiStoreOutboundRank();
        this.aiOutboundStoreGroupSplit();
      } catch (err) {}
    },
    radioChange(data) {
      this.form = {
        search: '',
        storeGroupId: '',
        storeGroupLevel: '',
        orderBy: '',
        activityId: this.$route.params.id,
        pageNum: 1,
        pageSize: 20
      };
      if (data == '分组维度') {
        this.form.storeGroupLevel = 1;
        this.selectVal = 1;
      }
      try {
        this.$refs.selectTree.onClearSelect();
      } catch (err) {
        console.log(err);
      }
    },

    handleSizeChange(val) {
      this.form.pageSize = val;
      this.form.pageNum = 1;
      this.getListData();
    },
    groupSelectChange(data) {
      // 分组维度列表+统计数据
      this.aiStoreGroupOutboundRank();
      this.aiStoreGroupOutboundStatistics();
    },
    handleSearch() {
      this.form.pageNum = 1;
      this.getStaticListData();
    },
    getListData() {
      if (this.dimension == '门店维度') {
        this.aiStoreOutboundRank();
      } else if (this.dimension == '分组维度') {
        this.aiStoreGroupOutboundRank();
      }
    },
    getStaticListData() {
      if (this.dimension == '门店维度') {
        // 门店维度列表+统计数据
        this.aiStoreOutboundRank();
        this.aiStoreOutboundStatistics();
      } else if (this.dimension == '分组维度') {
        // 分组维度列表+统计数据
        this.aiStoreGroupOutboundRank();
        this.aiStoreGroupOutboundStatistics();
      }
    },
    onChange(data) {
      if (!data) {
        this.aiOutboundStoreGroupSplit();
      }
      this.form.storeGroupId = data ? data.storeGroupId : undefined;
      this.getStaticListData();
    },
    handleExport() {
      this.dialogVisible = true;
      if (this.dimension == '门店维度') {
        this.excelUrl = exportAiStoreOutbound;
      } else if (this.dimension == '分组维度') {
        this.excelUrl = exportAiStoreGroupOutbound;
      }
    },
    handleSortChange(data) {
      const { prop, order } = data;
      console.log(order);
      if (order == 'descending') {
        this.form.orderBy = prop + ' desc';
      } else if (order === 'ascending') {
        this.form.orderBy = prop + ' asc';
      } else {
        this.form.orderBy = undefined;
      }
      this.form.pageNum = 1;
      this.getListData();
    }
  }
};
</script>

<style lang="scss" scoped>
.aiCall {
  padding: 5px 20px;
  .radioButton {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  .cardContent {
    margin: -14px 0 20px 0;
  }
  .table-page-search-wrapper {
    /deep/ .el-form-item__content {
      display: flex;
    }
  }
}
</style>
