<template>
  <div class="minwidth1200 member-fee">
    <div class="consumption-container">
      <v-nav :navpath="navpath" />
      <div class="record-count-wrap">
        <div class="record-navitem" v-for="item in totalCountList" :key="item">
          <p class="count-label">
            {{ item.label }}
          </p>
          <p class="count-txt" v-if="item.filter==='fomatFloat'">
            {{ memberInfo[item.key] | fomatFloat }}
          </p>
          <p class="count-txt" v-else-if="item.filter==='formatYMD'">
            {{ memberInfo[item.key] | formatYMD }}
          </p>
          <p class="count-txt" v-else>
            {{ memberInfo[item.key] }}
          </p>
        </div>
      </div>
      <div class="record" v-loading="fullscreenLoading">
        <div class="record-search">
          <div class="record-searchitem">
            <el-select v-model="orderType" style="width:160px;" placeholder="所有类型"
              @change="handleSearch">
              <el-option v-for="item in orderOpts" :key="item.value" :label="item.label"
                :value="item.value" />
            </el-select>
          </div>
        </div>
        <div class="table-content" v-loading="load">
          <el-table :class="['only-head-table',!memberData.length?'no-data':'']">
            <el-table-column v-for="colunm in tableColumnList" :key="colunm" :label="colunm.label"
              :min-width="colunm.width" />
          </el-table>
          <div class="only-content-table-list" style="height:calc(100vh - 224px);"
            v-if="memberData.length">
            <div class="group-item" v-for="group in memberData" :key="group">
              <div class="group-header">
                <div class="left">
                  <p class="order-number">
                    订单编号：{{ group.orderNumber }}
                  </p>
                  <p class="order-time">
                    订单时间：{{ group.receiptsDate|formatTime }}
                  </p>
                </div>
                <div class="right">
                  <p class="store-name">
                    {{ group.storeName }}
                  </p>
                </div>
              </div>
              <el-table class="only-content-table" :data="group.orderItems" show-overflow-tooltip
                :span-method="(obj)=>spanMethod({...obj,length:group.orderItems.length})">
                <template v-for="colunm in tableColumnList">
                  <el-table-column :key="colunm" :label="colunm.label" :min-width="colunm.width"
                    show-overflow-tooltip :prop="colunm.prop">
                    <template slot-scope="{row}">
                      <template
                        v-if="['orderStatus','clerkName','payAmount'].includes(colunm.prop)">
                        <!-- 订单类型 -->
                        <template v-if="colunm.prop==='orderStatus'">
                          <div style="padding-left:14px;">{{ group[colunm.prop]|orderTypeFilter }}
                          </div>
                        </template>
                        <template v-else-if="colunm.prop==='clerkName'">
                          <div class="clerk-info">
                            <p class="name">
                              {{ group[colunm.prop] }}
                            </p>
                            <p class="code">
                              {{ group.clerkCode }}
                            </p>
                          </div>
                        </template>
                        <template v-else>
                          <div style="display:flex;align-items:center;padding-left:14px;">
                            ￥{{ group[colunm.prop]|fomatFloat }}
                            <el-popover popper-class="amount-detail-popover" placement="bottom"
                              width="242" trigger="hover" :open-delay="200" @show="getOrderDetail(group.orderId)">
                              <div class="amount-detail" v-loading="orderLoading">
                                <template v-if="Object.keys(orderInfo).length">
                                  <h5 class="title">
                                    金额详情
                                  </h5>
                                  <div class="middle">
                                    <p class="amount-line">
                                      <span>吊牌价总额：</span>¥{{ orderInfo.totalAmount|fomatFloat }}
                                    </p>
                                    <p class="amount-line">
                                      <span>订单应收：</span>¥{{ orderInfo.paidAmount|fomatFloat }}
                                    </p>
                                    <p class="amount-line">
                                      <span>订单实付：</span>¥{{ orderInfo.actualAmount|fomatFloat }}
                                    </p>
                                  </div>
                                  <div class="bottom">
                                    <p class="amount-line">
                                      支付方式：
                                    </p>
                                    <div class="right">
                                      <p v-for="pay in payInfo" :key="pay">
                                        <span>{{ pay.name }}</span>¥{{ pay.value|fomatFloat }}
                                      </p>
                                    </div>
                                  </div>
                                </template>
                                <div v-else style="text-align:center">
                                  暂无数据
                                </div>
                              </div>
                              <span slot="reference" class="icon-span" title="查看金额详情"><i
                                  class="iconfont icon-zhangdan" /></span>
                            </el-popover>
                          </div>
                        </template>
                      </template>
                      <template v-else>
                        <div class="good-info" v-if="colunm.prop==='productName'">
                          <el-image fit="cover"
                            :src="row.imageUrl ? row.imageUrl : './static/img/default-goods.png'">
                            <div slot="error" class="image-slot">
                              <img width="60" :src="require('../../../static/img/broke-img.png')"
                                alt="">
                            </div>
                          </el-image>
                          <div class="info-detail">
                            <p class="good-name">
                              <span class="name">{{ row.productName }}</span>
                              <el-tag type="warning" v-if="[2,3].includes(row.productType)">
                                {{ row.productType===2?'赠品':'换购'}}
                              </el-tag>
                            </p>
                            <p class="good-code">
                              {{ row.productCode }}
                            </p>
                            <p class="good-attr">
                              {{ row.attrColorSize }}
                            </p>
                          </div>
                        </div>
                        <div class="price-info" v-else-if="colunm.prop==='unitPrice'">
                          <p class="good-unitPrice">
                            ￥{{ row.unitPrice|fomatFloat }}
                          </p>
                          <p class="italics-line">
                            /
                          </p>
                          <p class="good-payPrice">
                            ￥{{ row.payPrice|fomatFloat }}
                          </p>
                        </div>
                        <div v-else style="padding-left:14px;">
                          {{ row.number }}
                        </div>
                        <!-- {{row[colunm.prop]}} -->
                      </template>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </div>
          <div class="page mTop20" v-if="totalCount > 0">
            <dm-pagination background @size-change="handleSizeChange"
              @current-change="handleCurrentChange" :current-page="page.currentPage"
              :page-sizes="[20, 40, 60, 80]" :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next" :total="totalCount" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import nav from '../../common/navbar/navbar.vue';
