<template>
  <div v-loading="loadings">
    <div class="search-bar">
      <el-input v-model="params.orderNumber" @change="onSearch" prefix-icon="el-icon-search" clearable placeholder="请输入订单/退款/退换单号" style="width: 260px"></el-input>
      <el-select v-model="params.orderType" @change="onSearch" clearable placeholder="全部订单类型" style="margin-left: 10px;width: 160px">
        <el-option :label="params.channelType == 3 ? '销售单' : '购买单'" value="1"></el-option>
        <el-option label="退款单" value="2"></el-option>
        <el-option label="退换货单" value="4"></el-option>
      </el-select>
      <span class="search-create-time">创建时间</span>
      <el-date-picker
        v-model="params.dateRange"
        @change="onSearch"
        clearable
        value-format="yyyy-MM-dd"
        type="daterange"
        range-separator="~"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="margin-left: 10px">
      </el-date-picker>
    </div>
    <!-- 展示表头 -->
    <el-table class="table-header">
      <el-table-column label="商品信息" min-width="350px"></el-table-column>
      <el-table-column label="吊牌价/应收(元)" min-width="130px"></el-table-column>
      <el-table-column label="数量" min-width="70px"></el-table-column>
      <el-table-column label="小计金额(元)" min-width="120px"></el-table-column>
      <el-table-column label="订单金额(元)" min-width="210px"></el-table-column>
      <el-table-column label="收货/导购信息" min-width="244px"></el-table-column>
    </el-table>
    <!-- 无数据时列表展示 -->
    <el-table v-if="tableData.length == 0" :show-header="false">
      <el-table-column label="商品信息" min-width="350px"></el-table-column>
      <el-table-column label="吊牌价/应收(元)" min-width="130px"></el-table-column>
      <el-table-column label="数量" min-width="70px"></el-table-column>
      <el-table-column label="小计金额(元)" min-width="120px"></el-table-column>
      <el-table-column label="订单金额(元)" min-width="210px"></el-table-column>
      <el-table-column label="收货/导购信息" min-width="244px"></el-table-column>
    </el-table>
    <div :style="{maxHeight: maxHeight}" style="overflow-y:scroll">
      <!-- 有数据时列表展示 -->
      <div class="order-list" v-for="el in tableData" :key="el">
        <!-- 订单号、订单时间、门店等信息 -->
        <el-table class="order-info-box" :data="[{}]" :span-method="orderInfoSpan" :show-header="false">
          <el-table-column label="商品信息" min-width="350px" >
            <div class="order-info">
              <!-- orderType	订单类型 -1 所有，1 销售，2.退货，4.退换货 -->
              <!-- 购买单、销售单为绿色背景 order-buy -->
              <!-- 退款单背景色为红色 order-refund -->
              <!-- 退换单背景色为黄色 order-exchange -->
              <!-- 线下订单orderType=1时为销售单 -->
              <div v-if="el.orderType == 1" class="order-type-tag order-buy">{{ el.channelType == 3 ? '销售单' : '购买单' }}</div>
              <div v-if="el.orderType == 2" class="order-type-tag order-refund">退款单</div>
              <div v-if="el.orderType == 4" class="order-type-tag order-exchange">退换单</div>
              <!-- 购买单、销售单为订单号 -->
              <!-- 退款单为退款单号 -->
              <!-- 退换单为退换单号 -->
              <div class="order-num-box">
                <div v-if="el.orderType == 4" class="order-num">退换单号：{{ el.orderNumber }}</div>
                <div v-else-if="el.orderType == 2" class="order-num">退款单号：{{ el.orderNumber }}</div>
                <div v-else class="order-num">订单号：{{ el.orderNumber }}</div>
                <!-- 退款单、退换单才有原始单号 -->
                <div class="connect-order-num">{{ el.orderType == 2 || el.orderType == 4 ? `原始订单号：${ el.oorderNumber }` : ''}}</div>
              </div>
            </div>
          </el-table-column>
          <el-table-column label="吊牌价/应收(元)" min-width="130px">abc</el-table-column>
          <el-table-column label="数量" min-width="70px">
            <div class="order-time-info">
              <div class="time-info-box">
                <div class="order-create-time">创建时间：{{ el.orderCreateTime | formatTime }}</div>
                <div class="order-sync-time">订单同步时间：{{ el.createTime | formatTime }}</div>
              </div>
              <div class="store-info">
                <!-- 天猫、微盟、抖音、门店 -->
                <div v-if="formatChannelType(el.channelType)" class="store-type-tag">{{ formatChannelType(el.channelType) }}</div>
                <div class="store-name">
                  {{ el.storeName }}
                  <br />
                  <template v-if="el.channelType == 3">{{ el.storeCode }}</template>
                </div>
              </div>
            </div>
          </el-table-column>
          <el-table-column label="小计金额(元)" min-width="120px">abc</el-table-column>
          <el-table-column label="订单金额(元)" min-width="210px">abc</el-table-column>
          <el-table-column label="收货/导购信息" min-width="244px">abc</el-table-column>
        </el-table>
        <!-- 订单商品、价格等信息 -->
        <el-table :data="el.orderItems" :show-header="false" :span-method="({ rowIndex, columnIndex }) => goodsInfoSpan(el, rowIndex, columnIndex)" class="order-detail">
          <el-table-column label="商品信息" min-width="350px" show-overflow-tooltip>
            <div class="goods-info-box" slot-scope="{ row }">
              <div class="goods-logo">
                <!-- <img class="goods-logo-icon" :src="row.imageUrl ? row.imageUrl : defaultGoodsIcon" alt=""> -->
                <el-image class="goods-logo-icon" :src="row.imageUrl ? row.imageUrl : defaultGoodsIcon" alt="">
                  <div slot="error" class="image-slot">
                    <!-- <i class="iconfont-components3 icon-cp-pic-error errorimage"></i> -->
                    <svg aria-hidden="true" width="60px" height="60px" style="border-radius:4px;">
                      <use xlink:href="#icon-cp-pic-error"></use>
                    </svg>
                  </div>
                </el-image>
                <!-- productType	商品类型 1正常 2赠品 3换购 -->
                <div v-if="row.productType == 2" class="goods-type-icon gift">赠品</div>
                <div v-if="row.productType == 3" class="goods-type-icon swap">换购</div>
              </div>
              <div class="goods-info">
                <p class="goods-name">{{ row.productName }}</p>
                <p class="goods-num">{{ row.productCode }}</p>
                <p class="goods-sku">{{ getSKU(row.skuValue) }}</p>
              </div>
            </div>
          </el-table-column>
          <el-table-column label="吊牌价/应收(元)" min-width="130px">
            <div slot-scope="{ row }" class="tag-price">
              <del v-if="el.channelType == 3" class="del-price">{{ row.unitPrice | fomatFloat }}</del>
              <div class="sale-price">{{ row.payPrice | fomatFloat }}</div>
            </div>
          </el-table-column>
          <el-table-column label="数量" prop="skuNum" min-width="70px"></el-table-column>
          <el-table-column label="小计金额(元)" min-width="120px">
            <div slot-scope="{ row }">{{ row.payPrice * Math.abs(row.skuNum) | fomatFloat }}</div>
          </el-table-column>
          <el-table-column label="订单金额(元)" class-name="order-amount" min-width="210px">
            <div class="order-descript">
              <!-- 购买单、退换单、销售单显示应收金额 -->
              <!-- 退款单不显示商品合计 -->
              <div v-if="el.orderType != 2" class="order-descript-item gray">
                <div class="order-descript-label">
                  <div class="order-descript-label-text">商品合计</div>：
                </div>
                <div class="order-descript-content">{{ el.paidAmount - el.deliveryPaymentAmount | fomatFloat }}</div>
              </div>
              <div v-if="el.deliveryPaymentAmount" class="order-descript-item gray">
                <div class="order-descript-label">
                  <div class="order-descript-label-text">运费</div>：
                </div>
                <div class="order-descript-content">{{ el.deliveryPaymentAmount | fomatFloat }}</div>
              </div>
              <!-- 退款单显示应退金额 -->
              <div class="order-descript-item gray">
                <div class="order-descript-label">
                  <div class="order-descript-label-text">{{ el.orderType == 2 ? '应退金额' : '应收金额'}}</div>：
                </div>
                <div class="order-descript-content">
                  <div>{{ el.paidAmount | fomatFloat }}</div>
                </div>
              </div>
              <!-- 购买单、退换单显示优惠 -->
              <div class="order-descript-item gray" v-if="el.promotionAmount > 0">
                <div class="order-descript-label">
                  <div class="order-descript-label-text">支付优惠</div>：
                </div>
                <div class="order-descript-content">{{ el.promotionAmount | fomatFloat }}</div>
              </div>
              <!-- 购买单、销售单显示实付金额 -->
              <!-- 退款单、退换单显示实退金额 -->
              <div class="order-descript-item">
                <div class="order-descript-label">
                  <div class="order-descript-label-text">{{ el.orderType == 2 ? '实退金额' : '实付金额'}}</div>：
                </div>
                <div class="order-descript-content">
                  {{ el.payAmount | fomatFloat }}
                  <el-popover v-if="Array.isArray(el.payInfo) && el.payInfo.length > 0" placement="top" title="支付方式" width="200" trigger="hover">
                    <div>
                      <p v-for="(item, index) in el.payInfo" :key="index">{{ item.name }}：￥{{ item.value | fomatFloat }}</p>
                    </div>
                    <span slot="reference" class="payment-type">
                      <i class="payment-type-icon iconfont icon-chakanxiangqing-copy"></i>
                    </span>
                  </el-popover>
                </div>
              </div>
            </div>
          </el-table-column>
          <el-table-column label="收货/导购信息" min-width="244px">
            <div class="order-descript">
              <!-- 门店订单单只显示导购，其他单显示收货信息 -->
              <div v-if="el.channelType == 3" class="order-descript-item">
                <div class="order-descript-label">
                  <div class="order-descript-label-text">导购</div>：
                </div>
                <div class="order-descript-content">
                  <div v-if="!Array.isArray(el.clerks) || el.clerks.length == 0">--</div>
                  <template v-else>
                    <div v-for="(item, index) in el.clerks" :key="index">{{ item.clerkName }}({{ item.clerkCode }})</div>
                  </template>
                </div>
              </div>
              <template v-else>
                <!-- 收货人、手机号、收货地址都无数据时，只显示一个-- -->
                <template v-if="!el.receiverName && !el.phoneNumber && !el.receiverAddress">--</template>
                <template v-else>
                  <div class="order-descript-item">
                    <div class="order-descript-label">
                      <div class="order-descript-label-text">收件人</div>：
                    </div>
                    <div class="order-descript-content">{{ el.receiverName || '--' }}</div>
                  </div>
                  <div class="order-descript-item">
                    <div class="order-descript-label">
                      <div class="order-descript-label-text">手机号</div>：
                    </div>
                    <div class="order-descript-content">{{ el.phoneNumber || '--' }}</div>
                  </div>
                  <div class="order-descript-item">
                    <div class="order-descript-label">
                      <div class="order-descript-label-text">收货地址</div>：
                    </div>
                    <div class="order-descript-content">{{ el.receiverAddress || '--' }}</div>
                  </div>
                </template>
              </template>
            </div>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-pagination
      v-if="params.total > 0"
      :page-sizes="[20, 40, 60, 80]"
      :total="params.total"
      :page-size="params.pageSize"
      :current-page="params.currentPage"
      @current-change="onCurrentChange"
      @size-change="onSizeChange"
      background
      layout="total,sizes,prev,pager,next"
      style="margin-top: 20px; text-align: right"
    ></el-pagination>
  </div>
