<template>
  <div class="p20" v-loading="loading">
    <div class="pb20 clearfix flex-center">
      <!-- <el-select class="dm-select mr10 w140" clearable v-model="listParams.cardType" placeholder="所有卡券类型" @change="refresh">
        <el-option v-for="(v, i) in cardType" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select> -->
      <el-select class="dm-select mr10 w140" clearable v-model="listParams.statusFlag" placeholder="所有使用状态" @change="refresh">
        <el-option v-for="(v, i) in status" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-select class="mr10" style="width:170px" v-model="listParams.memberType" @change="refresh" placeholder="所有用户领取记录" clearable>
        <el-option label="会员领取记录" :value="1"></el-option>
        <el-option label="非会员领取记录" :value="2"></el-option>
      </el-select>
      <el-input placeholder="请输入关键字" class="mr10 w400" v-model="searchValue" clearable @change="refresh">
        <el-select v-model="searchType" slot="prepend" style="width:120px;" placeholder="请选择" @change="refresh">
          <!-- <el-option label="卡券名称" value="cardName"></el-option>
          <el-option label="备注名" value="remarkName"></el-option>
          <el-option label="副标题" value="subTitle"></el-option> -->
          <el-option label="会员昵称" value="memberName"></el-option>
          <el-option label="会员手机号" value="memberPhone"></el-option>
          <el-option label="会员卡号" value="memberCardNo"></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> -->
      <dm-perm-button class="mlAuto" :disabled="$itemPerm($itemCode.gicCardMemberGetExport)" type="primary" icon="iconfont-market4 mr5 icon-icon_yunxiazai" @click="showExport">数据导出</dm-perm-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="w250" style="margin-right:60px" v-model="dateTime" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" @change="changeTime" :clearable="false"></el-date-picker>
      核销时间：<el-date-picker class="w250" v-model="dateTime2" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" @change="refresh"></el-date-picker>
    <!-- </div> -->
    <el-table class="mt20" tooltip-effect="dark" :data="tableList" style="width:100%" :max-height="mainHeight(54 + 50)">
      <el-table-column label="领取时间" min-width="120" fixed="left">
        <span slot-scope="scope" v-html="listTime(scope.row.receiveTime)"></span>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="memberName" label="会员信息" min-width="180">
        <template slot-scope="{row}">
          <member-info :member-name="row.memberName" :member-image="row.memberImage" :member-phone="row.memberPhone"></member-info>
        </template>
      </el-table-column>
      <el-table-column label="卡券类型" min-width="120">
        <div slot-scope="scope" v-html="formatCardType(scope.row)"></div>
      </el-table-column>
      <el-table-column label="卡券信息" min-width="140" show-overflow-tooltip>
        <template slot-scope="scope">
          <p p-key="couponId" :title="scope.row.couponId">{{ scope.row.cardName }}</p>
          <p class="fz12">{{ scope.row.couponCode }}</p>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" min-width="120" show-overflow-tooltip>
        <div slot-scope="scope" v-html="formatCardStatus(scope.row)"></div>
      </el-table-column>
      <el-table-column label="订单号" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <p>
            {{ scope.row.verifyOrderNo }}
            <el-popover v-if="[5, 7].includes(scope.row.statusFlag)" placement="bottom" width="200" trigger="hover">
              <ul>
                <template v-if="scope.row.statusFlag  == 5">
                  <li>核销时间：{{ formatDateTimeByType(scope.row.verifyTime, 'yyyy-MM-dd') }}</li>
                  <li>核销方式：{{ scope.row.verifyType == 1 ? '手动核销' : '订单核销' }}</li>
                  <li>核销渠道：{{ formatChannel(scope.row) }}</li>
                  <li>核销门店/店铺：{{ scope.row.verifyStoreCode || '--' }}/{{ scope.row.verifyStoreName || '--' }}</li>
                </template>
                <li v-if="scope.row.statusFlag  == 7">销毁时间：{{ formatDateTimeByType(scope.row.destroyTime) }}</li>
              </ul>
              <i class="el-icon-more cursor" slot="reference"></i>
            </el-popover>
          </p>
        </template>
      </el-table-column>
      <el-table-column label="来源明细" min-width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <p class="fz14">{{ scope.row.appName }}</p>
          <p class="fz10">{{scope.row.activityName}}</p>
          <!-- <div v-html="formatChannel(scope.row)"></div> -->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="130px" fixed="right">
        <template slot-scope="scope" v-if="listParams.memberType == 0">
          <el-button type="text" v-if="scope.row.statusFlag  == 4 && edit == 1" @click="orderData(scope.row)">手动核销</el-button>
          <dm-delete @confirm="delData(scope.row)" v-if="scope.row.statusFlag === 4 && edit == 1" width="280" tips="销毁后无法恢复，确认销毁?">
            <el-button type="text">销毁</el-button>
          </dm-delete>
        </template>
        <span v-else>-</span>
      </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>
    <card-order :show.sync="cardOrderShow" :obj="currentObj" @refresh="getTableList" is-gic></card-order><!-- 核销组件dialog -->
    <dm-export-data ref="exportData" :visible.sync="exportVisible" :sens-value="true" :fields="fields" :label="label" :value="value" :sens-key="sensKey" :loading="loading" :is-created="isCreated" @export="onExport" @closed="isCreated = false"></dm-export-data>
  </div>
</template>

