<template>
  <div class="p20" 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.refundFlag" @change="handleChangeRefundFlag" clearable>
        <el-option v-for="(value, key) in refundFlagMap" :key="key" :label="value" :value="parseInt(key)"></el-option>
        <!-- <el-option label="待处理" :value="0"></el-option>
        <el-option label="同意退货" :value="1"></el-option>
        <el-option label="拒绝退货" :value="2"></el-option>
        <el-option label="已关闭" :value="3"></el-option> -->
      </el-select>
      <el-input class="w360 ml10" placeholder="请输入关键词搜索" v-model="searchValue" clearable @keyup.enter.native="handleSearch" @change="handleSearch">
        <el-select class="w160" v-model="searchType" slot="prepend" @change="handleSearchTypeChange">
          <el-option label="退货单号" value="refundId"></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="memberPhone"></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="refundLogisticsNo"></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" 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.giftImageUrl" alt="" />
            <div class="goods-text">
              <div class="goods-text-name">
                {{row.giftName}}
              </div>
              <div class="goods-text-info">
                <div v-if="row.giftSkuStandard">
                  <span v-for="(item, i) in JSON.parse(row.giftSkuStandard || '[]')" :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="refundQuantity"></el-table-column>
      <el-table-column label="退货单号" width="200">
        <template slot-scope="{ row }">
          {{row.refundId}}
          <el-popover
            placement="bottom-end"
            width="300"
            trigger="hover">
            <i class="iconfont-welfare4 icon-gengduo2" 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.refundFlag === 0 && !row.refundLogisticsNo">
                <div class="mt10"><span>退货原因：</span><span>{{row.refundReason}}</span></div>
                <div class="mt10"><span>退货说明：</span><span>{{row.refundRemark}}</span></div>
              </template>
              <template v-else-if="row.refundFlag === 0 && row.refundLogisticsNo">
                <div class="mt10"><span>寄回时间：</span><span>{{row.deliveryTime | formatDate('dateTime')}}</span></div>
                <div class="mt10"><span>退货原因：</span><span>{{row.refundReason}}</span></div>
                <div class="mt10"><span>退货说明：</span><span>{{row.refundRemark}}</span></div>
              </template>
              <template v-else-if="row.refundFlag === 1">
                <div class="mt10"><span>操作人：</span><span>{{row.refundUserName}}</span></div>
                <div class="mt10"><span>操作时间：</span><span>{{row.processTime | formatDate('dateTime')}}</span></div>
                <div class="mt10"><span>退货原因：</span><span>{{row.refundReason}}</span></div>
                <div class="mt10"><span>退货说明：</span><span>{{row.refundRemark}}</span></div>
              </template>
              <template v-else-if="row.refundFlag === 2">
                <div class="mt10"><span>操作人：</span><span>{{row.refundUserName}}</span></div>
                <div class="mt10"><span>操作时间：</span><span>{{row.processTime | formatDate('dateTime')}}</span></div>
                <div class="mt10"><span>拒绝原因：</span><span>{{row.refuseReason}}</span></div>
                <div class="mt10"><span>退货原因：</span><span>{{row.refundReason}}</span></div>
                <div class="mt10"><span>退货说明：</span><span>{{row.refundRemark}}</span></div>
              </template>
              <template v-else-if="row.refundFlag === 3">
                <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="寄回状态">
        <template slot-scope="{ row }">
          <template v-if="row.refundLogisticsNo">
            <div class="state-point state-point-success">已寄回</div>
            <div>
              <el-button type="text" @click="openDialog('logisticsDialog', row)">查看物流</el-button>
            </div>
          </template>
          <template v-else>
            <span class="state-point state-point-warning">待寄回</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="{ row }">
          <template v-if="row.refundFlag == 0 && row.refundLogisticsNo">
            <div>
              <dm-delete @confirm="handleReceive(row, 1)" tips="确认同意收货？">
                <el-button type="text">同意收货</el-button>
              </dm-delete>
              <el-button type="text" @click="openDialog('refuseDialog', row)">拒绝收货</el-button>
            </div>
          </template>
          <template v-if="row.refundFlag != 0 && row.refundLogisticsNo">
            <span>{{ refundStatus[row.refundFlag] }}</span>
          </template>
        </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>

    <!-- 拒绝收货弹窗 -->
    <el-dialog :visible.sync="refuseDialog.visible" title="拒绝收货" width="500px" @close="$refs.refuseForm.resetFields()">
      <el-form :model="refuseDialog.form" :rules="refuseDialog.rules" ref="refuseForm" label-width="100px">
        <el-form-item label="原因备注" prop="reason">
          <dm-input type="textarea" :maxlength="240" :rows="5" show-word-limit v-model="refuseDialog.form.reason"></dm-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="refuseDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleReceive(row, 0)">确认</el-button>
      </div>
    </el-dialog>

    <!-- 查看物流弹窗 -->
    <el-dialog title="物流详情" :visible.sync="logisticsDialog.visible" width="800px">
      <div class="logistics-info">
        <div>
          <span class="key">快递公司：</span>
          <span>{{ logisticsDialog.logisticsCompanyName || '--' }}</span>
        </div>
        <div>
          <span class="key">快递单号：</span>
          <span>{{ logisticsDialog.logisticCode || '--' }}</span>
          <el-button class="ml15" type="text" v-clipboard:copy="logisticsDialog.logisticCode" v-clipboard:success="onCopy" v-clipboard:error="onError">复制</el-button>
        </div>
      </div>
      <div v-if="logisticsDialog.logisticsList.length>0" class="logistics-step">
        <h3>派送中</h3>
        <el-timeline class="hollow logistics-list">
          <el-timeline-item
            v-for="(activity, index) in logisticsDialog.logisticsList"
            :key="index"
            :color="index===0?'':'#c0c4cc'">
            <div class="logistics-line-step">
              <span class="time">{{ activity.acceptTime || '--' }}</span>
              <p class="content">{{ activity.acceptStation }}</p>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <div v-else class="empty_block"></div>
    </el-dialog>
  </div>
