<template>
  <div class="statistics">
    <div class="report-module">
      <dm-sub-title>活动信息</dm-sub-title>
      <div class="mt20">
        <el-descriptions column="4">
          <el-descriptions-item label="活动名称"> {{ baseData.gameName }}</el-descriptions-item>
          <el-descriptions-item label="活动类型">盲盒</el-descriptions-item>
          <el-descriptions-item label="活动状态"><span :class="gameStatusClass[baseData.status]"></span> {{ gameStatus[baseData.status] }}</el-descriptions-item>
          <el-descriptions-item label="活动有效期">{{ baseData.gameTimeStr }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
    <div class="report-module">
      <dm-sub-title title-align="space-between">
        <div>
          活动数据<span class="tips ml5">(数据实时更新)</span>
          <el-button class="check-detail" @click="toDetailPage(1)" v-if="$getButtonLimit($buttonCode.marketingCmhActivityDetail)" :limit-code="$buttonCode.marketingCmhActivityDetail">查看详情</el-button>
        </div>
      </dm-sub-title>
      <el-row :gutter="20">
        <el-col :span="6" v-for="(el, index) in activityData" :key="index">
          <target-group :data-list="el"></target-group>
        </el-col>
      </el-row>
    </div>
    <div class="report-module" v-if="isCard">
      <dm-sub-title> 卡券核销<span class="tips ml5">(数据每天更新 1 次)</span> </dm-sub-title>
      <el-row :gutter="20" class="flex">
        <el-col :span="6" v-for="(el, index) in cardData" :key="index">
          <target-group :data-list="el"></target-group>
        </el-col>
      </el-row>
    </div>
    <div class="report-module">
      <dm-sub-title title-align="space-between" class="mb20">
        <div>
          奖品数据<span class="tips ml5">(数据每天更新 1 次)</span>
          <el-button class="check-detail" @click="toDetailPage(2)" v-if="$getButtonLimit($buttonCode.marketingCmhPrizeDetail)" :limit-code="$buttonCode.marketingCmhPrizeDetail">查看详情</el-button>
        </div>
      </dm-sub-title>
      <el-radio-group class="customize" v-model="dimension" @change="radioChange" v-show="dimensionOpt.length > 1">
        <el-radio-button :label="item.label" v-for="item in dimensionOpt" :key="item.label">{{ item.value }}</el-radio-button>
      </el-radio-group>
      <el-table :data="prizeList" style="width:100%" :span-method="objectSpanMethod" v-show="dimension == 1" class="mt20">
        <el-table-column v-for="v in tableHead" :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="header" v-if="v.tipsContent">
            {{ v.label }}
            <el-tooltip placement="top">
              <div slot="content">
                {{ v.tipsContent }}
              </div>
              <i class="iconfont icon-QuestionCircleOutlined"></i>
            </el-tooltip>
          </template>
          <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>
      <el-table :data="prizeList" style="width:100%" v-show="dimension == 2" class="mt20">
        <el-table-column v-for="v in pointHead" :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="header" v-if="v.tipsContent">
            {{ v.label }}
            <el-tooltip placement="top">
              <div slot="content">
                {{ v.tipsContent }}
              </div>
              <i class="iconfont icon-QuestionCircleOutlined"></i>
            </el-tooltip>
          </template>
          <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>
    </div>
  </div>
</template>

<script>
import { numFormat, formatDateTimeByType } from '@/utils/index.js';
import { getGameOverview, getGameCardWriteOff, getGameDetail, getGamePrize } from '@/service/api/gameApi.js';
import TargetGroup from '@/components/target-group.vue';
const tableHead = [
  {
    label: '奖品名称',
    minWidth: '206',
    prop: 'prizeName',
    formatter: function(row) {
      return `<span class="ellipsis-l2">${row.prizeName ? row.prizeName : '- -'}</span>`;
    }
  },
  {
    label: '奖品数量',
    prop: 'prizeTotalStock',
    minWidth: '88',
    formatter: function(row) {
      return `<span>${numFormat(row.prizeTotalStock)}</span>`;
    }
  },
  {
    label: '中奖人数',
    prop: 'prizeWinningMNum',
    minWidth: '116',
    formatter: function(row) {
      return `<span>${numFormat(row.prizeWinningMNum)}</span>`;
    }
  },
  {
    label: '中奖率',
    prop: 'prizeWinningRate',
    minWidth: '120',
    tipsContent: '奖项中奖人数/中奖人数',
    formatter: function(row) {
      return `<span>${row.prizeWinningRate ? row.prizeWinningRate + '%' : '- -'}</span>`;
    }
  },
  {
    label: '领取数',
    prop: 'receivedMNum',
    minWidth: '100',
    formatter: function(row) {
      return `<span>${numFormat(row.receivedMNum)}</span>`;
    }
  },
  {
    label: '核销数量',
    prop: 'writeOffNum',
    minWidth: '120',
    formatter: function(row) {
      return `<span>${numFormat(row.writeOffNum)}</span>`;
    }
  },
  {
    label: '核销人数',
    prop: 'writeOffMNum',
    minWidth: '120',
    formatter: function(row) {
      return `<span>${numFormat(row.writeOffMNum)}</span>`;
    }
  },
  {
    label: '核销率',
    prop: 'writeOffRate',
    minWidth: '100',
    formatter: function(row) {
      return `<span>${typeof row.writeOffRate == 'number' ? row.writeOffRate + '%' : '- -'}</span>`;
    }
  },
  {
    label: '客单价',
    prop: 'perCustomerTransaction',
    minWidth: '100',
    formatter: function(row) {
      return `<span>${numFormat(row.perCustomerTransaction)}</span>`;
    }
  },
  {
    label: '连带率',
    prop: 'jointRate',
    minWidth: '100',
    formatter: function(row) {
      return `<span>${row.jointRate ? row.jointRate : '- -'}</span>`;
    }
  }
];
const pointHead = [
  {
    label: '奖品名称',
    minWidth: '206',
    prop: 'prizeName',
    formatter: function(row) {
      return `<span class="ellipsis-l2">${row.prizeName ? row.prizeName : '- -'}</span>`;
    }
  },
  {
    label: '奖品数量',
    minWidth: '120',
    prop: 'prizeTotalStock',
    formatter: function(row) {
      return `<span class="ellipsis-l2">${row.prizeTotalStock ? row.prizeTotalStock : '- -'}</span>`;
    }
  },
  {
    label: '中奖人数',
    prop: 'prizeWinningMNum',
    minWidth: '116',
    formatter: function(row) {
      return `<span>${row.prizeWinningMNum ? row.prizeWinningMNum.toLocaleString() : '- -'}</span>`;
    }
  },
  {
    label: '中奖率',
    prop: 'prizeWinningRate',
    minWidth: '120',
    tipsContent: '奖项中奖人数/中奖人数',
    formatter: function(row) {
      return `<span>${row.prizeWinningRate ? row.prizeWinningRate + '%' : '- -'}</span>`;
    }
  },
  {
    label: '累计中奖积分',
    prop: 'cumulativeIntegral',
    minWidth: '100',
    formatter: function(row) {
      return `<span>${row.cumulativeIntegral ? row.cumulativeIntegral : '- -'}</span>`;
    },
    fixed: 'right'
  }
];
const cardOpt = {
  label: 1,
  value: '卡券'
};
const pointOpt = {
  label: 2,
  value: '积分'
};
export default {
  components: { TargetGroup },
  data() {
    return {
      tableHead,
      pointHead,
      gameStatus: {
        0: '未开始',
        1: '进行中',
        2: '已结束',
        3: '已终止'
      },
      gameStatusClass: {
        0: 'dm-status--info',
        1: 'dm-status--primary--flash',
        2: 'dm-status--info',
        3: 'dm-status--error'
      },
      dimensionOpt: [],
      baseData: {},
      dimension: 1,
      // type number:数字、time:时间、amount:金额、rate:百分比
      originActivityData: [
        [
          {
            label: '浏览人数',
            value: '',
            key: 'browseCnt',
            type: 'number'
          },
          {
            label: '参与人数',
            value: '',
            key: 'palyCnt',
            type: 'number'
          }
        ],
        [
          {
            label: '参与人次',
            value: '',
            key: 'playTimes',
            type: 'number'
          },
          {
            label: '中奖人数',
            value: '',
            key: 'winCnt',
            type: 'number'
          }
        ],
        [
          {
            label: '中奖人次',
            value: '',
            key: 'winTimes',
            type: 'number'
          },
          {
            label: '中奖率',
            tips: '中奖人次/参与人次',
            value: '',
            key: 'winRate',
            type: 'rate'
          }
        ],
        [
          {
            label: '分享人数',
            value: '',
            key: 'shareCnt',
            type: 'number'
          },
          {
            label: '新增会员',
            value: '',
            key: 'openCardCnt',
            type: 'number'
          }
        ],
        [
          {
            label: '总消耗积分',
            value: '',
            key: 'integralUseCnt',
            type: 'number'
          }
        ]
      ],
      activityData: [],
      originCardData: [
        [
          {
            label: '订单总金额',
            value: '',
            tips: '订单实付金额',
            key: 'orderAmount',
            type: 'number'
          },
          {
            label: '参与用户订单数',
            value: '',
            key: 'orderNum',
            type: 'number'
          }
        ],
        [
          {
            label: '领取数量',
            value: '',
            key: 'receivedNum',
            type: 'number'
          },
          {
            label: '核销数量',
            value: '',
            key: 'writeOffNum',
            type: 'number'
          }
        ],
        [
          {
            label: '核销人数',
            value: '',
            key: 'writeOffMNum',
            type: 'number'
          },
          {
            label: '新用户核销人数',
            value: '',
            key: 'newWriteOffMNum',
            type: 'number'
          }
        ],
        [
          {
            label: '核销率',
            value: '',
            key: 'writeOffRate',
            type: 'rate'
          }
        ],
        [
          {
            label: '客单价',
            value: '',
            key: 'perCustomerTransaction',
            type: 'number'
          },
          {
            label: '连带率',
            value: '',
            key: 'jointRate',
            type: 'number'
          }
        ]
      ],
      cardData: [],
      prizeList: [],
      gameId: this.$route.params.id,
      isShare: false, // 有门槛且配置了分享
      isPoint: false, // 有门槛且配置了消耗积分
      isCard: false //奖品配置了卡券
    };
  },
  mounted() {
    const gameId = this.$route.params.id;
    this.getGameDetail(gameId);
  },
  computed: {},
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if ([5, 6, 7, 8, 9].includes(columnIndex)) {
        if (row.row) {
          return {
            rowspan: row.row,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    toDetailPage(type) {
      console.log(type);
      if (type == 1) {
        this.$router.push(`/game/cmh/statistics/activityDetail/${this.gameId}`);
      } else {
        this.$router.push(`/game/cmh/statistics/prizeDetail/${this.gameId}`);
      }
    },
    radioChange(data) {
      this.getGamePrize(data);
    },
    getGameOverview(gameId) {
      getGameOverview({ gameId }).then(res => {
        const { result } = res;
        this.activityData = this.handleData(this.originActivityData, result || {});
      });
    },
    getGameCardWriteOff(gameId) {
      getGameCardWriteOff({ gameId }).then(res => {
        const { result } = res;
        this.cardData = this.handleData(this.originCardData, result || {});
      });
    },
    getGameDetail(gameId) {
      getGameDetail({ gameId }).then(res => {
        const {
          result: {
            startDate,
            endDate,
            gameName,
            status,
            gameRuleConditionList,
            gamePrizeList,
            gameRuleInfo: { playConditionFlag }
          }
        } = res;
        if (playConditionFlag == 1) {
          gameRuleConditionList.map(item => item.conditionType).includes(1) ? (this.isShare = true) : '';
          gameRuleConditionList.map(item => item.conditionType).includes(0) ? (this.isPoint = true) : '';
        }
        let startDateStr = formatDateTimeByType(startDate, 'yyyy-MM-dd');
        let endDateStr = formatDateTimeByType(endDate, 'yyyy-MM-dd');
        let gameTimeStr = startDateStr + ' 至 ' + endDateStr;
        this.baseData = { gameTimeStr, gameName, status };
        this.getGameOverview(gameId); // 活动基础数据
        if (gamePrizeList.map(item => item.prizeType).includes(2)) {
          this.isCard = true;
          this.getGameCardWriteOff(gameId); // 卡券核销数据
          this.getGamePrize(1);
        } else if (gamePrizeList.map(item => item.prizeType).includes(1)) {
          this.getGamePrize(2);
        }
        if (gamePrizeList.map(item => item.prizeType).includes(2)) {
          this.dimensionOpt.push(cardOpt);
        }
        if (gamePrizeList.map(item => item.prizeType).includes(1)) {
          this.dimensionOpt.push(pointOpt);
        }
      });
    },
    getGamePrize(prizeType) {
      getGamePrize({ gameId: this.$route.params.id, prizeType }).then(res => {
        const { result } = res;
        this.prizeList = result;
        prizeType == 1 ? this.handleList() : '';
      });
    },
    handleList() {
      let obj = {};
      this.prizeList.forEach(item => {
        if (obj[item.cardId]) {
          obj[item.cardId].push(item);
        } else {
          obj[item.cardId] = [item];
        }
      });
      Object.values(obj).forEach(arr => {
        arr[0].row = obj[arr[0].cardId].length;
      });
      this.prizeList = Object.values(obj).flat();
    },
    handleData(data, obj) {
      return data
        .map(el => {
          return el.filter(item => {
            const value = obj[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)
                    .toString()
                    .padStart(2, '0');
                  const m = Math.floor((value % 3600) / 60)
                    .toString()
                    .padStart(2, '0');
                  const s = (value % 60).toString().padStart(2, '0');
                  item.value = `${h}:${m}:${s}`;
                }
                break;
              case 'amount':
                item.value = numFormat(value);
                break;
              case 'rate':
                item.value = value ? value + '%' : '- -';
                break;
            }
            if (['shareCnt', 'openCardCnt'].includes(item.key)) {
              return this.isShare;
            }
            if (['integralUseCnt'].includes(item.key)) {
              return this.isPoint;
            }
            return true;
          });
        })
        .filter(el => el.length > 0);
    }
  }
};
</script>

<style lang="scss" scoped>
.statistics {
  background-color: #f7f8fa;
  .report-module {
    padding: 16px 20px 20px 20px;
    background-color: #fff;
    + .report-module {
      margin-top: 16px;
    }
    .title-tip {
      margin-left: 4px;
      font-size: 12px;
      font-weight: 400;
      color: #606266;
      line-height: 17px;
    }
    .check-detail {
      margin-left: 16px;
      color: #2f54eb;
      background: #ebeffe;
      border: none;
      &:hover {
        background: #dee3fc;
      }
    }
  }
  .tips {
    font-weight: 400;
    color: #606266;
    line-height: 17px;
  }
}
.flex {
  display: flex;
  flex-wrap: wrap;
}
</style>