<script>
import cardOrder from './module/card-order';
import { page, formate, getMainHeight } from '@/mixins/table.js';
import { cardType, sendCardStatus, verifyOrderType } from '@/config/mapping/gic-card';
import { dealExportParams } from '@/utils/common.js';
import { listTime, formatDateTimeByType } from '@/utils/index.js';
import fetch from '@/api/gic-card.js';
const { couponlogList, exportCoupReceivedLog, couponDestroy } = fetch;
const _statusList = Object.keys(sendCardStatus).map(v => {
  return sendCardStatus[v];
}).filter(v => {
  return v.value !== 3; // 不要待领取
});

export default {
  name: 'MemberGet',
  components: {
    cardOrder
  },
  mixins: [ page, formate, getMainHeight ],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      dateTime: [ Date.now(), Date.now() ], // 默认当天
      dateTimeCopy: [ Date.now(), Date.now() ],
      dateTime2: [ , ],
      edit: this.$route.query.edit,
      listParams: {
        couponId: this.$route.query.id, // 卡券id
        // search: '',
        // searchType: 1,
        cardType: '',
        statusFlag: '',
        receiveBeginTime: '',
        receiveEndTime: '',
        verifyBeginTime: '',
        verifyEndTime: '',
        currentPage: 1,
        pageSize: 20,
        memberType: '', // 0会员 1非会员
      },
      searchValue: '',
      searchType: 'memberName',
      cardType: Object.keys(cardType).map(v => { return cardType[v]; }),
      status: _statusList,
      cardOrderShow: false,
      currentObj: {},
      tableList: [],
      total: 0,
      // 导出组件
      exportVisible: false,
      isCreated: false,
      // eslint-disable-next-line
      fields: [{label:'领取时间',value:'receiveTimeRemark',sensKey:false},{label:'会员头像', value: 'memberImage', sensKey: false},{label:'会员名称',value:'memberName',sensKey:false},{label:'会员手机号',value:'memberPhone',sensKey:true},{label:'卡券类型',value:'cardTypeRemark',sensKey:false},{label:'卡券名称',value:'cardName',sensKey:false},{label:'卡券代码',value:'wxCardCode',sensKey:false},{label:'卡券状态',value:'statusRemark',sensKey:false},{label:'发放来源',value:'appName',sensKey:false},{label:'来源明细',value:'appActivityName',sensKey:false},{label:'核销时间',value:'verifyTimeRemark',sensKey:false},{label:'核销方式',value:'verifyTypeRemark',sensKey:false},{label:'核销渠道',value:'verifyOrderType',sensKey:false},{label:'核销门店',value:'verifyStoreName',sensKey:false},{label:'订单号',value:'verifyOrderNumber',sensKey:false}],
      sensKey: 'sensKey',
      label: 'label',
      value: 'value',
      isOpen: false
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '卡券列表', breadPath: '/gic-card/list'  }, { breadName: '卡券领取记录' } ]);
  },
  mounted() {
    if(this.currentAreaId) {
      this.getTableList();
    }
  },
  methods: {
    listTime,
    formatDateTimeByType,
    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();
    },
    formatCardType(row) {
      return cardType[row.cardType] ? cardType[row.cardType].label : '--';
    },
    formatCardStatus(row) {
      // （3：已发放，4：已领取，5：已使用，6：已到期,7:已销毁, 8:已占用, 9:转赠中, 10: 已转赠）
      const st = sendCardStatus[row.statusFlag];
      if(st) {
        return `<span class="state-point ${st.cl}">${st.label}</span>`;
      } else {
        return '<span class="state-point state-point-default">未知状态</span>';
      }
    },
    formatChannel({ verifyType }) {
      // verifyType  核销方式(0:订单核销; 1:手动核销)
      // verifyOrderChannel  核销渠道(1:线下门店;2:达摩微商城;3:微盟微商城)
      return `${ verifyType ? verifyOrderType[verifyType].label : '--' }`;
    },
    delData({ couponLogId }) {
      this.loading = true;
      couponDestroy({ couponLogId: couponLogId })
        .then(res => {
          this.loading = false;
          this.$tips({ type: 'success', message: '销毁成功!' });
          this.getTableList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 核销弹窗
    orderData(row) {
      this.cardOrderShow = true;
      this.currentObj = row;
    },
    getTableList() {
      if(!this.$route.query.id) { // 必须要有卡券id
        return;
      }
      if(this.loading) {
        return;
      }
      this.tableList = [];

      this.formatterTimeFunc('receiveBeginTime', 'receiveEndTime', 'yyyy-MM-dd', 'dateTime');
      this.formatterTimeFunc('verifyBeginTime', 'verifyEndTime', 'yyyy-MM-dd', 'dateTime2');
      let params = { ...this.listParams, memberCardId: this.currentAreaId, [this.searchType]: this.searchValue };
      this.loading = true;
      couponlogList(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;
      });
    },
    // ********数据导出*************
    showExport() {
      if(!this.tableList.length) {
        this.$tips({ message: '没有要导出的数据', type: 'warning' });
        return;
      }
      this.exportVisible = true;
    },
    onExport(config) {
      let params = dealExportParams({ config, listParams: this.listParams, fieldList: this.fields, path: this.$route.path, pathName: 'GIC卡券-会员领取记录', query: { areaId: this.currentAreaId } });
      // 将config转换为请求参数
      // const params = config;
      // 导出数据完成后，必须调导出组件的applyReport方法
      // applyReport方法的第一个参数表示是否生成导出数据，第二个参数为导出数据的id
      exportCoupReceivedLog(params).then(res => {
        this.$refs.exportData.applyReport(true, res.result);
      }).catch(err => {
        this.$refs.exportData.applyReport();
      });
    }
  },
};
</script>

<style scoped lang="scss">
.dm-switch /deep/ {
  .el-switch__label {
    color: $gray02;
    &.is-active {
      color: $gray01;
    }
  }
}
</style>
