<template>
  <div>
    <div class="search-bar">
      <el-select class="contrast" placeholder="选择对比项" clearable v-if="comparative.options.length > 0" v-model="comparative.type" @change="onComparativeChange">
        <el-option v-for="el in comparative.options" :key="el.value" :value="el.value" :label="el.label"></el-option>
      </el-select>
      <div class="contrast-box" v-if="comparative.type">
        <el-select class="contrast-selector" clearable v-model="comparative.subTypeLeft" @change="onSubComparativeChange">
          <el-option v-for="el in subOptions" :disabled="comparative.subTypeRight == el.key" :key="el.key" :value="el.key" :label="el.value"></el-option>
        </el-select>
        <span class="contrast-box-text">vs</span>
        <el-select class="contrast-selector" clearable v-model="comparative.subTypeRight" @change="onSubComparativeChange">
          <el-option v-for="el in subOptions" :disabled="comparative.subTypeLeft == el.key" :key="el.key" :value="el.key" :label="el.value"></el-option>
        </el-select>
      </div>
      <el-button v-if="comparative.type" type="text" @click="onClearComparative">清空对比项</el-button>
    </div>
    <el-table class="comparative-table" v-if="comparative.type && comparative.subTypeLeft && comparative.subTypeRight" :data="comparative.data" v-loading="comparative.loading">
      <el-table-column label="对比项" prop="comparativeType" min-width="160"></el-table-column>
      <el-table-column label="营销人数" prop="marketingNumber" min-width="100" :formatter="(row, col, val) => numFormat(val)"></el-table-column>
      <el-table-column label="触达人数" prop="reachNumber" min-width="100" :formatter="(row, col, val) => numFormat(val)"></el-table-column>
      <el-table-column label="触达率" prop="reachRate" min-width="90" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="转化人数" prop="conversionNumber" min-width="100" :formatter="(row, col, val) => numFormat(val)"></el-table-column>
      <el-table-column label="转化率" prop="conversionRate" min-width="90" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="转化销售额(元)" prop="conversionSale" min-width="120" :formatter="(row, col, val) => numFormat(val)"></el-table-column>
      <el-table-column label="客单价(元)" prop="perCustomerTransaction" min-width="100" :formatter="(row, col, val) => numFormat(val)"></el-table-column>
      <el-table-column label="连带率" prop="associatedPurchaseRate" min-width="70" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="活动费用(元)" prop="activityCost" min-width="110" :formatter="(row, col, val) => numFormat(val)"></el-table-column>
      <el-table-column label="ROI" prop="ROI" min-width="70" :formatter="(row, col, val) => (val == null ? '--' : `1:${val}`)"></el-table-column>
    </el-table>
    <div class="chart-box">
      <div class="chart-member-count" v-if="funnelData.hasData">
        <div class="funnel">
          <div class="funnel-item plan-count">
            <p class="item-label">营销人数</p>
            <p class="item-value">{{ numFormat(funnelData.marketingNumber) }}</p>
          </div>
          <div class="funnel-item target-count">
            <p class="item-label">触达人数</p>
            <p class="item-value">{{ numFormat(funnelData.reachNumber) }}</p>
            <div class="item-rate">
              <p class="rate-label">触达率</p>
              <p class="rate-value">{{ funnelData.reachRate }}</p>
            </div>
          </div>
          <div class="funnel-item change-count">
            <p class="item-label">转化人数</p>
            <p class="item-value">{{ numFormat(funnelData.conversionNumber) }}</p>
            <div class="item-rate">
              <p class="rate-label">转化率</p>
              <p class="rate-value">{{ funnelData.conversionRate }}</p>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="no-data">
        <svg aria-hidden="true" class="no-data-icon">
          <use xlink:href="#icon-cp-no-data"></use>
        </svg>
        暂无数据
      </div>
      <el-row :gutter="20" class="target-list">
        <el-col :span="index == 0 ? 24 : 12" v-for="(el, index) in targetList" :key="index">
          <target-group :data-list="el"></target-group>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getPlanStatistics, getMemberCrowd, getComparativeData } from '@/service/api/aiApi.js';
import { numFormat } from '@/utils/index.js';
import TargetGroup from './target-group.vue';

