<template>
  <div class="clue" v-loading="loading">
    <div class="dm-wrap draw_wrap">
      <h2 class="title">{{ type == 1 ? '导购线索概况' : '后台线索概况' }}</h2>
      <touch-charts :style="{ marginBottom: '3px' }" :type="$route.query.type" :createTime="$route.query.createTime" />
      <market-list :isCluePage="true" :isRepeat="true" :isReference="false" :data="marketListData" />
    </div>
    <div class="dm-wrap area">
      <div class="areatitle">
        <span class="txt">区域详情</span>
        <!-- <vue-gic-store-new :options="options" :isAdd="isAdd" :uuid.sync="uuid" ref="storeNew" @store-change="storeChange"></vue-gic-store-new> 门店选择器-->
      </div>
      <div class="tab1" v-if="type == 1">
        <span v-for="item in listTabs" :key="item.value" :class="{ active: item.value == listTabsIndex }" @click="changeListTab(item.value)">{{ item.name }}</span>
        <div class="line" :class="{ lineActive: listTabsIndex == 0 }"></div>
      </div>
      <!--转为树结构下钻-->
      <div class="area_content">
        <div class="tree">
          <el-tree ref="treeList" :expand-on-click-node="false" highlight-current :props="defaultProps" @node-click="refreshLazyTree" :load="loadNode" lazy node-key="storeGroupId" :default-expanded-keys="allStoreId">
            <span class="node-label" v-if="data.storeGroupName.length <= 10" slot-scope="{ data }">{{ data.storeGroupName }}</span>
            <el-tooltip effect="dark" :content="data.storeGroupName" placement="top" slot-scope="{ data }" v-else>
              <span class="custom-tree-node">{{ data.storeGroupName }}</span>
            </el-tooltip>
          </el-tree>
        </div>
        <div class="map_area">
          <div class="top">
            <div class="tab2">
              <template v-if="type == 1">
                <span class="tab2-item" v-for="item in listTabsIndex == 1 ? touchTabs : taskTabs" :key="item.id" :class="{ active2: listTabsIndex == 1 ? item.id == tabsIndex : item.id == taskTabIndex }" @click="changeTabs(item.id)">{{ item.name }}</span>
                <span class="tab2-tip" v-if="listTabsIndex == 1">* 只展示有数据的触达方式（默认按触达转化率倒序排序）</span>
                <span class="tab2-tip" v-else>* 只展示有数据的任务</span>
              </template>
              <span class="tab2-tip" v-else>默认按转化人数倒序排序</span>
            </div>
            <el-button type="primary" class="btn" @click="cdkeyExport"><i class="iconfont icon-icon_yunxiazai" style="marginRight:6px;fontSize:14px"></i>导出</el-button>
          </div>
          <el-table ref="table" tooltipEffect="light" :data="tableList" element-loading-text="拼命加载中" @sort-change="sortChange" :style="{ padding: '0 20px 0 22px' }">
            <el-table-column v-for="(v, i) in tableHeader" :key="i" :prop="v.prop" :min-width="v.minWidth" :label="v.label" :formatter="v.formatter" :sortable="v.sortable">
              <template slot-scope="scope">
                <span v-if="v.formatter" v-html="v.formatter(scope.row)" @click="onMapTree(scope.row, $event)"></span>
                <span v-else>{{ scope.row[v.prop] }}</span>
              </template>
            </el-table-column>
          </el-table>
          <dm-pagination v-show="tableList.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
        </div>
      </div>
    </div>
    <!--数据导出-->
    <vue-gic-export-excel :dialogVisible.sync="exportDialog" :dataArr="tableList" :type="1" :excelUrl="excelUrl" :params="params" projectName="marketing"></vue-gic-export-excel>
  </div>
</template>

