<template>
  <div class="p20" v-loading="loading">
    <div class="pb20 clearfix flex-center">
      <el-input class="vertical-middle w250 mr10" v-model="listParams.search" clearable placeholder="请输入卡券代码/会员信息" @change="refresh"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <template>
        <el-tooltip :open-delay="300" content="查询全部卡券领取记录单次仅支持区间范围7天的查询，速度较慢，请耐心等候" placement="top">
          <i class="el-icon-info mr5 gray-lighter cursor"></i>
        </el-tooltip>
        <el-switch class="mr10 dm-switch" @change="changeAllCouponFlag" v-model="listParams.allCouponFlag" active-color="#2f54ed" inactive-color="#ff9900" active-text="单张卡券" inactive-text="全部卡券" :active-value="0" :inactive-value="1"></el-switch>
        <card-select-filter v-show="!listParams.allCouponFlag" v-if="currentAreaId" :member-card-id="currentAreaId" ref="cdf" :c-id.sync="listParams.couponId" class="w250 mr10" @cIdUpdate="refresh" :disabled="listParams.allCouponFlag" />
      </template>
      <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 class="table-search-head">
      <el-select class="w150 mr10" v-model="listParams.visitorFlag" @change="refresh">
        <el-option label="会员领取记录" :value="0"></el-option>
        <el-option label="非会员领取记录" :value="1"></el-option>
      </el-select>
      <el-select class="dm-select mr10 w140" clearable v-model="listParams.status" 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="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-date-picker class="w250 mr10" :clearable="false" v-model="dateTime" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" @change="changeTime"></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 tooltip-effect="dark" :data="tableList" style="width:100%" :max-height="mainHeight(54 + 50)" :empty-text="listParams.couponId || listParams.allCouponFlag ? '暂无数据' : '请选择单张卡券或开启全部卡券'">
      <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">
          <span p-key="couponId" :title="scope.row.couponId">{{ scope.row.cardName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="wxCardCode" label="卡券代码" min-width="120"> </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 prop="appName" label="发放来源" min-width="120"></el-table-column>
      <el-table-column prop="appActivityName" label="来源明细" min-width="120" show-overflow-tooltip></el-table-column>
      <el-table-column label="核销时间" min-width="120">
        <span slot-scope="scope" v-html="listTime(scope.row.verifyTime)"></span>
      </el-table-column>
      <el-table-column label="核销方式" min-width="120">
        <template slot-scope="scope">
          <!--  verifyType 0订单核销 1手动核销 -->
          {{ scope.row.status === 5 ? (scope.row.verifyType === 0 ? '订单核销' : '手动核销') : '--' }}
        </template>
      </el-table-column>
      <el-table-column label="核销渠道" min-width="120">
        <span slot-scope="scope" v-html="formatChannel(scope.row)"></span>
      </el-table-column>
      <el-table-column prop="verifyStoreName" label="核销门店" min-width="120"></el-table-column>
      <el-table-column prop="verifyOrderNumber" label="订单号" min-width="120" show-overflow-tooltip></el-table-column>


      <el-table-column label="操作" align="left" width="130px" fixed="right">
        <template slot-scope="scope" v-if="listParams.visitorFlag == 0">
          <el-button type="text" v-if="scope.row.status === 4 && Date.now() < scope.row.effectEndTime + 24 * 60 * 60 * 1000" @click="orderData(scope.row)">核销</el-button>
          <dm-delete @confirm="delData(scope.row)" v-if="scope.row.status === 4 && Date.now() < scope.row.effectEndTime + 24 * 60 * 60 * 1000" 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 cardSelectFilter from '@/components/card-select/filterable';
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 } 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, cardSelectFilter
  },
  mixins: [ page, formate, getMainHeight ],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      dateTime: [ Date.now() - 7 * 24 * 60 * 60 * 1000, Date.now() ], // 默认7天
      dateTimeCopy: [ Date.now() - 7 * 24 * 60 * 60 * 1000, Date.now() ],
      dateTime2: [ , ],
      listParams: {
        // appActivityId: this.$route.query.appActivityId || '',
        // appCode: this.$route.query.appCode || '',
        couponId: '', // 卡券id
        search: '',
        cardType: '',
        status: '',
        receiveBeginTime: '',
        receiveEndTime: '',
        verifyBeginTime: '',
        verifyEndTime: '',
        currentPage: 1,
        pageSize: 20,
        allCouponFlag: 1, // 1全部会员 // 默认开启全部，有展架id无切换
        visitorFlag: 0, // 0会员 1非会员
      },
      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'
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券日志' }, { breadName: '领取记录' } ]);
  },
  mounted() {
    if(this.currentAreaId) {
      if (this.$route.query.id) {
        this.listParams.couponId = this.$route.query.id;
        this.listParams.allCouponFlag = 0;
        this.$refs.cdf.getCardDetail(this.listParams.couponId);
      } else {
        this.$refs.cdf.getCardList();
        this.getTableList();
      }
    }
  },
  methods: {
    listTime,
    formatCardType(row) {
      return cardType[row.cardType] ? cardType[row.cardType].label : '--';
    },
    formatCardStatus(row) {
      // （3：已发放，4：已领取，5：已使用，6：已到期,7:已销毁, 8:已占用）
      const st = sendCardStatus[row.status];
      if(st) {
        return `<span class="state-point ${st.cl}">${st.label}</span>`;
      } else {
        return '<span class="state-point state-point-default">未知状态</span>';
      }
    },
    formatChannel(row) {
      // verifyOrderType 1线下订单 2gic微商城 3微盟微商城
      return row.status === 5 && row.verifyOrderType ? verifyOrderType[row.verifyOrderType].label : '--';
    },
    changeTime(date) {
      // 单张卡券可以设置领取n久  全部卡券范围不能超过7天
      if (this.listParams.allCouponFlag && 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();
    },
    changeAllCouponFlag(val) {
      if (val) {
        this.listParams.couponId = '';
        if (new Date(this.dateTime[1]).getTime() - new Date(this.dateTime[0]).getTime() > 7 * 24 * 60 * 60 * 1000) {
          // 设置为默认值
          this.dateTime = [ Date.now() - 7 * 24 * 60 * 60 * 1000, Date.now() ];
        }
      }
      this.refresh();
    },
    delData(row) {
      this.loading = true;
      couponDestroy({ couponLogId: row.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.loading) {
        return;
      }
      this.tableList = [];
      if (!this.listParams.couponId && !this.listParams.allCouponFlag) {
        this.recordList = [];
        return;
      }

      this.formatterTimeFunc('receiveBeginTime', 'receiveEndTime', 'yyyy-MM-dd', 'dateTime');
      this.formatterTimeFunc('verifyBeginTime', 'verifyEndTime', 'yyyy-MM-dd', 'dateTime2');
      let params = { ...this.listParams, memberCardId: this.currentAreaId };
      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>