</template>

<script>
import fetch from '@/api/performance.js';
const { getRefund, getApplicationList, exportRefundData, handleRefundOrder, getLogisticsInfo } = fetch;
import { dealExportParams } from '@/utils/common.js';

const refundFlagMap = {
  0: '待处理',
  1: '同意退货',
  2: '拒绝退货',
  3: '已关闭',
};
const refundStatus = {
  1: '已同意',
  2: '已拒绝',
  3: '已关闭',
};

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: 'createTime', sensKey: false },
  { label: '发货时间', value: 'deliveryTime', sensKey: false },
  { label: '履约单号', value: 'orderId', sensKey: false },
  { label: '发货单号', value: 'deliveryId', sensKey: false },
  { label: '退货单号', value: 'refundId', sensKey: false },
  { label: '退货处理状态', value: 'refundFlag', sensKey: false },
  { label: '会员姓名', value: 'memberName', sensKey: true },
  { label: '会员手机号', value: 'memberPhone', sensKey: true },
  { label: '来源应用', value: 'appName', sensKey: false },
  { label: '来源活动', value: 'activityName', sensKey: false },
  { label: '退货物流公司', value: 'refundCompanyName', sensKey: false },
  { label: '退货物流单号', value: 'refundLogisticsNo', sensKey: false },
  { label: '退货原因', value: 'refundReason', sensKey: false },
  { label: '拒绝原因', value: 'cancelReason', sensKey: false },
];

