<template>
  <div v-loading="loading">
    <header>
      <el-select class="w160" placeholder="所有应用来源" v-model="query.appCode" @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-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:140px;" @change="handleSearchTypeChange">
          <el-option label="商品名称" value="giftName"></el-option>
          <el-option label="礼品编码" value="giftCode"></el-option>
          <el-option label="sku编码" value="giftSkuCode"></el-option>
          <el-option label="发货单号" value="deliveryId"></el-option>
          <el-option label="收件人手机号" value="consigneePhone"></el-option>
          <el-option label="会员姓名" value="memberName"></el-option>
          <el-option label="会员卡号" value="memberCardNo"></el-option>
          <el-option label="履约单号" value="orderId"></el-option>
        </el-select>
      </el-input>
      <el-date-picker class="w400 ml10" v-model="daterange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="handleSearch"></el-date-picker>
      <div class="mt20">
        <el-button type="primary" @click="openDialog('BulkDelivery')">批量发货</el-button>
        <el-button icon="el-icon-download" @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 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>SKU编码：{{ row.giftSkuCode }}</div>
              </div>
            </div>
          </div>
        </template>
      </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="数量" prop="exchangeQuantity"></el-table-column>
      <el-table-column label="发货单号" width="250">
        <template slot-scope="{ row }">
          <el-button type="text" @click="linkToDetail(row)">{{row.deliveryId}}</el-button>
          <el-popover
            placement="bottom-end"
            width="300"
            trigger="hover">
            <i class="iconfont-welfare4 icon-gengduo2 ml5" slot="reference"></i>
            <div class="performance-order-info">
              <div><span>发货单来源：</span><span>{{row.appName}}</span></div>
              <div class="mt10"><span>履约单号：</span><span>{{row.orderId}}</span></div>
              <template v-if="row.deliveryType === 1 && row.deliveryFlag === 0">
                <div class="mt10"><span>收货信息：</span><span>{{row.consignee}} {{row.consigneePhone}} {{row.consigneeAddress}}</span></div>
              </template>
              <template v-else-if="row.deliveryType === 1 && row.deliveryFlag === 1">
                <div class="mt10"><span>完成时间：</span><span>{{row.deliveryTime | formatDate('dateTime')}}</span></div>
                <div class="mt10"><span>收货信息：</span><span>{{row.consignee}} {{row.consigneePhone}} {{row.consigneeAddress}}</span></div>
              </template>
              <template v-else-if="row.deliveryType === 2 && row.deliveryFlag === 0">
                <div class="mt10"><span>自提信息：</span><span>{{row.consignee}} {{row.consigneePhone}}</span></div>
                <div class="mt10"><span>自提时间：</span><span>{{row.pickUpStopTime | formatDate('dateTime')}}</span></div>
                <div class="mt10"><span>自提地址：</span><span>{{row.pickUpStartTime}} - {{row.pickUpStopTime}}</span></div>
              </template>
              <template v-else-if="row.deliveryType === 2 && row.deliveryFlag === 1">
                <div class="mt10"><span>自提信息：</span><span>{{row.consignee}} {{row.consigneePhone}}</span></div>
                <div class="mt10"><span>完成时间：</span><span>{{row.deliveryTime | formatDate('dateTime')}}</span></div>
                <div class="mt10"><span>核销门店：</span><span>{{row.pickUpPointName}}</span></div>
                <div class="mt10"><span>操作人：</span><span>{{row.pickUpPointName}}</span></div>
              </template>
              <template v-else-if="row.deliveryFlag === 2">
                <div class="mt10"><span>关闭时间：</span><span>{{row.cancelTime | formatDate('dateTime')}}</span></div>
                <div class="mt10"><span>关闭原因：</span><span>{{row.cancelReason}}</span></div>
              </template>
            </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="发货单状态" width="200">
        <template slot-scope="{ row }">
          <template v-if="row.deliveryType === 1 && row.deliveryFlag === 0">
            <span class="state-point state-point-warning">待发货</span>
            <p>
              <el-button type="text" @click="openDialog('LogisticsDelivery', row)">物流发货</el-button>
              <el-button type="text" @click="openDialog('CancelOrder', row)">关闭发货单</el-button>
            </p>
          </template>
          <template v-else-if="row.deliveryType === 1 && row.deliveryFlag === 1">
            <span class="state-point state-point-success">已发货</span>
            <p>
              <el-button type="text" @click="openDialog('LogisticsInfo', row)">查看物流</el-button>
              <el-button type="text" @click="linkToDetail(row)">查看详情</el-button>
            </p>
          </template>
          <template v-else-if="row.deliveryType === 2 && row.deliveryFlag === 0">
            <span class="state-point state-point-warning">待核销</span>
            <p>
              <el-button type="text" @click="openDialog('WriteOff', row)">自提核销</el-button>
              <el-button type="text" @click="openDialog('CancelOrder', row)">关闭发货单</el-button>
            </p>
          </template>
          <template v-else-if="row.deliveryType === 2 && row.deliveryFlag === 1">
            <span class="state-point state-point-success">已核销</span>
            <p>
              <el-button type="text" @click="linkToDetail(row)">查看详情</el-button>
            </p>
          </template>
          <template v-else-if="row.deliveryFlag === 2">
            <span class="state-point state-point-default">已关闭</span>
            <p>
              <el-button type="text" @click="linkToDetail(row)">查看详情</el-button>
            </p>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <dm-pagination
      background
      layout="total, sizes, prev, pager, next"
      style="text-align: right"
      @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>
    <component :is="activeDialog" :data="row" @close="activeDialog=''" @refresh="getList"></component>

    <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 { getDelivery, getApplicationList, exportDeliveryData } = fetch;