export default {
  name: 'Conversion',
  props: {
    memberType: {
      type: Number,
      default: 0
    },
    filterJson: {
      type: String,
      default: ''
    }
  },
  components: { TargetGroup },
  data() {
    return {
      numFormat,
      activityId: '',
      planId: '',
      funnelData: {
        hasData: false
      },
      targetList: [
        [
          {
            label: '活动目标(销售额)',
            unit: '元',
            value: '',
            key: 'activityTargetSale',
            type: 'amount'
          },
          {
            label: '实际达成(销售额)',
            unit: '元',
            value: '',
            key: 'actualSale',
            type: 'amount'
          },
          {
            label: '实际达成率',
            value: '',
            key: 'actualReachRate',
            type: 'rate'
          }
        ],
        [
          {
            label: '活动费用',
            tips: '不包含短信发送失败退回金额',
            unit: '元',
            value: '',
            key: 'activityCost',
            type: 'amount'
          },
          {
            label: 'ROI',
            value: '',
            key: 'ROI',
            type: 'roi'
          }
        ],
        [
          {
            label: '客单价',
            unit: '元',
            value: '',
            key: 'perCustomerTransaction',
            type: 'amount'
          },
          {
            label: '连带率',
            value: '',
            key: 'associatedPurchaseRate',
            type: 'number'
          }
        ]
      ],
      comparative: {
        loading: false,
        originData: [],
        data: [],
        options: [],
        type: '',
        subTypeLeft: '',
        subTypeRight: ''
      }
    };
  },
  computed: {
    subOptions() {
      return this.comparative.options.find(el => el.value == this.comparative.type).children;
    }
  },
  created() {
    this.activityId = this.$route.params.id;
    this.planId = this.$route.query.planId;
    this.getPlanStatistics();
    this.getMemberCrowd();
  },
  methods: {
    getPlanStatistics() {
      getPlanStatistics({ activityId: this.activityId, planId: this.planId }).then(res => {
        if (!Array.isArray(res.result)) {
          res.result = [];
        }
        const targetData = res.result.length > 0 ? res.result[0] : {};
        this.targetList = this.targetList.map(el => {
          return el.map(item => {
            const value = targetData[item.key];
            switch (item.type) {
              case 'number':
                item.value = numFormat(value);
                break;
              case 'amount':
                item.value = numFormat(value);
                break;
              case 'rate':
                item.value = value == null ? '--' : value;
                break;
              case 'roi':
                item.value = value == null ? '--' : `1:${value}`;
                break;
            }
            return item;
          });
        });

        this.funnelData = {
          hasData: targetData.marketingNumber != null || targetData.reachNumber != null || targetData.conversionNumber != null,
          // 营销人数
          marketingNumber: targetData.marketingNumber,
          // 触达人数
          reachNumber: targetData.reachNumber,
          // 触达率
          reachRate: targetData.reachRate,
          // 转化人数
          conversionNumber: targetData.conversionNumber,
          // 转化率
          conversionRate: targetData.conversionRate
        };
      });
    },
    getMemberCrowd() {
      this.comparative.options = [];
      if (this.memberType == 0) {
        getMemberCrowd({ memberCrowdWidgetId: this.filterJson }).then(res => {
          if (Object.prototype.toString.call(res.result) != '[object Object]') return;
          const filterFrontShow = JSON.parse(res.result.filterFrontShow || '[]');
          this.comparative.options = filterFrontShow
            .map(typeItem => {
              // 对比项 1会员类型、2会员等级、3金字塔、4会员分组
              const valueMap = { wxMember: 1, gradeId: 2, tagGroup: 3 };
              const result = { label: typeItem.chainNodeName, value: valueMap[typeItem.columnKey], children: [] };
              if (typeItem.columnKey == 'wxMember') {
                result.children = typeItem.selectValue.map(el => {
                  return typeItem.selectList.find(item => item.key == el);
                });
              } else {
                result.children = typeItem.selectList
                  .reduce((result, item) => {
                    return result.concat(item.data);
                  }, [])
                  .filter(item => {
                    return typeItem.selectValue.includes(item.key);
                  });
              }
              return result;
            })
            .filter(el => el.columnKey != 'mainStoreId' && el.children.length > 1);
        });
      } else if (this.memberType == 1) {
        this.axios.get(`/gic-member-tag-web/member-tag-group/queryGroupByIds?requestProject=memberTag&memberTagGroupIds=${this.filterJson}`).then(res => {
          const { errorCode, result } = res.data;
          if (errorCode == 1 && Array.isArray(result)) {
            this.comparative.options = [
              {
                label: '客户分组',
                value: 4,
                children: result.map(el => {
                  return {
                    key: el.memberTagGroupId,
                    value: el.groupName
                  };
                })
              }
            ];
            this.comparative.options = this.comparative.options.filter(el => el.children.length > 1);
          }
        });
      }
    },
    getComparativeData() {
      this.comparative.loading = true;
      // 对比项 1会员类型、2会员等级、3金字塔、4会员分组
      getComparativeData({ activityId: this.activityId, planId: this.planId, comparativeItem: this.comparative.type })
        .then(res => {
          this.comparative.originData = res.result || [];
        })
        .finally(() => (this.comparative.loading = false));
    },
    onComparativeChange() {
      this.comparative.subTypeLeft = '';
      this.comparative.subTypeRight = '';
      this.comparative.data = [];
      this.getComparativeData();
    },
    onSubComparativeChange() {
      if (this.comparative.subTypeLeft && this.comparative.subTypeRight) {
        this.comparative.loading = true;
        setTimeout(() => {
          this.comparative.loading = false;
        }, 500);
        const subTypeLeft = this.subOptions.find(el => el.key == this.comparative.subTypeLeft).value;
        const subTypeRight = this.subOptions.find(el => el.key == this.comparative.subTypeRight).value;
        // 取出对比数据
        this.comparative.data = [];
        this.comparative.data.push(this.comparative.originData.find(el => el.comparativeType == subTypeLeft) || { comparativeType: subTypeLeft });
        this.comparative.data.push(this.comparative.originData.find(el => el.comparativeType == subTypeRight) || { comparativeType: subTypeRight });
      }
    },
    onClearComparative() {
      this.comparative.type = '';
      this.comparative.subTypeLeft = '';
      this.comparative.subTypeRight = '';
      this.comparative.data = '';
    }
  }
};
</script>

