<template>
  <div style="padding: 20px">
    <header>
      <el-select style="width:160px" 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 style="width:160px;margin-left:10px" 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 style="width:360px;margin-left:10px" placeholder="请输入关键词搜索" v-model="searchValue" clearable @keyup.enter.native="handleSearch" @change="handleSearch">
        <el-select v-model="searchType" slot="prepend" style="width:140px;">
          <el-option label="退货单号" value="456"></el-option>
          <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-option label="退货物流号" value="123456"></el-option>
        </el-select>
      </el-input>
      <el-date-picker class="w400" style="margin-left: 10px" v-model="daterange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="handleSearch"></el-date-picker>
      <div style="margin-top:20px">
        <el-button icon="el-icon-download" @click="handleExport">导出</el-button>
      </div>
    </header>

    <el-table style="margin-top:20px" :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>
                  <span v-for="(item, i) in JSON.parse(row.giftSkuStrand)" :key="i">{{ item.specStandardName }}：{{ item.specStandardValueName }} &nbsp;&nbsp;</span>
                </div>
                <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">{{row.deliveryId}}</el-button>
          <el-popover
            placement="bottom-end"
            width="300"
            trigger="hover">
            <i class="el-icon-info-outline" slot="reference"></i>
            <div>发货单来源：{{row.appName}}</div>
            <div>履约单号：{{row.orderId}}</div>
            <template v-if="row.deliveryType === 1 && row.deliveryFlag === 0">
              <div>收货信息：{{row.consignee}} {{row.consigneePhone}} {{row.consigneeAddress}}</div>
            </template>
            <template v-else-if="row.deliveryType === 1 && row.deliveryFlag === 1">
              <div>完成时间：{{row.deliveryTime | formatDate}}</div>
              <div>收货信息：{{row.consignee}} {{row.consigneePhone}} {{row.consigneeAddress}}</div>
            </template>
            <template v-else-if="row.deliveryType === 2 && row.deliveryFlag === 0">
              <div>自提信息：{{row.consignee}} {{row.consigneePhone}}</div>
              <div>自提时间：{{row.pickUpStopTime | formatDate}}</div>
              <div>自提地址：{{row.pickUpStartTime}} - {{row.pickUpStopTime}}</div>
            </template>
            <template v-else-if="row.deliveryType === 2 && row.deliveryFlag === 1">
              <div>自提信息：{{row.consignee}} {{row.consigneePhone}}</div>
              <div>完成时间：{{row.deliveryTime | formatDate}}</div>
              <div>核销门店：{{row.pickUpPointName}}</div>
              <div>操作人：{{row.pickUpPointName}}</div>
            </template>
            <template v-else-if="row.deliveryFlag === 2">
              <div>关闭时间：{{row.cancelTime | formatDate}}</div>
              <div>关闭原因：{{row.cancelReason}}</div>
            </template>
          </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 }">
          <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="handleWiped(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">查看详情</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">查看详情</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=''"></component>
  </div>
</template>

<script>
import fetch from '@/api/performance.js';
const { getDelivery, getApplicationList } = 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';

export default {
  name: 'DeliveryList',
  components: { BulkDelivery, CancelOrder, LogisticsDelivery, LogisticsInfo },
  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: null,
    };
  },
  created() {
    console.log(this);
    this.getApplicationList();
    let sort = 'desc';
    if(this.type === 0) {
      sort = 'asc';
    } else {
      let now = Date.now();
      this.query.endTime = this.$options.filters['formatDate'](now);
      this.query.startTime = this.$options.filters['formatDate'](now - 30 * 24 * 60 * 60 * 1000);
    }
    this.getList(sort);
  },
  methods: {
    handleWiped() {
      this.$alert('自提核销', '请确认买家出示的提货码<div>{{123123}}</div>确认无误后，将商品交付给买家，确认核销后发货单完成', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确认',
        showClose: false,
      });
    },
    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.totalCount = totalCount;
      if(this.type === 0) this.$emit('count', this.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;
    },
    handleExport() {
      console.log('导出');
    },
  },
  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(':')
      }[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>