import BulkDelivery from './components/bulk-delivery-dialog';
import CancelOrder from './components/cancel-order-dialog';
import LogisticsDelivery from './components/logistics-delivery-dialog';
import LogisticsInfo from './components/logistics-info-dialog';
import WriteOff from './components/writeoff-dialog';

import { dealExportParams } from '@/utils/common.js';

const fields = [
  { label: '福利ID', value: 'giftId', 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: 'deliveryId', sensKey: false },
  { label: '退货单号', value: 'refundId', sensKey: false },
  { label: '会员姓名', value: 'memberName', sensKey: true },
  { label: '会员手机号', value: 'memberPhone', sensKey: true },
  { label: '来源应用', value: 'appName', sensKey: false },
  { label: '来源活动', value: 'activityName', sensKey: false },
  { label: '发货单号', value: 'deliveryOrderId', sensKey: false },
  { label: '发放文本内容', value: 'deliveryInfo', sensKey: false },
  { label: '创建时间', value: 'createTime', sensKey: false },
  { label: '关闭时间', value: 'updateTime', sensKey: false },
];

export default {
  name: 'DeliveryList',
  components: { BulkDelivery, CancelOrder, LogisticsDelivery, LogisticsInfo, WriteOff },
  props: {
    type: [ String, Number ],
  },
  data() {
    return {
      pager: {
        currentPage: 1,
        pageSize: 20,
        totalCount: 0,
      },
      list: [],
      appList: [],
      searchType: 'deliveryId',
      searchValue: '',
      query: {
        deliveryType: '',
        appCode: '',
        startTime: '',
        endTime: '',
      },
      activeDialog: '',
      row: {},
      exportConfig: {
        exportVisible: false,
        fields,
        sensKey: 'sensKey',
        label: 'label',
        value: 'value'
      },
      loading: false,
    };
  },
  created() {
    this.getApplicationList();
    let sort = 'desc';
    if(this.type === 0) {
      sort = 'asc';
    } else {
      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.getList(sort);
  },
  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 getDelivery(query).finally(() => this.loading = false);
      this.list = result || [];
      this.pager.totalCount = totalCount;
      if(this.type === 0) this.$emit('count', 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();
    },
    handleSortChange({ column, prop, order }) {
      let map = {
        descending: 'desc',
        ascending: 'asc'
      };
      this.getList(map[order]);
    },
    openDialog(dialogName, row) {
      this.row = row;
      this.activeDialog = dialogName;
    },
    linkToDetail(row) {
      this.$router.push({ path: '/performance/delivery-detail', query: { deliveryId: row.deliveryId } });
    },
    handleExport(config) {
      let listParams = {
        ...this.query,
        [this.searchType]: this.searchValue,
      };
      const params = dealExportParams({ config, listParams, fieldList: this.exportConfig.fields, path: this.$route.path, pathName: '福利中心-履约管理-退货单' });
      exportDeliveryData(params).then(res => {
        this.$refs.exportData.applyReport(true, res.result);
      }).catch(err => {
        this.$refs.exportData.applyReport();
      });
    },
    handleSearchTypeChange() {
      this.searchValue = '';
      this.handleSearch();
    },
  },
  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>
.goods-info {
  height: 100%;
  display: flex;
  img {
    width: 62px;
    height: 62px;
    border: 1px solid rgba(241, 243, 247, 1);
    border-radius: 5px;
  }
  .goods-text {
    margin-left: 18px;
    font-size: 13px;
    color: #303133;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  .goods-text-info {
    color: #909399;
    font-size: 12px;
  }
  .goods-text-name {
    margin-bottom: 5px;
    line-height: 16px;
  }
}
</style>
