<template>
  <div class="p20" v-loading="loading">
    <div class="pb20 clearfix flex-center">
      <el-select v-model="listParams.appCode" class="w140 mr10" placeholder="所有应用来源" clearable @change="refresh">
        <el-option v-for="item in appList" :key="item.appCode" :label="item.appName" :value="item.appCode"></el-option>
      </el-select>
      <el-input prefix-icon="el-icon-search" placeholder="请输入活动名称" class="w300 mr10" v-model="listParams.activityName" clearable @change="refresh" />
      <el-input placeholder="请输入关键字" class="w400 mr10" v-model="listParams.search" clearable @change="refresh">
        <el-select v-model="listParams.searchType" slot="prepend" style="width:120px;" placeholder="请选择" @change="refresh">
          <el-option label="福利ID" :value="1"></el-option>
          <el-option label="卡券包名称" :value="2"></el-option>
          <el-option label="备注名" :value="3"></el-option>
          <el-option label="会员称呼" :value="4"></el-option>
          <el-option label="会员手机号" :value="5"></el-option>
          <el-option label="会员卡号" :value="6"></el-option>
        </el-select>
      </el-input>
      <el-button class="ml10" type="text" @click="isOpen = !isOpen">{{ isOpen ? '收起' : '展开' }}<i :class="`${isOpen ? 'el-icon-arrow-up' : 'el-icon-arrow-down'} el-icon--right ml5`"></i></el-button>
    </div>
    <div v-show="isOpen" class="table-search-head p20">
      <el-tooltip content="数据量较大，最多支持筛选7日，请耐心等待" placement="bottom" open-delay="200">
        <span class="tooltip-icon">发放时间</span>
      </el-tooltip>
      ：<el-date-picker class="w350 mr10" v-model="dateTime" type="daterange" range-separator="~" start-placeholder="领取开始日期" end-placeholder="领取结束日期" @change="changeTime" :clearable="false"></el-date-picker>
    </div>
    <el-table class="mt20" tooltip-effect="dark" :data="tableList" style="width:100%" :default-sort="{prop: 'createTime', order: ''}" @sort-change="sortChange">
      <el-table-column label="会员信息" fixed="left" min-width="120px">
        <template slot-scope="scope">
          <member-info :member-name="scope.row.memberName" :member-image="scope.row.memberImage" :member-phone="scope.row.memberPhone || scope.row.memberCardNo"></member-info>
        </template>
      </el-table-column>
      <el-table-column sortable prop="createTime" label="发放时间" min-width="120px">
        <template slot-scope="scope">
          <div v-html="listTime(scope.row.createTime)"></div>
        </template>
      </el-table-column>
      <el-table-column prop="packageLogId" label="外部单号" min-width="120px"></el-table-column>
      <el-table-column prop="name" label="卡券包名称" min-width="140px"></el-table-column>
      <el-table-column label="卡券数量" min-width="130px">
        <template slot="header">
          <el-tooltip placement="top" content="卡券包中会员真实领取的卡券数量" open-delay="200">
            <span class="tooltip-icon">卡券数量</span>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <el-popover
            placement="top"
            width="500"
            trigger="click">
            <el-table tooltip-effect="dark" :data="packageLogList" style="width:100%" max-height="400px">
              <el-table-column prop="couponName" label="卡券名称" show-overflow-tooltip :min-width="140">
                <template slot-scope="{row}">
                  <el-tag class="mr5">{{ cardType[row.cardType].label }}</el-tag>
                  {{ row.couponName }}
                </template>
              </el-table-column>
              <!-- <el-table-column prop="cardType" label="卡券类型">
                <span slot-scope="scope">{{ cardType[scope.row.cardType].label }}</span>
              </el-table-column> -->
              <el-table-column prop="statusFlag" label="领取状态">
                <span slot-scope="scope" :class="scope.row.statusFlag == 4 ? 'state-point state-point-success' : ''">{{ scope.row.statusFlag == 4 ? '已领取' : '--' }}</span>
              </el-table-column>
              <el-table-column prop="couponLogId" label="卡券代码"></el-table-column>
            </el-table>
            <el-button slot="reference" type="text" @click="showDetail(scope.row)">{{ scope.row.receiveCount || 0 }}</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="来源" min-width="150px">
        <template slot-scope="scope">
          <div>{{ scope.row.appName || '--' }}</div>
          <div class="fz12 gray02">{{ scope.row.activityName || '--' }}</div>
        </template>
      </el-table-column>
    </el-table>
    <div class="clearfix">
      <dm-pagination class="fr mb0" v-if="tableList.length" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listParams.currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="listParams.pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
    </div>
    <el-dialog title="卡券包" :visible.sync="dialogVisible" width="1000px" @closed="packageLogList = [];">
      <el-table tooltip-effect="dark" :data="packageLogList" style="width:100%" max-height="400px">
        <el-table-column prop="couponName" label="卡券名称"></el-table-column>
        <el-table-column prop="cardType" label="卡券类型">
          <span slot-scope="scope">{{ cardType[scope.row.cardType].label }}</span>
        </el-table-column>
        <el-table-column prop="statusFlag" label="卡券类型">
          <span slot-scope="scope">{{ scope.row.statusFlag == 4 ? '已领取' : '--' }}</span>
        </el-table-column>
        <el-table-column prop="couponLogId" label="卡券代码"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { cardType } from '@/config/mapping/gic-card';
