<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" />
      <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="tabs" v-if="type == 1">
        <div class="tab1">
          <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="tab2">
          <span v-for="item in listTabsIndex == 1 ? touchTabs : taskTabs" :key="item.value" :class="{ active2: listTabsIndex == 1 ? item.value == tabsIndex : item.value == taskTabIndex }" @click="changeTabs(item.value)">{{ item.name }}</span>
        </div> -->
      </div>
      <el-table ref="table" tooltipEffect="light" :data="tableList" style="width: 100%" element-loading-text="拼命加载中" @sort-change="sortChange" :style="{ marginTop: '20px', padding: '0 20px 0 22px' }">
        <el-table-column v-for="(v, i) in tableHeader" :key="i" :prop="v.prop" :label="v.label" :formatter="v.formatter" :sortable="v.sortable">
          <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="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>
</template>

<script>
// ecmGuideCluesTouchEffectTabTotalHead1
import { ecmGuideCluesTable, ecmHeadCluesTaskTab, ecmHeadGuideCluesTable, ecmHeadCluesTaskTabHead, ecmGuideCluesTaskTable, ecmGuideCluesTouchEffectTotalTab, ecmGuideCluesTouchEffectTabTotalHead, ecmGuideCluesTouchEffectTab, ecmGuideCluesTouchEffectTabHead } from '@/service/api/ecmApi.js';
import marketList from '@/views/ecm/touch-components/market-list.vue';
import touchCharts from '@/views/ecm/touch-components/touch-charts.vue';
export default {
  name: 'touch-clue',
  components: {
    marketList,
    touchCharts
  },
  data() {
    return {
      tableHeader: [],
      tableList: [],
      touchTabs: [
        {
          name: '整体转化',
          value: 0
        },
        {
          name: '企业电话',
          value: 1
        },
        {
          name: '私人电话',
          value: 2
        },
        {
          name: '企业微信',
          value: 3
        },
        {
          name: '私人短信',
          value: 4
        },
        {
          name: '话务',
          value: 999
        }
      ],
      taskTabs: [
        {
          name: '合计',
          value: 0
        },
        {
          name: '企业微信',
          value: 1
        },
        {
          name: '话务',
          value: 999
        }
      ],
      listTabs: [
        {
          name: '触达效果',
          value: 1
        },
        {
          name: '任务完成情况',
          value: 0
        }
      ],
      tabsIndex: 0,
      taskTabIndex: 0,
      listTabsIndex: 1,
      type: 1, // 1导购 2后台
      marketListData: [],
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableFirstData: {},
      // headClueTableFirstData: [], // 后台线索的表头第一期不做两个
      touchOrderBy: '',
      taskOrderBy: '',
      uuid: '', // 新增传空，编辑必传,
      options: [0, 4, 5], // 0 全部 1 门店类型 2门店标签 3 门店区域 4 门店分组 5 部分门店
      isAdd: true,
      isHeade2: false
    };
  },
  mounted() {
    let planName = this.$route.query.planName;
    let name;
    let planId = this.$route.query.id;
    this.type = this.$route.query.type;
    this.getMarketList();
    if (this.type == 2) {
      // this.getTableFirstData();
      // this.getTableFirstData(true); // 后台线索调第二个表头接口,第一期不做
      name = '后台线索';
    } else {
      name = '导购线索';
      // this.getTableFirstData();
    }
    this.getTableFirstData();
    this.$store.commit('mutations_breadcrumb', [{ name: '营销管理', path: '' }, { name: '智能营销', path: '/ecm' }, { name: `${planName} - 触达效果`, path: `/ecm/touch/${planId}?name=${planName}` }, { 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) {
      this.listTabsIndex = index;
      this.currentPage = 1;
      this.$refs.table.clearSort();
      this.getTableList();
    },
    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.flag = true;
        }
        data.touchRate = parseFloat(((data.touchMbrNum / data.planMbrNum) * 100).toFixed(2));
        data.transformRate = parseFloat(((data.convMbrNum / data.touchMbrNum) * 100).toFixed(2));
        this.marketListData = [{ ...data }];
      });
    },
    getTableHeader() {
      if (this.listTabsIndex != 0) {
        this.tableHeader = [
          {
            label: '排名',
            prop: 'index',
            minWidth: '160',
            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: 'storeName', minWidth: '160', align: 'left', fixed: 'left' },
          { label: '触达人数', prop: 'touchMbrNum', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom' },
          { label: '触达率', prop: 'reachRate', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => row.reachRate && row.reachRate.toFixed(2) + '%' },
          { label: '转化人数', prop: 'convMbrNum', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom' },
          { label: '触达转化收益', prop: 'convSalesAmt', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => row.convSalesAmt && row.convSalesAmt.toFixed(2) },
          { label: '客单价', prop: 'customerPrice', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => row.customerPrice && row.customerPrice.toFixed(2) },
          { label: '折扣率', prop: 'discountRate', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => row.discountRate && row.discountRate.toFixed(2) }
        ];
      }
      if (this.type == 1 && this.listTabsIndex == 0) {
        this.tableHeader = [
          {
            label: '排名',
            prop: 'index',
            minWidth: '160',
            align: 'left',
            fixed: 'left',
            formatter(row) {
              let color = '#F0F5FF';
              if (row.index == 1) {
                color = '#F5222D';
              } else if (row.index == 2) {
                color = '#FAAD14';
              } else if (row.index == 3) {
                color = '#FFCB48';
              } else if (!row.index) {
                return '--';
              }
              return `<span style="background:${color};width: 16px; display: inline-block; text-align: center; line-height:16px">${row.index}</span>`;
            }
          },
          { label: '门店名称', prop: 'storeName', minWidth: '160', align: 'left', fixed: 'left' },
          { label: '任务总数', prop: 'taskCnt', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom' },
          { label: '任务完成数', prop: 'cplTaskCnt', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom' },
          { label: '任务完成率', prop: 'taskCompletionRate', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom', formatter: row => row.taskCompletionRate && row.taskCompletionRate.toFixed(2) + '%' },
          { label: '任务放弃数', prop: 'tasksAbandonedNum', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom' },
          { label: '逾期未完成', prop: 'overdueNotCompleted', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom' },
          { label: '未完成', prop: 'notCompleted', minWidth: '160', align: 'left', fixed: 'left', sortable: 'custom' }
        ];
      }
    },
    getTableList() {
      let meth;
      let params = { ecmPlanId: this.$route.query.id, pageNum: this.currentPage, pageSize: this.pageSize, orderBy: this.listTabsIndex == 1 ? this.touchOrderBy : this.taskOrderBy, storeWidgetKey: this.uuid };
      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;
        }
        if (this.currentPage == 1 && this.listTabsIndex != 0) {
          // 任务完成情况无表头
          let resetArr = [];
          // if (this.type == 2) {
          //   this.headClueTableFirstData.forEach(item => {
          //     if (item.storeName == '区域合计') resetArr[1] = item;
          //     else if (item.storeName == '计划整体') resetArr[0] = item;
          //   });
          // } else {
          //   resetArr[0] = this.tableFirstData;
          // }
          resetArr[0] = this.tableFirstData;
          res.result.result && (this.tableList = resetArr.concat(res.result.result));
        } else {
          this.tableList = res.result.result;
        }
        this.total = res.result.totalCount;
        this.loading = false;
      });
      this.getTableHeader();
    },
    getTableFirstData(head2) {
      let meth;
      let params = { ecmPlanId: this.$route.query.id };
      if (this.type == 2) {
        // 后台线索 要调两个表头接口
        // if (head2) {
        //   this.isHeade2 = true;
        //   meth = ecmGuideCluesTouchEffectTabTotalHead1;
        // } else meth = ecmHeadCluesTaskTabHead;
        meth = ecmHeadCluesTaskTabHead;
      } else {
        if (this.listTabsIndex == 1) {
          if (this.tabsIndex == 0) {
            meth = ecmGuideCluesTouchEffectTabTotalHead;
          } else {
            meth = ecmGuideCluesTouchEffectTabHead;
            params.touchTypes = this.tabsIndex;
          }
        } else {
          this.getTableList();
          return;
        }
      }
      meth(params).then(res => {
        let data = res.result;
        data.storeName = '合计';
        if (this.type == 2) data.storeName = '计划整体';
        // if (this.type == 2 && !head2) {
        //   data.storeName = '计划整体';
        // } else if (this.type == 2 && head2) {
        //   data.storeName = '区域合计';
        // }
        this.tableFirstData = data;
        // if (this.type == 2) {
        //   this.headClueTableFirstData.push(data);
        // }
        // if (this.type == 2 && head2) this.getTableList();
        // else if (this.type == 1) this.getTableList();
        this.getTableList();
      });
    },
    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();
    },
    storeChange(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'
      };
    }
  },
  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;
    }
  }
  .tabs {
    .tab2 {
      cursor: pointer;
      margin-top: 20px;
      display: flex;
      padding-left: 22px;
      span {
        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;
      }
      .active2 {
        background: #1890ff;
        color: #fff;
      }
      .derive {
        background: #1890ff;
        color: #fff;
        width: 76px;
      }
    }
    .tab1 {
      height: 40px;
      font-size: 0;
      padding: 0 0 0 33px;
      box-sizing: border-box;
      border-bottom: 1px solid #dcdfe6;
      cursor: pointer;
      position: relative;
      .line {
        position: absolute;
        width: 84px;
        height: 2px;
        background: #1890ff;
        bottom: 0px;
        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 {
  padding: 19px 0 20px 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>