</template>

<script>
import url from '../../../components/axios/url.js';
import { doFetch } from '../../../components/axios/api.js';
import defaultGoodsIcon from '../../../../static/img/default-goods.png'
export default {
  name: 'OrderTable',
  props: {
    tab: String
  },
  data() {
    return {
      maxHeight: '',
      defaultGoodsIcon,
      params: {
        memberId: '', // 会员id
        pageSize: 20,
        currentPage: 1,
        orderType: '', // 订单类型  1 销售，2.退货，4.退换货
        channelType: '', // 渠道类型 1:达摩微商城， 3:门店（线下）订单，8：天猫，9：微盟，10:其他，11:抖音
        // startTime: '', // 2021-01-01 开始时间
        // endTime: '', // 2022-01-01 结束时间
        orderNumber: '', // 单号
        dateRange: [],
        total: 0
      },
      loadings: false,
      tableData: [
        // {
        //   orderNumber: '单号（订单/退款单）',
        //   oorderNumber: '原始订单号',
        //   orderCreateTime: Date.now(),
        //   createTime: Date.now(),
        //   storeName: '店铺名称',
        //   storeCode: '店铺（门店）编码',
        //   // 订单类型 -1 所有，1 销售，2.退货，4.退换货	
        //   orderType: 1,
        //   totalAmount: 100,
        //   paidAmount: 200,
        //   payAmount: 300,
        //   promotionAmount: 400,
        //   deliveryPaymentAmount: 10,
        //   payInfo: JSON.stringify([{code:101,name:'现金',value:1}]),
        //   receiverName:	'收货人姓名',
        //   phoneNumber: '收货人手机号',
        //   receiverAddress: '收获地址',
        //   clerks: [
        //     { clerkName: '导购名称', clerkCode: '导购code' }
        //   ],
        //   orderItems: [
        //     {
        //       productName: '商品标题',
        //       productCode: '商品编码',
        //       skuValue: '商品规格',
        //       imageUrl: '',
        //       // 商品类型 1正常 2赠品 3换购
        //       productType: 2,
        //       skuNum: 5,
        //       unitPrice: 100,
        //       payPrice: 80
        //     }
        //   ]
        // }
      ]
    }
  },
  created() {
    this.params.memberId = this.$route.query.memberId;
    // channelType: '', // 渠道类型 1:达摩微商城， 3:门店（线下）订单，8：天猫，9：微盟，10:其他，11:抖音
    // <el-tab-pane :label="`门店订单(${orderCount.numOfSale || 0})`" name="store">
    // <el-tab-pane :label="`达摩微商城{${orderCount.wechatMallNum || 0}}`" name="demo">
    // <el-tab-pane :label="`微盟订单(${orderCount.weimobMallNum || 0})`" name="weimob">
    // <el-tab-pane :label="`天猫订单(${orderCount.numOfTmall || 0})`" name="tmall">
    // <el-tab-pane :label="`抖音订单(${orderCount.numOfDouYin || 0})`" name="douyin">
    // <el-tab-pane :label="`其他订单(${orderCount.otherMallNum || 0})`" name="other">
    const channel = { store: 3, demo: 1, weimob: 9, tmall: 8, douyin: 11, other: 10 };
    this.params.channelType = channel[this.tab];
    this.getTableData();
    // if(this.params.channelType == 3) {
    //   let screenHeight = document.documentElement.clientHeight - 540 + 'px';
    //   this.$nextTick(() => {
    //     this.maxHeight = screenHeight;
    //   });
    // }else {
      let screenHeight = document.documentElement.clientHeight - 375 + 'px';
      this.$nextTick(() => {
        this.maxHeight = screenHeight;
      });
    // }
  },
  mounted() {
    const that = this;
    // if(this.params.channelType == 3) {
    //   window.onresize = () => {
    //     return (() => {
    //       let screenHeight = document.documentElement.clientHeight - 540 + 'px';
    //       that.maxHeight = screenHeight;
    //     })();
    //   };
    // }else{
      window.onresize = () => {
        return (() => {
          let screenHeight = document.documentElement.clientHeight - 375 + 'px';
          that.maxHeight = screenHeight;
        })();
      };
    // }
  },
  methods: {
    orderInfoSpan({rowIndex, columnIndex}) {
      if (columnIndex == 0) {
        return [1, 2];
      } else if (columnIndex == 2) {
        return [1, 4];
      } else {
        return [0, 0];
      }
    },
    goodsInfoSpan(data, rowIndex, columnIndex) {
      if (columnIndex == 4 || columnIndex == 5) {
        if (rowIndex == 0) {
          return [data.orderItems.length, 1];
        } else {
          return [0, 0];
        }
      } else {
        return [1, 1];
      }
    },
    formatChannelType(type) {
      // 渠道类型：1:达摩微商城， 3:门店（线下）订单，8：天猫，9：微盟，10:其他，11:抖音
      // <!-- 天猫、微盟、抖音、门店 -->
      const typeList = { 3: '门店', 8: '天猫', 9: '微盟', 11: '抖音' };
      return typeList[type];
    },
    getSKU(data) {
      if (typeof data != 'string') return '';
      let result = data;
      try {
        const sku = JSON.parse(data);
        result = sku.map(el => el.value).join('；');
      } catch (e) {}
      return result;
    },
    getTableData() {
      this.loadings = true;
      const { memberId, pageSize, currentPage, orderType, channelType, dateRange, orderNumber } = this.params;
      const params = { memberId, pageSize, currentPage, orderType, channelType, orderNumber };
      if (Array.isArray(dateRange) && dateRange.length > 0) {
        params.startTime = dateRange[0];
        params.endTime = dateRange[1];
      }
      doFetch(url.getOrderList, params).then(res => {
        let { page } = res.data.result || {};
        if (Object.prototype.toString.call(page) != '[object Object]') {
          page = {};
        }
        this.tableData = page.result.map(el => {
          el.payInfo = typeof el.payInfo == 'string' ? JSON.parse(el.payInfo) : null;
          return el;
        });
        this.params.total = page.totalCount;
        this.loadings = false;
      });
    },
    onSearch() {
      this.onCurrentChange(1);
    },
    onSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.onSearch();
    },
    onCurrentChange(currentPage) {
      this.params.currentPage = currentPage;
      this.getTableData();
    }
  }
}
</script>