import { page, formate } from '@/mixins/table.js';
import { listTime } from '@/utils/index.js';
import api from '@/api/card-package.js';
import commonApi from '@/api/common.js';
const { pagePackageLog, listCouponByPackageId } = api;
const { getAppList } = commonApi;

export default {
  name: 'MergeRecordList',
  mixins: [ page, formate  ],
  data() {
    return {
      loading: false,
      cardType,
      appList: [], // 应用列表
      dateTime: [ Date.now(), Date.now() ], // 默认当天
      dateTimeCopy: [ Date.now(), Date.now() ],
      listParams: {
        activityName: '',
        appCode: '',
        beginTime: '',
        endTime: '',
        search: '',
        searchType: 2, // 1、福利id 2、卡券包名称、3、备注名、、4会员称呼、5会员手机号、6会员卡号
        currentPage: 1,
        pageSize: 20,
        sortOrder: '', // 默认可以不传; asc:升序; desc:倒序
        couponPackageId: this.$route.query.id // 卡券包id
      },
      tableList: [],
      total: 0,
      dialogVisible: false,
      packageLogLoading: false,
      packageLogList: [],
      isOpen: false
    };
  },
  created() {
    if('id' in this.$route.query) {
      this.$emit('updateBread', [ { breadName: '卡券包列表', breadPath: '/card-package/list' }, { breadName: '卡券包发放记录' } ]);
    } else {
      this.$emit('updateBread', [ { breadName: '卡券包发放记录' } ]);
    }
  },
  mounted() {
    this.getTableList();
    this.getAppList();
  },
  methods: {
    listTime,
    sortChange(sort) {
      this.listParams.sortOrder = sort.order ? sort.order == 'ascending' ? 'asc' : 'desc' : '';
      this.refresh();
    },
    changeTime(date) {
      if (new Date(this.dateTime[1]).getTime() - new Date(this.dateTime[0]).getTime() > 7 * 24 * 60 * 60 * 1000) {
        this.$tips({ message: '时间段范围不能超过7天', type: 'warning' });
        this.dateTime = [ ...this.dateTimeCopy ];
        return;
      }
      this.dateTimeCopy = [ ...this.dateTime ];
      this.refresh();
    },
    getAppList() {
      getAppList().then(res => {
        this.appList = res.result || [];
      });
    },
    showDetail({ packageLogId }) {
      // this.dialogVisible = true;
      this.packageLogLoading = true;
      listCouponByPackageId({ packageLogId }).then(res => {
        this.packageLogLoading = false;
        this.packageLogList = res.result || [];
      }).catch(() => {
        this.packageLogLoading = false;
      });
    },
    getTableList() {
      if(this.loading) {
        return;
      }
      this.loading = true;
      this.formatterTimeFunc('beginTime', 'endTime', 'yyyy-MM-dd', 'dateTime');
      let params = { ...this.listParams, memberCardId: this.currentAreaId };
      pagePackageLog(params).then(res => {
        this.loading = false;
        const data = res.result;
        this.tableList = data.result || [];
        this.total = data.totalCount;
        // 删除至最后一页没数据的情况，页码-1
        if (this.tableList.length === 0 && this.listParams.currentPage !== 1) {
          this.listParams.currentPage -= 1;
          this.getTableList();
        }
      }).finally(() => {
        this.loading = false;
      });
    }
  },
};
</script>