<script>
import { ecmGuideCluesTable, ecmHeadCluesTaskTab, ecmHeadGuideCluesTable, ecmGuideCluesTaskTable, ecmGuideCluesTouchEffectTotalTab, ecmGuideCluesTouchEffectTab, getGroupTree } from '@/service/api/ecmApi.js';
import { otherTableExoport, allConvTableExport, taskTableExport, headClueTableExport, getTabList, ecmGuideCluesTouchEffectTotalTabHead, ecmGuideCluesTouchEffectTabHead, ecmGuideCluesTaskTableHead, ecmHeadCluesTaskTabHead } from '@/service/api/ecmApi';
import marketList from '@/views/ecm/touch-components/market-list.vue';
import touchCharts from '@/views/ecm/touch-components/touch-charts.vue';
import formatterNum from '@/mixins/validateNum';
export default {
  name: 'touch-clue',
  components: {
    marketList,
    touchCharts
  },
  mixins: [formatterNum],
  data() {
    return {
      tableHeader: [],
      tableList: [],
      touchTabs: [],
      taskTabs: [],
      listTabs: [
        {
          name: '触达效果',
          value: 1
        },
        {
          name: '任务完成情况',
          value: 0
        }
      ],
      defaultProps: {
        label: 'storeGroupName',
        isLeaf: 'isLeaf'
      },
      tabsIndex: 0,
      taskTabIndex: 0,
      listTabsIndex: 1,
      type: 1, // 1导购 2后台
      marketListData: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableExtra: [], // 表格的额外数据,合计和计划整体
      touchOrderBy: '',
      taskOrderBy: '',
      // uuid: '', // 新增传空，编辑必传,
      // options: [0, 4, 5], // 0 全部 1 门店类型 2门店标签 3 门店区域 4 门店分组 5 部分门店
      // isAdd: true,
      allStoreId: [],
      storeGroupId: '',
      level: 0,
      loading: false,
      dialogVisible: false,
      // 导出数据
      projectName: 'marketing', // 当前项目名
      exportDialog: false,
      excelUrl: '', // 下载数据的地址
      params: {} // 传递的参数
    };
  },
  mounted() {
    let planName = this.$route.query.planName;
    let name;
    let planId = this.$route.query.id;
    let createTime = this.$route.query.createTime;
    this.type = this.$route.query.type;
    this.effectType = this.$route.query.effectType;
    this.getMarketList();
    this.getTabData();
    if (this.type == 2) {
      name = '后台线索';
      this.touchOrderBy = 'convMbrNum desc';
    } else {
      name = '导购线索';
      this.touchOrderBy = 'reachConvMbrRate desc';
    }
    this.$store.commit('mutations_breadcrumb', [{ name: '营销管理', path: '' }, { name: '智能营销', path: '/ecm' }, { name: `${planName} - 触达效果`, path: `/ecm/touch/${planId}?name=${planName}&&createTime=${createTime}&&effectType=${effectType}` }, { name }]); // eslint-disable-line
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getTableList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableList();
    },
    changeTabs(index) {
      if (this.type == 1) {
        if (this.listTabsIndex == 1) {
          if (this.tabsIndex == index) return;
          this.tabsIndex = index;
        } else {
          if (this.taskTabIndex == index) return;
          this.taskTabIndex = index;
        }
      }
      this.currentPage = 1;
      this.getTableFirstData();
    },
    changeListTab(index) {
      if (index == this.listTabsIndex) return;
      this.listTabsIndex = index;
      this.currentPage = 1;
      this.$refs.table.clearSort();
      this.getTabData();
      this.getTableFirstData();
    },
    getMarketList() {
      let meth;
      if (this.type == 1) meth = ecmGuideCluesTable;
      else if (this.type == 2) meth = ecmHeadGuideCluesTable;
      meth({ ecmPlanId: this.$route.query.id }).then(res => {
        let data = res.result || {};
        if (this.type == 1) {
          data.taskRate = (data.cplTaskTotalCnt / data.taskCnt) * 100;
        }
        data.touchRate = data.touchMbrNum * 1 && data.planMbrNum * 1 ? ((data.touchMbrNum / data.planMbrNum) * 100).toFixed(2) : 0;
        data.transformRate = data.convMbrNum * 1 && data.touchMbrNum * 1 ? ((data.convMbrNum / data.touchMbrNum) * 100).toFixed(2) : 0;
        this.marketListData = [{ ...data }];
      });
    },
    getTableHeader() {
      if (this.listTabsIndex != 0) {
        this.tableHeader = [
          {
            label: '排序',
            prop: 'index',
            align: 'left',
            fixed: 'left',
            formatter(row) {
              let color = '#F0F5FF';
              let textColor = '#606266';
              if (row.index == 1) {
                color = '#F5222D';
                textColor = 'white';
              } else if (row.index == 2) {
                color = '#FAAD14';
                textColor = 'white';
              } else if (row.index == 3) {
                color = '#FFCB48';
                textColor = 'white';
              } else if (!row.index) {
                return '--';
              }
              return `<span style="background:${color};color:${textColor};width: 16px; display: inline-block; text-align: center; line-height:16px">${row.index}</span>`;
            }
          },
          {
            label: '区域',
            prop: 'groupName',
            align: 'left',
            fixed: 'left',
            formatter(row) {
              if (!row.groupName) return '--';
              else if (row.groupName == '-1') return '【无归属门店】';
              else if (row.groupName == '区域合计' || row.groupName == '计划整体' || row.groupId == '-1') return row.groupName;
              return `<span style="color:#1890FF;cursor:pointer;" data-type="groupName">${row.groupName}</span>`;
            }
          },
          { label: '触达人数', prop: 'touchMbrNum', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterNum(row.touchMbrNum) },
          { label: '触达率', prop: 'reachRate', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterRate(row.reachRate) },
          { label: '转化人数', prop: 'convMbrNum', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterNum(row.convMbrNum) },
          { label: '触达转化收益', prop: 'convSalesAmt', align: 'left', fixed: 'left', minWidth: '90', sortable: 'custom', formatter: row => this.formatterToFixed(row.convSalesAmt) },
          { label: '客单价', prop: 'customerPrice', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterToFixed(row.customerPrice) },
          { label: '折扣率', prop: 'discountRate', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterToFixed(row.discountRate) }
        ];
      }
      if (this.type == 1 && this.listTabsIndex == 1) {
        this.tableHeader.splice(5, 0, { label: '触达转化率', prop: 'reachConvMbrRate', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterRate(row.reachConvMbrRate) });
      }
      if (this.type == 1 && this.listTabsIndex == 0) {
        this.tableHeader = [
          {
            label: '排序',
            prop: 'index',
            align: 'left',
            fixed: 'left',
            formatter(row) {
              let textColor = '#606266';
              let color = '#F0F5FF';
              if (row.index == 1) {
                textColor = 'white';
                color = '#F5222D';
              } else if (row.index == 2) {
                color = '#FAAD14';
                textColor = 'white';
              } else if (row.index == 3) {
                color = '#FFCB48';
                textColor = 'white';
              } else if (!row.index) {
                return '--';
              }
              return `<span style="background:${color};color:${textColor};width: 16px; display: inline-block; text-align: center; line-height:16px">${row.index}</span>`;
            }
          },
          {
            label: '门店名称',
            prop: 'groupName',
            align: 'left',
            fixed: 'left',
            formatter(row) {
              if (!row.groupName) return '--';
              else if (row.groupName == '-1') return '【无归属门店】';
              else if (row.groupName == '区域合计' || row.groupName == '计划整体' || row.groupId == '-1') return row.groupName;
              return `<span style="color:#1890FF;cursor:pointer;" data-type="groupName">${row.groupName}</span>`;
            }
          },
          { label: '任务总数', prop: 'taskCnt', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterNum(row.taskCnt) },
          { label: '任务完成数', prop: 'cplTaskCnt', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterNum(row.cplTaskCnt) },
          { label: '任务完成率', prop: 'taskCompletionRate', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterRate(row.taskCompletionRate) },
          { label: '任务放弃数', prop: 'tasksAbandonedNum', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterNum(row.tasksAbandonedNum) },
          { label: '逾期未完成', prop: 'overdueNotCompleted', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterNum(row.overdueNotCompleted) },
          { label: '未完成', prop: 'notCompleted', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => this.formatterNum(row.notCompleted) }
        ];
      }
    },
    getTableList() {
      let meth;
      //  storeWidgetKey: this.uuid 门店选择器字段
      let params = { ecmPlanId: this.$route.query.id, pageNum: this.currentPage, pageSize: this.pageSize, orderBy: this.listTabsIndex == 1 ? this.touchOrderBy : this.taskOrderBy, storeGroupId: this.storeGroupId, level: this.level };
      if (this.type == 2) {
        // 后台线索
        meth = ecmHeadCluesTaskTab;
      } else {
        // 导购线索,列表类型切换listTabsIndex 0 为任务完成情况 1为触达效果
        if (this.listTabsIndex == 0) {
          // 任务完成情况
          meth = ecmGuideCluesTaskTable;
          if (this.taskTabIndex != 0) params.taskType = this.taskTabIndex;
        } else {
          if (this.tabsIndex == 0) {
            // 整体计划tab是单独的接口
            meth = ecmGuideCluesTouchEffectTotalTab;
          } else {
            // 其他几个tab接口 带参
            meth = ecmGuideCluesTouchEffectTab;
            params.touchTypes = this.tabsIndex;
          }
        }
      }
      meth(params).then(res => {
        this.tableList = [];
        if (!res.result.result || !res.result.result.length) return;
        // 拼接表头数据
        let resetArr = [];
        this.tableExtra.forEach(item => {
          if (item.groupName == '区域合计') resetArr[0] = item;
          // else if (item.groupName == '计划整体' && this.level < 2) resetArr[1] = item;
        });
        res.result.result && (this.tableList = resetArr.concat(res.result.result));
        this.total = res.result.totalCount;
        this.loading = false;
      });
      this.getTableHeader();
    },
    // 获取合计的行数据
    getTableFirstData() {
      let meth;
      let params = { ecmPlanId: this.$route.query.id, pageSize: this.pageSize, pageNum: this.currentPage, storeGroupId: this.storeGroupId, level: this.level };
      if (this.type == 2) {
        meth = ecmHeadCluesTaskTabHead; // 后台线索计划整体接口
      } else {
        if (this.listTabsIndex == 1) {
          if (this.tabsIndex == 0) {
            meth = ecmGuideCluesTouchEffectTotalTabHead; // 导购线索整体计划的表头
          } else {
            meth = ecmGuideCluesTouchEffectTabHead; // 导购线索其他tab的表头
            params.touchTypes = this.tabsIndex;
          }
        } else {
          meth = ecmGuideCluesTaskTableHead; // 任务完成情况表头
          if (this.taskTabIndex != 0) params.taskType = this.taskTabIndex;
        }
      }
      meth(params).then(res => {
        let data = res.result || {};
        let arr = [];
        for (let key in data) {
          data[key] = data[key] || {};
          data[key].groupName = key == 'thisCalc' ? '区域合计' : '计划整体';
          arr.push(data[key]);
        }
        this.tableExtra = arr;
        this.getTableList();
      });
    },
    // 获取tab切换数据
    getTabData() {
      getTabList({ ecmPlanId: this.$route.query.id, type: this.listTabsIndex }).then(res => {
        let tab = res.result || [];
        if (this.listTabsIndex == 0) this.taskTabs = [{ name: '合计', id: 0 }, ...tab];
        else this.touchTabs = [{ name: '整体转化', id: 0 }, ...tab];
      });
    },
    sortChange(column) {
      let prop = column.prop;
      let orderby = column.order;
      if (orderby == 'descending') orderby = 'desc';
      else orderby = 'asc';
      if (this.listTabsIndex == 1) {
        this.touchOrderBy = prop + ' ' + orderby;
      } else {
        this.taskOrderBy = prop + ' ' + orderby;
      }
      this.getTableList();
    },
    // 懒加载树结构
    async loadNode(node, resolve) {
      let params = { level: node.level, storeGroupId: node.data ? node.data.storeGroupId : null };
      if (node.level === 0) {
        let allStore = await getGroupTree(params);
        allStore.result.forEach(el => {
          el.isLeaf = !el.child;
        });
        this.allStoreId.push(allStore.result[0].storeGroupId); // 设置默认展开所有门店的叶子节点
        this.$nextTick(() => this.$refs.treeList.setCurrentKey(this.allStoreId[0])); // 设置树默认高亮结点
        return resolve(allStore.result || []);
      }
      if (node.level == 1) {
        this.level = node.level;
        this.storeGroupId = node.data ? node.data.storeGroupId : null;
        this.getTableFirstData();
      }
      let otherArea = await getGroupTree(params);
      otherArea.result.forEach(el => {
        el.isLeaf = !el.child;
      });
      return resolve(otherArea.result || []);
    },
    // 点击表格映射到树结构
    onMapTree(row, event) {
      // 展开且选中对应的树，然后调获取合计字段的接口,给表格接口带入树的参数
      if (event.srcElement.dataset.type == 'groupName') {
        this.currentPage = 1;
        this.level = row.level;
        this.storeGroupId = row.groupId;
        this.$refs.treeList.setCurrentKey(row.groupId);
        this.allStoreId.push(row.groupId);
        this.getTableFirstData();
        setTimeout(() => this.allStoreId.splice(this.allStoreId.length - 1, 1)); // 点击表格添加进树结构展开组的要删除掉，否则下次展开树结构会直接加载到对应的叶子结点
      }
    },
    refreshLazyTree(data) {
      if (data.storeGroupId == this.storeGroupId) return;
      this.level = data.level;
      this.storeGroupId = data.storeGroupId;
      this.currentPage = 1;
      this.getTableFirstData();
    },
    // 导出表格数据
    cdkeyExport() {
      this.exportDialog = true;
      let meth;
      let params = { requestProject: 'marketing', ecmPlanId: this.$route.query.id, pageNum: this.currentPage, pageSize: this.pageSize, orderBy: this.listTabsIndex == 1 ? this.touchOrderBy : this.taskOrderBy, storeGroupId: this.storeGroupId, level: this.level };
      if (this.type == 2) {
        meth = headClueTableExport;
      } else {
        if (this.listTabsIndex == 0) {
          meth = taskTableExport;
          if (this.taskTabIndex != 0) params.taskType = this.taskTabIndex;
        } else {
          if (this.tabsIndex == 0) {
            meth = allConvTableExport;
          } else {
            meth = otherTableExoport;
            params.touchTypes = this.tabsIndex;
          }
        }
      }
      this.excelUrl = meth;
      this.params = params;
    }
    // storeChange(val) {  // 门店选择器
    //   console.log(val);
    //   this.isAdd = false;
    //   this.uuid = val;
    //   this.getTableList();
    // },
  },
  beforeRouteEnter: (to, from, next) => {
    if (to.query.type == 1) {
      to.meta.aliasName = '导购线索';
    } else if (to.query.type == 2) {
      to.meta.aliasName = '后台线索';
    }
    next();
  },
  computed: {
    rankStyle() {
      return {
        width: '16px',
        display: 'inline-block',
        'text-align': 'center',
        'line-height': '16px'
      };
    }
    // formatterNum() {
    //   // return val => (!val && val != 0 ? '--' : parseInt(val).toLocaleString());
    //   return val => (!val ? '0' : parseInt(val).toLocaleString());
    // },
    // formatterToFixed() {
    //   // return val => (!val && val != 0 ? '--' : parseFloat(val).toFixed(2));
    //   return val => (!val ? '0.00' : parseFloat(val).toFixed(2));
    // },
    // formatterRate() {
    //   // return val => (!val && val != 0 ? '--' : parseFloat(val).toFixed(2) + '%');
    //   return val => (!val ? '0.00%' : parseFloat(val).toFixed(2) + '%');
    // }
  }
  // watch: {
  //   uuid(val) { // 门店选择器
  //     this.uuid = val;
  //   }
  // }
};
</script>
<style lang="scss" scoped>
.clue {
  .title {
    padding-left: 12px;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 700;
    color: #303133;
    line-height: 22px;
    margin-bottom: 38px;
  }
  .areatitle {
    font-size: 16px;
    padding-left: 32px;
    margin-bottom: 8px;
    display: flex;
    justify-content: space-between;
    padding-right: 20px;
    .txt {
      font-family: PingFangSC-Medium, PingFang SC;
      width: 64px;
      font-weight: 600;
      height: 22px;
      color: #303133;
      line-height: 22px;
    }
  }
  .tab1 {
    height: 40px;
    font-size: 0;
    padding: 0 0 0 33px;
    box-sizing: border-box;
    cursor: pointer;
    position: relative;
    .line {
      position: absolute;
      width: 84px;
      height: 2px;
      background: #1890ff;
      bottom: -1px;
      left: 21px;
      transition: all 0.3s;
      &.lineActive {
        left: 137px;
      }
    }
    .active {
      color: #1890ff;
    }
    span {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #606266;
      line-height: 40px;
      display: inline-block;
      height: 100%;
      position: relative;
      &:nth-child(1) {
        margin-right: 47px;
        &.active::before {
          left: -5px;
        }
      }
    }
  }
  .area_content {
    display: flex;
    border-top: 1px solid #dcdfe6;
    .tree {
      width: 223px;
      padding: 20px 20px 0 0;
      border-right: 1px solid #dcdfe6;
      .node-label {
        font-family: PingFangSC-Regular, PingFang SC;
        color: #303133;
      }
      .custom-tree-node {
        font-family: PingFangSC-Regular, PingFang SC;
        color: #303133;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
      /deep/ .el-tree-node__expand-icon {
        margin-left: 31px;
        color: #606266;
      }
      /deep/ .el-tree-node__content:hover {
        background: rgba(24, 144, 255, 0.06);
      }
      /deep/ .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
        background: rgba(24, 144, 255, 0.06);
      }
      /deep/ .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content .el-tree-node__label {
        color: #1890ff !important;
      }
      /deep/ .el-tree-node__expand-icon.is-leaf {
        color: transparent !important;
      }
    }
    .map_area {
      padding-bottom: 20px;
      width: calc(100% - 243px);
      .top {
        display: flex;
        justify-content: space-between;
        padding: 20px;
        .tab2 {
          display: flex;
          .tab2-item {
            display: inline-block;
            width: 84px;
            height: 32px;
            background: #f5f7fa;
            border-radius: 4px;
            margin-right: 10px;
            font-size: 14px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #606266;
            line-height: 32px;
            text-align: center;
            cursor: pointer;
          }
          .tab2-tip {
            line-height: 32px;
            color: #c0c4cc;
            font-family: PingFangSC-Regular, PingFang SC;
            margin-left: 20px;
          }
          .active2 {
            background: #1890ff;
            color: #fff;
          }
          .derive {
            background: #1890ff;
            color: #fff;
            width: 76px;
          }
        }
        .btn {
          font-family: PingFangSC-Regular, PingFang SC;
        }
      }
    }
  }
}
.area {
  padding: 19px 0 0 !important;
  margin-top: 0 !important;
}
.draw_wrap {
  padding: 16px 20px 32px !important;
  margin-bottom: 10px !important;
}
.dm-pagination {
  margin: 20px 15px 0 0;
  padding: 0;
}
</style>