<style lang="scss" scoped>
.search-bar {
  margin-bottom: 20px;
  font-size: 0;
  .search-create-time {
    margin-left: 10px;
    vertical-align: middle;
    color: #303133;
  }
}
.table-header {
  margin-bottom: 16px;
  /deep/ .el-table__empty-block {
    display: none;
  }
  /deep/ th>.cell:first-child {
    padding-left: 10px;
  }
}
.order-list {
  +.order-list {
    margin-top: 12px;
  }
  .order-info-box {
    width: 100%;
    height: 36px;
    font-size: 13px;
    font-weight: 400;
    color: #303133;
    background: #F7F8FA;
    border-bottom: 1px solid #E4E7ED;
    box-sizing: border-box;
    /deep/ tr, /deep/ tr:hover>td.el-table__cell {
      background-color: transparent;
    }
    /deep/ .el-table__cell {
      padding: 0;
      border-bottom: none;
    }
    &+.order-info-box {
      margin-top: 12px;
    }
    .order-info {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height: 36px;
      .order-type-tag {
        flex-shrink: 0;
        padding: 0 9px;
        height: 22px;
        text-align: center;
        line-height: 24px;
        font-size: 12px;
        font-weight: 400;
        color: #FFFFFF;
        border-radius: 2px;
        box-sizing: border-box;
        &.order-buy {
          background: #33AF4A;
        }
        &.order-refund {
          background: #F5222D;
        }
        &.order-exchange {
          background: #FA8C16;
        }
      }
      .order-num-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-left: 17px;
        font-size: 13px;
        .connect-order-num {
          margin-left: 30px;
        }
      }
    }
    .order-time-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 36px;
      .time-info-box {
        flex-shrink: 0;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        .order-create-time {
          flex-shrink: 0;
          width: 200px;
          font-size: 13px;
        }
        .order-sync-time {
          flex-shrink: 0;
          margin-left: 30px;
          width: 228px;
          font-size: 13px;
        }
      }
      .store-info {
        // flex-shrink: 0;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        line-height: normal;
        max-width: calc(100% - 475px);
        .store-type-tag {
          display: flex;
          flex-shrink: 0;
          justify-content: center;
          align-items: center;
          margin-right: 6px;
          padding: 0 4px;
          // width: 32px;
          height: 18px;
          background: #DEE3FC;
          border-radius: 2px;
          font-size: 12px;
          font-weight: 400;
          color: #2F54EB;
        }
        .store-name {
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 13px;
        }
      }
    }
  }
  .goods-info-box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .goods-logo {
      position: relative;
      flex-shrink: 0;
      margin-right: 10px;
      width: 60px;
      height: 60px;
      border-radius: 2px;
      .goods-logo-icon {
        width: 100%;
        height: 100%;
        vertical-align: middle;
        .errorimage {
          display: inline-block;
          margin-top: 18px;
          font-size: 60px;
          // color: #f8fafe;
          border-radius: 2px;
        }
      }
      .goods-type-icon {
        position: absolute;
        top: 0;
        right: 0;
        z-index: 1;
        padding: 1px 5px;
        border-radius: 2px;
        font-size: 12px;
        font-weight: 400;
        color: #FFFFFF;
        line-height: normal;
        &.gift {
          background: #0FC6C2;
        }
        &.swap {
          background: #7816FF;
        }
      }
    }
    .goods-info {
      width: calc(100% - 60px);
      .goods-name {
        width: 100%;
        font-size: 14px;
        font-weight: 400;
        color: #303133;
        line-height: 18px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .goods-num {
        margin-top: 4px;
        font-size: 12px;
        font-weight: 400;
        color: #303133;
        line-height: 17px;
      }
      .goods-sku {
        margin-top: 4px;
        font-size: 12px;
        font-weight: 400;
        color: #606266;
        line-height: 17px;
      }
    }
  }
  .order-detail {
    /deep/ .el-table__body tr:hover>td.el-table__cell {
      background: transparent;
    }
    /deep/ .order-amount {
      border-left: 1px solid #E4E7ED;
    }
    .tag-price {
      font-size: 14px;
      font-weight: 400;
      color: #303133;
      line-height: 22px;
      .del-price {
        color: #909399;
      }
    }
    .order-descript {
      padding-left: 14px;
      .order-descript-item {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        font-size: 14px;
        font-weight: 400;
        color: #303133;
        line-height: 20px;
        &+.order-descript-item {
          margin-top: 6px;
        }
        &.gray {
          color: #606266;
        }
        .order-descript-label {
          flex-shrink: 0;
          width: 70px;
          .order-descript-label-text {
            display: inline-block;
            width: 56px;
            text-align: justify;
            text-align-last: justify;
          }
        }
        .order-descript-content {}
        .payment-type {
          display: inline-block;
          vertical-align: middle;
          padding: 5px 5px 4px;
          border-radius: 2px;
          line-height: normal;
          font-size: 0;
          &:hover {
            background: #F2F3F5;
          }
          .payment-type-icon {
            font-size: 14px;
          }
        }
      }
    }
  }
}
</style>
