<template>
  <div class="p20" v-loading="loading">
    <header>
      <el-select clas="w160" v-model="query.appCode" placeholder="所有应用来源" @change="handleSearch" clearable>
        <el-option v-for="item in appList" :key="item.appCode" :label="item.appName" :value="item.appCode"></el-option>
      </el-select>
      <el-select class="w160 ml10" placeholder="所有配货方式" v-model="query.deliveryType" @change="handleSearch" clearable>
        <el-option label="物流发货" :value="1"></el-option>
        <el-option label="门店自提" :value="2"></el-option>
        <el-option label="文本券码" :value="3"></el-option>
      </el-select>
      <el-select class="w160 ml10" placeholder="所有履约状态" v-model="query.orderFlag" @change="handleSearch" clearable>
        <el-option label="待履约" :value="0"></el-option>
        <el-option label="已履约" :value="1"></el-option>
        <el-option label="已关闭" :value="2"></el-option>
      </el-select>
      <el-input class="w360 ml10" placeholder="请输入关键词搜索" v-model="searchValue" clearable @keyup.enter.native="handleSearch" @change="handleSearch">
        <el-select v-model="searchType" slot="prepend" style="width:160px;" @change="handleSearchTypeChange">
          <el-option label="履约单号" value="orderId"></el-option>
          <el-option label="礼品名称" value="giftName"></el-option>
          <el-option label="礼品编码" value="giftNo"></el-option>
          <el-option label="sku编码" value="giftSkuCode"></el-option>
          <el-option label="会员姓名" value="memberName"></el-option>
          <el-option label="会员卡号" value="memberCardNo"></el-option>
        </el-select>
      </el-input>
      <div class="clearfix mt20" style="margin-top:20px">
        <el-date-picker class="w400 fl" v-model="daterange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="handleSearch"></el-date-picker>
        <el-button class="fr" icon="iconfont-welfare4 icon-xiazai mr5" type="primary" @click="exportConfig.exportVisible = true">导出</el-button>
      </div>
    </header>

    <el-table class="mt20" :data="list" @sort-change="handleSortChange">
      <el-table-column label="礼品信息" width="300">
        <template slot-scope="{ row }">
          <div class="goods-info">
            <img class="imgs-style" :src="row.giftImgUrl" alt="" />
            <div class="goods-text">
              <div class="goods-text-name">
                {{row.giftName}}
              </div>
              <div v-if="row.giftType == 1" class="goods-text-info">
                <div v-if="row.giftSkuStrand">
                  <span v-for="(item, i) in JSON.parse(row.giftSkuStrand || '[]')" :key="i">{{ item.specStandardName }}：{{ item.specStandardValueName }} &nbsp;&nbsp;</span>
                </div>
                <span v-else>- -</span>
                <div class="goods-sku">SKU编码：{{ row.giftSkuCode }}</div>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="exchangeQuantity"></el-table-column>
      <el-table-column label="创建时间" sortable>
        <template slot-scope="{ row }">
          <p>{{ row.createTime | formatDate }}</p>
          <p>{{ row.createTime | formatDate('time') }}</p>
        </template>
      </el-table-column>
      <el-table-column label="履约单号" width="200">
        <template slot-scope="{ row }">
          {{row.orderId}}
          <el-popover
            placement="bottom-end"
            width="300"
            trigger="hover">
            <i class="iconfont-welfare4 icon-gengduo2 more-detail" slot="reference"></i>
            <div>
              应用单号：{{row.businessId}}
            </div>
            <div v-if="row.orderFlag == 1 && row.giftType == 1" class="mt10">
              <span>发货单号：</span>
              <el-button type="text" @click="linkToDetail(row.deliveryOrderId)">{{row.deliveryOrderId}}</el-button>
            </div>
            <div v-if="row.orderFlag == 1 && row.giftType == 2" class="mt10" v-html="row.deliveryInfo">
              <!-- {{row.deliveryInfo}} -->
            </div>
            <div v-else-if="row.orderFlag == 0" class="mt10">
              <span style="display:flex">
                <span style="flex-shrink:0">备注：</span>
                <span>{{row.waitReason}}</span>
              </span>
            </div>
            <div v-else-if="row.orderFlag == 2" class="mt10">
              <span>关闭时间： {{row.updateTime | formatDate('dateTime')}}</span>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="会员信息">
        <template slot-scope="{ row }">
          <p>{{ row.memberName || '--' }}</p>
          <p>{{ row.memberCardNo || '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="来源">
        <template slot-scope="{ row }">
          <p>{{ row.appName || '--' }}</p>
          <p>{{ row.activityName || '--' }}</p>
        </template>
      </el-table-column>
      <el-table-column label="履约状态">
        <template slot-scope="{ row }">
          <span v-if="row.orderFlag == 0" class="state-point state-point-warning">待履约</span>
          <span v-else-if="row.orderFlag == 1" class="state-point state-point-success">已履约</span>
          <span v-else-if="row.orderFlag == 2" class="state-point state-point-default">已关闭</span>
        </template>
      </el-table-column>
    </el-table>

    <dm-pagination
      class="text-right"
      background
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pager.currentPage"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="pager.pageSize"
      :total="pager.totalCount">
    </dm-pagination>

    <dm-export-data ref="exportData" :visible.sync="exportConfig.exportVisible" :sens-value="true" :fields="exportConfig.fields" :label="exportConfig.label" :value="exportConfig.value" :sens-key="exportConfig.sensKey" @export="handleExport"></dm-export-data>
  </div>
</template>

<script>
import fetch from '@/api/performance.js';
const { getPerformanceList, exportPerformanceData, getApplicationList } = fetch;
import { dealExportParams } from '@/utils/common.js';

const fields = [
  { label: '福利ID', value: 'giftId', sensKey: false },
  { label: '配货方式', value: 'deliveryType', sensKey: false },
  { label: '礼品名称', value: 'giftName', sensKey: false },
  { label: '礼品编码', value: 'giftCode', sensKey: false },
  { label: 'SKU编码', value: 'giftSkuCode', sensKey: false },
  { label: 'SKU名称', value: 'giftSkuStandard', sensKey: false },
  { label: '数量', value: 'refundQuantity', sensKey: false },
  { label: '履约单号', value: 'orderId', sensKey: false },
  { label: '发货单号', value: 'deliveryId', sensKey: false },
  { label: '会员姓名', value: 'memberName', sensKey: true },
  { label: '会员手机号', value: 'memberPhone', sensKey: true },
  { label: '来源应用', value: 'appName', sensKey: false },
  { label: '来源活动', value: 'activityName', sensKey: false },
  { label: '发放文本内容', value: 'deliveryInfo', sensKey: false },
  { label: '创建时间', value: 'createTime', sensKey: false },
  { label: '关闭时间', value: 'updateTime', sensKey: false },
];

export default {
  name: 'PerformanceRecord',
  data() {
    return {
      loading: false,
      pager: { // 分页
        currentPage: 1,
        pageSize: 20,
        totalCount: 0,
      },
      list: [], // 表格数据
      searchType: 'orderId',
      searchValue: '',
      query: { // 查询参数
        deliveryType: '',
        appCode: '',
        startTime: '',
        endTime: '',
        orderFlag: ''
      },
      exportConfig: { // 导出组件配置
        exportVisible: false,
        fields,
        sensKey: 'sensKey',
        label: 'label',
        value: 'value'
      },
      appList: [],
    };
  },
  created() {
    this.$emit('updateBread', [
      {
        breadName: '福利中心'
      },
      {
        breadName: '履约管理'
      },
      {
        breadName: '履约记录'
      },
    ]);
    let now = Date.now();
    this.query.endTime = this.$options.filters['formatDate'](now) + ' 23:59:59';
    this.query.startTime = this.$options.filters['formatDate'](now - 30 * 24 * 60 * 60 * 1000) + ' 00:00:00';
    this.getApplicationList();
    this.getList();
  },
  methods: {
    async getList(sort = 'desc') {
      let query = {
        ...this.query,
        pageNum: this.pager.currentPage,
        pageSize: this.pager.pageSize,
        [this.searchType]: this.searchValue,
        deliveryFlag: this.type,
        sort
      };
      this.loading = true;
      let { result: { result, totalCount } } = await getPerformanceList(query).finally(() => this.loading = false);
      this.list = result || [];
      this.pager.totalCount = totalCount;
    },
    // 应用来源列表
    async getApplicationList() {
      const { result } = await getApplicationList();
      this.appList = result || [];
    },
    // 搜索
    handleSearch() {
      this.pager.currentPage = 1;
      this.getList();
    },
    // 改变每页显示数量
    handleSizeChange(pageSize) {
      this.pager.currentPage = 1;
      this.pager.pageSize = pageSize;
      this.getList();
    },
    // 换页
    handleCurrentChange(currentPage) {
      this.pager.currentPage = currentPage;
      this.getList();
    },
    handleExport(config) {
      let listParams = {
        ...this.query,
        [this.searchType]: this.searchValue,
      };
      const params = dealExportParams({ config, listParams, fieldList: this.exportConfig.fields, path: this.$route.path, pathName: '福利中心-履约管理-退货单' });
      exportPerformanceData(params).then(res => {
        this.$refs.exportData.applyReport(true, res.result);
      }).catch(err => {
        this.$refs.exportData.applyReport();
      });
    },
    linkToDetail(deliveryId) {
      // this.$router.push({ path: '/performance/delivery-detail', query: { deliveryId } });
      window.open(`/welfare/gift-performance/delivery-detail?deliveryId=${deliveryId}`);
    },
    handleSearchTypeChange() {
      this.searchValue = '';
      this.handleSearch();
    },
    handleSortChange({ column, prop, order }) {
      let map = {
        descending: 'desc',
        ascending: 'asc'
      };
      this.getList(map[order]);
    },
  },
  filters: {
    formatDate(ms, type = 'date') {
      if (!ms) return '--';
      const date = [];
      const time = [];
      ms = new Date(ms);
      date.push(ms.getFullYear());
      date.push((ms.getMonth() + 1).toString().padStart(2, '0'));
      date.push(ms.getDate().toString().padStart(2, '0'));

      time.push(ms.getHours().toString().padStart(2, '0'));
      time.push(ms.getMinutes().toString().padStart(2, '0'));
      time.push(ms.getSeconds().toString().padStart(2, '0'));

      return {
        date: date.join('-'),
        time: time.join(':'),
        dateTime: date.join('-') + ' ' + time.join(':')
      }[type];
    }
  },
  computed: {
    daterange: {
      get() {
        return [ this.query.startTime, this.query.endTime ];
      },
      set(v) {
        [ this.query.startTime, this.query.endTime ] = v || [ '', '' ];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
