<template>
  <section class="dm-wrap" v-loading="loading">
    <div class="game" v-if="notShrink == 1">
      <div class="game-content">
        <div class="gameDemo">
          <div class="title">游戏演示</div>
          <el-image lazy style="width: 180px; height: 312px; cursor: pointer" :src="img" @click.native="onView()"> </el-image>
        </div>
        <div class="gameIntro">
          <div class="title">游戏介绍</div>
          <div class="content">
            <div class="mini-title">玩法介绍</div>
            <div class="text">
              <p><span class="dm-status--normal"></span>商户设定盲盒礼品与数量，支持换肤，适应不同营销场景</p>
              <p><span class="dm-status--normal"></span>用户可免费/消耗积分/好友助力拆盲盒，刺激用户分享，实现活动传播与拉新裂变</p>
              <p><span class="dm-status--normal"></span>盲盒拆开后即可获得奖品</p>
            </div>
          </div>
          <div class="content">
            <div class="mini-title">流程配置</div>
            <div class="text">
              <p><span class="dm-status--normal"></span>配置游戏基础内容——如游戏背景、盲盒样式、背景音乐等</p>
              <p><span class="dm-status--normal"></span>配置游戏奖项——设定盲盒奖品、库存、中奖率等</p>
              <p><span class="dm-status--normal"></span>配置游戏规则——配置游戏玩法、参与门槛与条件等</p>
              <el-button type="text" class="fz12" style="margin-left: 13px" @click="goDetail">查看详细配置说明</el-button>
            </div>
          </div>
        </div>
      </div>
      <el-button type="text" @click="shrink(0)" style="width: 100%">收起 <i class="iconfont-components3 icon-cp-shangjiantou" style="font-size: 12px"/></el-button>
    </div>
    <dm-sub-title v-else>
      <div class="gameName">
        幸运盲盒
        <img @click="shrink(1)" style="width: 240px; height: 50px; cursor: pointer" src="https://pic01-10001430.cos.ap-shanghai.myqcloud.com/game/template1/banner_web.png" />
      </div>
    </dm-sub-title>
    <div class="pt20 pb20 clearfix">
      <el-date-picker class="w256" v-model="dateTime" value-format="yyyy-MM-dd" @change="refresh" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
      <el-input v-model="listParams.gameName" class="w260" placeholder="输入游戏名称" clearable @change="refresh"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-select class="w160" v-model="listParams.status" placeholder="所有游戏状态" @change="refresh" clearable>
        <el-option v-for="(v, i) in gameStatusOptions" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-checkbox class="vertical-middle ml0" v-if="$store.state.marketing.isShowSelf" v-model="listParams.createMe" :true-label="1" :false-label="0" label="仅看本人" border @change="refresh" />
      <el-button class="fr" type="primary" @click="addGame" v-if="$getButtonLimit($buttonCode.marketingCmhAdd)" :limit-code="$buttonCode.marketingCmhAdd">新建游戏</el-button>
    </div>

    <el-table tooltipEffect="light" :data="tableList" style="width: 100%" :height="tableH">
      <el-table-column label="游戏名称" fixed="left" min-width="183px" prop="gameName" show-overflow-tooltip :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="游戏时间" min-width="134px">
        <template slot-scope="{ row }">
          <p class="cell-time">
            {{ formatDateTimeByType(row.startDate, 'yyyy-MM-dd') }} 至<br />

            {{ formatDateTimeByType(row.endDate, 'yyyy-MM-dd') }}
          </p>
        </template>
      </el-table-column>
      <el-table-column label="参与门槛" min-width="96px" prop="playConditionFlag	">
        <template slot-scope="{ row }">
          {{ row.playConditionFlag == 1 ? '有门槛' : row.playConditionFlag == 0 ? '无门槛' : '- -' }}
        </template>
      </el-table-column>
      <el-table-column label="浏览人数" min-width="96px" prop="browseCnt"></el-table-column>
      <el-table-column label="参与人数" min-width="96px" prop="palyCnt"></el-table-column>
      <el-table-column label="参与人次" min-width="96px" prop="playTimes"></el-table-column>
      <el-table-column label="中奖人数" min-width="96px" prop="winCnt"></el-table-column>
      <el-table-column label="游戏状态" min-width="96px" prop="status">
        <template slot-scope="{ row }">
          <div><span :class="gameStatusClass[row.status]"></span>{{ gameStatus[row.status] }}</div>
        </template>
      </el-table-column>
      <el-table-column label="创建人" min-width="88px" prop="creatorName" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建时间" min-width="114px" prop="createTime">
        <template slot-scope="{ row }">
          {{ formatDateTimeByType(row.createTime, 'yyyy-MM-dd') }}<br />
          {{ formatDateTimeByType(row.createTime, 'HH-mm-ss') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="153px">
        <template slot-scope="{ row }">
          <dm-dropdown ref="drop" :scope-data="row" :configs="btnArr" @command="onCommand" />
        </template>
      </el-table-column>
    </el-table>

    <dm-pagination v-if="tableList.length" background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listParams.pageNum" :page-sizes="[20, 40, 60, 80]" :page-size="listParams.pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
    <links :show.sync="linkShow" :obj="linksObj" gameTypeName="幸运盲盒" :isNew="true"></links>
  </section>
</template>
<script>
import { api as viewerApi } from 'v-viewer';
import { cmhPage, stopGame, pageStatistics } from '@/service/api/gameApi.js';
import links from '../common/links';
import { formatDateTimeByType } from '@/utils/index.js';

export default {
  components: {
    links
  },
  data() {
    return {
      formatDateTimeByType,
      linkShow: false,
      linksObj: {},
      img: 'https://pic01-10001430.cos.ap-shanghai.myqcloud.com/game/template1/mould_share_page.png',
      listParams: {
        gameName: '',
        status: '',
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 20
      },
      total: 0,
      gameId: '',
      tableList: [],
      gameStatusOptions: [
        {
          label: '未开始',
          value: 0
        },
        {
          label: '进行中',
          value: 1
        },
        {
          label: '已结束',
          value: 2
        },
        {
          label: '已终止',
          value: 3
        }
      ],
      gameStatus: {
        0: '未开始',
        1: '进行中',
        2: '已结束',
        3: '已终止'
      },
      gameStatusClass: {
        0: 'dm-status--info',
        1: 'dm-status--primary--flash',
        2: 'dm-status--info',
        3: 'dm-status--error'
      },
      dateTime: [],
      loading: false,
      notShrink: 0,
      btnArr: [
        {
          text: '查看',
          props: {
            limitCode: this.$buttonCode.marketingCmhInfo
          },
          visible: row => {
            return this.$getButtonLimit(this.$buttonCode.marketingCmhInfo);
          },
          handler: row => window.open(`/marketing/#/game/cmh/info/${row.gameId}`)
          // handler: row => this.$router.push('/game/cmh/info/' + row.gameId)
        },
        {
          text: '编辑',
          props: {
            limitCode: this.$buttonCode.marketingCmhEdit
          },
          visible: row => {
            return (row.status === 1 || row.status === 0) && this.$getButtonLimit(this.$buttonCode.marketingCmhEdit);
          },
          // handler: row => this.$router.push('/game/cmh/edit/' + row.gameId)
          handler: row => window.open(`/marketing/#/game/cmh/edit/${row.gameId}`)
        },
        {
          text: '复制',
          props: {
            limitCode: this.$buttonCode.marketingCmhCopy
          },
          visible: row => {
            return this.$getButtonLimit(this.$buttonCode.marketingCmhCopy);
          },
          // handler: row => this.$router.push('/game/cmh/copy/' + row.gameId)
          handler: row => window.open(`/marketing/#/game/cmh/copy/${row.gameId}`)
        },
        {
          text: '链接',
          props: {
            limitCode: this.$buttonCode.marketingCmhLink
          },
          visible: row => {
            return (row.status === 1 || row.status === 0) && this.$getButtonLimit(this.$buttonCode.marketingCmhLink);
          },
          handler: row => this.getLink(row)
        },
        {
          text: '终止',
          props: {
            limitCode: this.$buttonCode.marketingCmhStop
          },
          visible: row => {
            return (row.status === 1 || row.status === 0) && this.$getButtonLimit(this.$buttonCode.marketingCmhStop);
          },
          handler: row => this.stopGame(row)
        },
        {
          text: '数据',
          props: {
            limitCode: this.$buttonCode.marketingCmhStatistics
          },
          visible: row => {
            return (row.status === 1 || row.status === 2 || row.status === 3) && this.$getButtonLimit(this.$buttonCode.marketingCmhStatistics);
          },
          handler: row => this.$router.push('/game/cmh/statistics/' + row.gameId)
        }
      ]
    };
  },
  computed: {
    tableH() {
      const h = window.innerHeight - 218 - 82;
      return h;
    }
  },
  mounted() {
    if (this.$route.meta.refresh) {
      this.dateTime = [];
      this.listParams = {
        gameName: '',
        status: '',
        startTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 20
      };
    } else {
      const data = JSON.parse(sessionStorage.getItem('listParams'));
      const { dateTime, listParams } = data;
      this.dateTime = dateTime;
      this.listParams = Object.assign({}, listParams);
    }
    this.getTableList();
  },
  beforeRouteEnter(to, from, next) {
    const {
      path,
      meta: { type, refresh }
    } = from;
    if (path.indexOf('/cmh') <= 0) {
      to.meta.refresh = true;
    } else {
      if (type === 'add' && refresh) {
        to.meta.refresh = true;
      } else {
        to.meta.refresh = false;
      }
    }
    next();
  },
  methods: {
    goDetail() {
      window.open('https://www.yuque.com/exnmlu/hpbb1c/yf16om');
    },
    getLink(row) {
      const { startDate, gameId, gameName } = row;
      this.linksObj = { gameName, gameId, gameStartTime: startDate };
      this.linkShow = true;
    },
    stopGame(row) {
      const { gameId } = row;
      this.$confirm('终止后游戏结束，用户无法继续参与。是否确认终止?', '终止提示', {
        confirmButtonText: '终止',
        cancelBUttonText: '取消',
        type: 'warning'
      })
        .then(() => {
          stopGame({ gameId }).then(res => {
            this.$message.success('终止成功');
            this.getTableList();
          });
        })
        .catch(() => {});
    },
    refresh() {
      this.listParams.pageNum = 1;
      this.getTableList();
    },
    handleSizeChange(val) {
      this.listParams.pageNum = 1;
      this.listParams.pageSize = val;
      this.getTableList();
    },
    handleCurrentChange(val) {
      this.listParams.pageNum = val;
      this.getTableList();
    },
    addGame() {
      window.open('/marketing/#/game/cmh/add');
    },
    onView() {
      let qrImg = this.img;
      viewerApi({
        images: [qrImg],
        options: {
          toolbar: false,
          navbar: false,
          title: false,
          zIndex: 9999
        }
      });
    },
    shrink(val) {
      this.notShrink = val;
    },
    getTableList() {
      if (this.dateTime && this.dateTime.length) {
        this.listParams.startTime = this.dateTime[0];
        this.listParams.endTime = this.dateTime[1];
      } else {
        this.listParams.startTime = '';
        this.listParams.endTime = '';
      }
      this.loading = true;
      const data = { dateTime: this.dateTime, listParams: this.listParams };
      sessionStorage.setItem('listParams', JSON.stringify(data));
      cmhPage(this.listParams)
        .then(res => {
          this.tableList = res.result.list || [];
          this.total = res.result.total || 0;
          this.notShrink = this.tableList.length > 0 ? 0 : 1;
          let ids = this.tableList.map(item => item.gameId).join(',');
          this.pageStatistics(ids);
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    pageStatistics(ids) {
      pageStatistics({ ids }).then(res => {
        const { result } = res;
        let obj = {};
        result.forEach(element => {
          obj[element.gameId] = element;
        });
        this.tableList.forEach(item => {
          if (obj[item.gameId]) {
            const { browseCnt, palyCnt, winCnt, playTimes } = obj[item.gameId];
            item.browseCnt = browseCnt;
            item.palyCnt = palyCnt;
            item.winCnt = winCnt;
            item.playTimes = playTimes;
          } else {
            item.browseCnt = '- -';
            item.palyCnt = '- -';
            item.winCnt = '- -';
            item.playTimes = '- -';
          }
        });
        this.tableList = this.tableList.splice(0);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}

.game {
  width: 100%;
  padding: 16px 20px;
  box-sizing: border-box;
  background: #f7f8fa;
}

.game-content {
  display: flex;
  justify-content: flex-start;

  .title {
    color: #303133;
    font-weight: 500;
    font-size: 14px;
    margin-bottom: 16px;
  }

  .mini-title {
    font-size: 12px;
  }

  .gameIntro {
    margin-left: 90px;

    .content {
      display: flex;
      margin-bottom: 30px;

      .text {
        margin-left: 58px;

        p {
          font-size: 12px;
          margin-bottom: 10px;
        }
      }
    }
  }
}
.gameName {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
}
</style>