import { doFetch } from '../axios/api';
import url from '../axios/url';
import {
  checkFalse,
  checkStatus,
} from '../../../static/js/checkStatus';

export default {
  name: 'Consumption',
  filters: {
    orderTypeFilter: (v) => {
      switch (v) {
        case 1: return '销售'; case 2: return '退货'; case 4: return '退换货'; default: return '';
      }
    },
  },
  components: {
    'v-nav': nav,
  },
  data() {
    return {
      load: false,
      memberId: this.$route.query.memberId || '',
      navpath: [
        {
          name: '首页',
          path: '',
        },
        {
          name: '客户列表',
          path: '/allCustomers',
        },
        {
          name: '客户详情',
          path: '/customerDetail?memberId=' + this.$route.query.memberId || '',
        },
        {
          name: '门店订单',
          path: '',
        },
      ],
      memberInfo: {
        costFee: 0,
        costTimes: 0,
        lastCostTime: '',
        avgCost: 0,
        relatedPercent: 0,
        avgGoodsCost: 0,
        highCost: 0,
        costCategoryCount: 0,
        avgDiscount: 0,
      },
      orderType: -1,
      orderLoading: false,
      orderInfo: {},
      payInfo: [],
      page: {
        currentPage: 1,
        pageSize: 20,
      },
      totalCount: 0,
      memberData: [],
      fullscreenLoading: false,
      orderOpts: [
        { label: '所有类型', value: -1 },
        { label: '销售', value: 1 },
        { label: '退货', value: 2 },
        { label: '退换货', value: 4 },
      ],
      totalCountList: [
        { label: '消费总额(实付)', key: 'costFeePaid', filter: 'fomatFloat' },
        { label: '消费总额(应收)', key: 'costFee', filter: 'fomatFloat' },
        { label: '消费次数', key: 'costTimes', filter: '' },
        { label: '最近消费', key: 'lastCostTime', filter: 'formatYMD' },
        { label: '客单价', key: 'avgCost', filter: 'fomatFloat' },
        { label: '连带率', key: 'relatedPercent', filter: 'fomatFloat' },
        { label: '件单价', key: 'avgGoodsCost', filter: 'fomatFloat' },
        { label: '最高单笔(实付)', key: 'highCostPaid', filter: 'fomatFloat' },
        { label: '最高单笔(应收)', key: 'highCost', filter: 'fomatFloat' },
        { label: '平均折扣', key: 'avgDiscount', filter: 'fomatFloat' },
      ],
      tableColumnList: [
        { label: '商品信息', width: '200', prop: 'productName' },
        { label: '单价（吊牌价/应收）', width: '200', prop: 'unitPrice' },
        { label: '数量', width: '80', prop: 'number' },
        { label: '订单类型', width: '100', prop: 'orderStatus' },
        { label: '导购', width: '120', prop: 'clerkName' },
        { label: '小计（实付）', width: '120', prop: 'payAmount' },
      ],
    };
  },
  created() {
    if (this.memberId) {
      this.initData();
    }
    this.$store.commit('mutations-slide', true);
  },
  methods: {
    async initData() {
      this.fullscreenLoading = true;
      await this.getAjaxMembersInfo();
      await this.getMemberOrderPage();
      this.fullscreenLoading = false;
    },
    handleSearch() {
      this.page.currentPage = 1;
      this.getMemberOrderPage();
    },
    handleCurrentChange(val) {
      this.page.currentPage = val;
      this.getMemberOrderPage();
    },
    handleSizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
      this.getMemberOrderPage();
    },
    async getMemberOrderPage() {
      const res = await doFetch(url.memberOrderPage, {
        ...this.page,
        memberId: this.memberId,
        orderType: this.orderType,
      });

      this.memberData = [];
      this.load = true;
      if (res.data.errorCode === 0) {
        this.load = false;
        const { page } = res.data.result || {};
        const list = Array.isArray(page.result) ? page.result : [];
        list.map((item, index) => {
          let price = 0;
          let receivable = 0;
          (item.orderItems || []).map(el => {
            const arr = [];
            // 处理商品吊牌价总额
            price += Number(el.unitPrice);
            // 处理商品应收总额
            receivable += Number(el.payPrice);
            // 处理商品属性
            (JSON.parse(el.attrColorSize) || []).map(ele => {
              arr.push(ele.value);
              return ele;
            });
            el.attrColorSize = arr.join(',');
            return el;
          });
          item.price = price;
          item.receivable = receivable;
          if (index === list.length - 1) {
            this.memberData = JSON.parse(JSON.stringify(list));
            this.totalCount = page.totalCount;
          }
          return item;
        });
      } else {
        checkFalse(res.data.message);
      }
    },
    async getAjaxMembersInfo() {
      const res = await doFetch(url.ajaxMembersInfo, {
        memberId: this.memberId,
      });
      if (res.data.errorCode === 0) {
        const ret = res.data.result;
        this.memberInfo = Object.assign({}, ret.memberInfo);
      } else {
        checkFalse(res.data.message);
        return false;
      }
    },
    getOrderDetail(orderId) {
      this.orderLoading = true;
      doFetch(url.orderDetailNew, {
        memberId: this.memberId,
        orderId: orderId,
      })
        .then(res => {
          if (res.data.errorCode === 0) {
            let orderInfo = { payInfo: [] };
            orderInfo = res.data.result.orderInfo;
            this.orderInfo = Object.assign({}, orderInfo);
            this.payInfo = JSON.parse(orderInfo.payInfo) || [];
          } else {
            checkFalse(res.data.message);
          }
        })
        .catch(err => {
          checkStatus(err);
        }).finally(_ => (this.orderLoading = false));
    },
    spanMethod({ rowIndex, columnIndex, length }) {
      if ([ 3, 4, 5 ].includes(columnIndex)) {
        if (rowIndex === 0) {
          return {
            rowspan: length,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
      return {
        rowspan: 1,
        colspan: 1,
      };
    },
  },
};
</script>
<style lang="less" scoped>
p {
  margin: 0;
}
.record-count-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  margin: 20px 20px 10px;
  background: #fff;
  .record-navitem {
    display: flex;
    flex-direction: column;
    justify-content: center;
    .count-label {
      margin-bottom: 15px;
      font-size: 13px;
      color: #606266;
      line-height: 20px;
    }
    .count-txt {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      line-height: 25px;
    }
  }
}

.record {
  margin: 0 20px 20px;
  padding: 20px;
  background-color: #fff;
  .record-search {
    display: flex;
    margin-bottom: 20px;
    .record-searchitem {
      flex: 1;
    }
  }
}

.table-content {
  .only-head-table {
    /deep/.el-table__body-wrapper {
      display: none;
    }
    /deep/.el-table__header-wrapper {
      margin-bottom: 10px;
    }
    &.no-data {
      /deep/.el-table__body-wrapper {
        display: block;
      }
    }
  }
  .only-content-table-list {
    overflow-y: scroll;
    .only-content-table {
      /deep/.el-table__header-wrapper {
        display: none;
      }
      /deep/td:nth-child(4) {
        border-left: 1px solid #ebeef5;
      }
    }
    /deep/.el-table--enable-row-hover
      .el-table__body
      tr:hover
      > td.el-table__cell {
      background: none;
    }
    .group-item {
      cursor: default;
      .group-header {
        display: flex;
        justify-content: space-between;
        padding: 0 20px 0 14px;
        height: 48px;
        background: #f7f8fa;
        font-size: 14px;
        color: #303133;
        line-height: 22px;
        .left {
          display: flex;
          align-items: center;
          gap: 32px;
        }
        p {
          line-height: 48px;
        }
      }
      .clerk-info {
        padding-left: 14px;
        .name {
          font-size: 14px;
          color: #303133;
          line-height: 22px;
        }
        .code {
          font-size: 14px;
          color: #909399;
          line-height: 22px;
        }
      }
      .good-info {
        display: flex;
        height: 60px;
        overflow-y: hidden;
        .el-image {
          width: 60px;
          height: 60px;
          margin-right: 10px;
          border-radius: 2px;
        }
        .info-detail {
          .good-name {
            display: flex;
            width: 100%;
            margin-bottom: 4px;
            font-size: 14px;
            color: #303133;
            line-height: 20px;
            .name {
              display: block;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .el-tag {
              display: block;
              height: 18px;
              margin-left: 4px;
              line-height: 16px;
            }
          }
          .good-code {
            margin-bottom: 3px;
          }
          .good-code,
          .good-attr {
            font-size: 12px;
            color: #909399;
            line-height: 17px;
          }
        }
      }
      .price-info {
        display: flex;
        padding-left: 4px;

        .good-unitPrice {
          font-size: 14px;
          color: #909399;
          text-decoration: line-through;
        }
        .italics-line,
        .good-payPrice {
          font-size: 14px;
          color: #303133;
        }
        .italics-line {
          margin: 0 5px;
        }
      }
      .icon-span {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 30px;
        height: 30px;
        margin-left: 4px;
        border-radius: 2px;
        text-align: center;
        cursor: pointer;
        .icon-zhangdan {
          font-size: 19px;
          color: #909399;
        }
        &:hover {
          background: #f0f5ff;
          .icon-zhangdan {
            color: #606266;
          }
        }
      }
    }
  }
}
</style>

<style lang="less">
.amount-detail-popover {
  cursor: default;
  .title {
    margin-bottom: 10px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    line-height: 22px;
  }
  .middle {
    padding: 7px 0;
    margin-bottom: 10px;
    background: #f5f7fa;
    border-radius: 2px;
    .amount-line {
      font-size: 14px;
      color: #303133;
      line-height: 20px;
      & + .amount-line {
        margin-top: 10px;
      }
      span {
        display: inline-block;
        width: 91px;
        text-align: right;
      }
    }
  }
  .bottom {
    display: flex;
    font-size: 14px;
    color: #303133;
    line-height: 20px;
    .amount-line {
      width: 91px;
      text-align: right;
    }
    .right {
      span {
        margin-right: 10px;
      }
    }
  }
}
</style>