<style lang="scss" scoped>
.search-bar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 16px;
  .contrast {
    margin-right: 10px;
    width: 160px;
  }
  .contrast-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-right: 10px;
    width: 300px;
    border-radius: 2px;
    border: 1px solid #dcdfe4;
    .contrast-selector {
      margin-right: 0;
      /deep/ .el-input__inner {
        height: 30px;
        line-height: 30px;
        border: none;
      }
    }
    .contrast-box-text {
      font-size: 14px;
      font-weight: 500;
      color: #2f54eb;
      line-height: 20px;
    }
  }
}
.comparative-table {
  margin-top: 20px;
  /deep/ .el-table__empty-block {
    min-height: 120px;
    .el-table__empty-text {
      margin-bottom: 0;
      &::before {
        margin: 30px auto 0;
      }
    }
  }
}
.chart-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 24px;
  .chart-member-count,
  .target-list {
    flex-shrink: 0;
    width: 50%;
    min-height: 272px;
  }
  .chart-member-count {
    width: calc(50% - 100px);
    margin-right: 100px;
    .funnel {
      margin: 16px auto 0;
      width: 300px;
      background-image: url('../../../assets/img/ai-chart.png');
      background-repeat: no-repeat;
      background-position: center;
      background-size: 100%;
      .funnel-item {
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        padding-right: 17px;
        .item-label {
          font-size: 14px;
          font-weight: 400;
          color: #ffffff;
          line-height: 20px;
        }
        .item-value {
          margin-top: 4px;
          font-size: 24px;
          font-family: DINAlternate-Bold, DINAlternate;
          font-weight: bold;
          color: #ffffff;
          line-height: 28px;
        }
        .item-rate {
          position: absolute;
          top: 0;
          right: -16px;
          z-index: 1;
          transform: translate(100%, -50%);
          .rate-label {
            font-size: 14px;
            font-weight: 400;
            color: #606266;
            line-height: 20px;
          }
          .rate-value {
            margin-top: 4px;
            font-size: 24px;
            font-family: DINAlternate-Bold, DINAlternate;
            font-weight: bold;
            color: #303133;
            line-height: 28px;
          }
        }
      }
      .plan-count {
        height: 75px;
      }
      .target-count {
        height: 68px;
      }
      .change-count {
        height: 69px;
      }
    }
  }
  .no-data {
    width: 50%;
    text-align: center;
    color: #606266;
    font-size: 14px;
    transform: translateY(-40px);
    .no-data-icon {
      display: block;
      width: 120px;
      height: auto;
      margin: 0 auto;
    }
  }
}
</style>