export default {
  name: 'DeliveryList',
  props: {
    type: [ String, Number ],
  },
  data() {
    return {
      loading: false,
      pager: { // 分页
        currentPage: 1,
        pageSize: 20,
        totalCount: 0,
      },
      refundFlagMap,
      refundStatus,
      list: [],
      appList: [],
      searchType: 'refundId',
      searchValue: '',
      query: {
        refundFlag: '',
        appCode: '',
        startTime: '',
        endTime: '',
      },
      row: {}, // 当前操作行数据
      exportConfig: { // 导出组件配置
        exportVisible: false,
        fields,
        sensKey: 'sensKey',
        label: 'label',
        value: 'value'
      },
      refuseDialog: { // 拒绝收货弹窗
        visible: false,
        form: {
          reason: '',
        },
        rules: {
          reason: [ { required: true, message: '请填写原因备注', trigger: 'blur' } ]
        }
      },
      logisticsDialog: { // 物流信息弹窗
        visible: false,
        logisticsList: [],
      },
    };
  },
  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.handleChangeRefundFlag();
  },
  methods: {
    async getList(sort = 'desc') {
      this.loading = true;
      let query = {
        ...this.query,
        pageNum: this.pager.currentPage,
        pageSize: this.pager.pageSize,
        [this.searchType]: this.searchValue,
        sort
      };
      let { result: { result, totalCount } } = await getRefund(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();
    },
    handleSortChange({ column, prop, order }) {
      let map = {
        descending: 'desc',
        ascending: 'asc'
      };
      this.getList(map[order]);
    },
    async openDialog(dialogName, row) {
      this[dialogName].visible = true;
      this.row = row;
      if(dialogName == 'logisticsDialog') {
        let { result } = await getLogisticsInfo({
          companyCode: row.refundId/* 'YD' */,
          logisticsNo: row.refundLogisticsNo/* '4312317986451' */,
        });
        this.logisticsDialog.logisticsList = result.traces || [];
        this.logisticsDialog.logisticsList.reverse();
        this.logisticsDialog.logisticsCompanyName = result.logisticsCompanyName;
        this.logisticsDialog.logisticCode = result.logisticCode;
      }
    },
    handleExport(config) {
      let listParams = {
        ...this.query,
        [this.searchType]: this.searchValue,
      };
      const params = dealExportParams({ config, listParams, fieldList: this.exportConfig.fields, path: this.$route.path, pathName: '福利中心-履约管理-退货单' });
      exportRefundData(params).then(res => {
        this.$refs.exportData.applyReport(true, res.result);
      }).catch(err => {
        this.$refs.exportData.applyReport();
      });
    },
    // 处理退货
    handleReceive(row, isAgree) { // true: 同意退货 false: 拒绝退货
      let params = {
        refundId: row.refundId,
        processFlag: isAgree,
        refuseReason: ''
      };
      if(!isAgree) {
        params.refuseReason = this.refuseDialog.form.reason;
        this.$refs.refuseForm.validate( async(valid) => {
          if(valid) {
            await handleRefundOrder(params);
            this.refuseDialog.visible = false;
            this.getList();
            this.$message('操作成功');
          }
        });
      } else {
        handleRefundOrder(params).then(()=>{
          this.getList();
          this.$message('操作成功');
        });
      }
    },
    handleChangeRefundFlag() {
      let sort;
      if(this.query.refundFlag === 0) {
        sort = 'asc';
      } else {
        sort = 'desc';
      }
      this.pager.currentPage = 1;
      this.getList(sort);
    },
    onCopy(e) {
      this.$message.success('复制成功');
    },
    onError(e) {
      this.$message.error('复制失败');
    },
    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) {
        console.log(v);
        [ this.query.startTime, this.query.endTime ] = v || [ '', '' ];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.empty_block::after {
  content: '暂无物流信息';
}
.logistics-info {
  display: flex;
  &>div {
    flex: 1;
  }
  span {
    display: inline-block;
  }
  span + span {
    margin-left: 10px;
  }
}
.logistics-step {
  margin-top: 24px;
  background: #fafafa;
  padding: 15px 0px;
  h3 {
    color: #303133;
    font-size: 16px;
    border-bottom: 1px solid #dcdfe6;
    padding: 0 20px 15px 20px;
  };
  .logistics-list {
    height: 328px;
    overflow-y: auto;
    padding: 20px
  };
  .logistics-item {
    position: relative;
    padding-bottom: 10px;
  }
  .logistics-line-step {
    display: flex;
    font-size: 12px;
  }
  .logistics-line-step .time {
    margin-right: 20px;
    width: 160px;
    line-height: 22px;
    font-weight: 500;
    color: #303133;
  }
  .logistics-line-step .content {
    color: #303133;
    flex: 1;
    line-height: 22px;
  }
}
</style>
