<template>
  <ai-list class="list" v-loading="isLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <ai-title
      slot="title"
      title="售后赔付统计"
      isShowBottomBorder>
      <template #rightBtn>
        <div class="title-right">
          <div>
            <label style="width:90px">店铺：</label>
            <el-select v-model="mallId" placeholder="请选择" size="small">
              <el-option
                v-for="item in $store.state.mallList"
                :key="item.mallId"
                :label="item.mallName"
                :value="item.mallId">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
    </ai-title>
    <template slot="content">
      <div class="content">
        <ai-search-bar>
          <template #left>
            <div class="search-item">
              <label>账务时间：</label>
              <el-date-picker
                v-model="searchDate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </template>
          <template #right>
            <el-button type="primary" @click="beforeGetList">加载</el-button>
          </template>
        </ai-search-bar>
        <ai-card title="数据明细" style="padding-bottom: 40px;">
          <template #right>
              <json-excel
                  :data="tableData"
                  :fields="jsonFields"
                  name="售后赔付统计列表.xls"
                  worksheet="售后赔付统计列表">
                  <el-button type="primary" :disabled="tableData.length == 0">下载数据</el-button>
                </json-excel>
          </template>
          <ai-table
            :isShowPagination="false"
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="tableData.length"
            height="700"
            style="margin-top: 8px;"
            @getList="() => {}">
            <el-table-column slot="productName" width="400px" :show-overflow-tooltip='true' label="商品名称"  fixed="left">
              <template slot-scope="scope">
                <div>
                  <el-image :src="scope.row.productUrl" style="width: 40px; height: 40px" class="image" :preview-src-list="[scope.row.productUrl]" />
                  {{ scope.row.productName }}
                </div>
              </template>
            </el-table-column>
          </ai-table>
        </ai-card>
      </div>
    </template>
  </ai-list>
</template>

<script>
import { Message } from 'element-ui'
import {sendChromeAPIMessage } from '@/api/chromeApi'
import {timestampToTime} from '@/utils/date'
import JsonExcel from 'vue-json-excel'

  export default {
    name: 'AfterSaleStat',

    data () {
      return {
        mallId: '',
        searchDate: [],
        reqData: {
          pageNum: 1,
          pageSize: 100
        },
        colConfigs: [
          { prop: 'productName', label: '商品名称', width: '400px', align: 'left', fixed: 'left' },
          { prop: 'productSkuId', label: 'SKU ID', align: 'left' },
          { prop: 'skuCode', label: 'SKU货号', align: 'left' },
          { prop: 'deductionAmount', label: '扣款总金额', align: 'left', sortable: true, 'sort-method': (a, b) => a.deductionAmount - b.deductionAmount },
          { prop: 'times', label: '扣款次数', align: 'left', sortable: true, 'sort-method': (a, b) => a.times - b.times },
          /*{ prop: 'supplierPrice', label: '供货价', align: 'left', sortable: true, 'sort-method': (a, b) => a.supplierPrice - b.supplierPrice },
          { prop: 'cost', label: '成本', align: 'left', sortable: true, 'sort-method': (a, b) => a.cost - b.cost },
          { prop: 'profitTimes', label: '相当于X件白卖', align: 'left', sortable: true, 'sort-method': (a, b) => a.profitTimes - b.profitTimes }*/
        ],
        isLoading: false,
        tableData: [],
        jsonFields: {
          "商品名称": "productName",
          "SKU ID": "productSkuId",
          "SKU货号": "skuCode",
          "扣款总金额": "deductionAmount",
          "扣款次数": "times"
        },
        costList: []
      }
    },
    components: {
      JsonExcel
    },
    methods: {
      beforeGetList() {
        this.$userCheck(this.mallId).then(() => {
          this.toLoad()
        }).catch((err) => {
          this.mallId = ''
        })
      },
      async toLoad() {
        if (!this.mallId) {
          Message.error("请选择店铺")
          return
        }
        if (!this.searchDate) {
          Message.error("请选择时间范围")
          return
        }
        this.reqData.pageNum = 1
        this.tableData = []
        this.isLoading = true

        let startTime = this.searchDate[0].getTime()
        let endTime = this.searchDate[1].getTime() + 86400000
        while(true) {
          if ((endTime - startTime) > 2592000000) {
            this.reqData.pageNum = 1
            await this.getAfterSaleDeductList(startTime, startTime + 2592000000)
            startTime = startTime + 2592000000
          } else {
            this.reqData.pageNum = 1
            await this.getAfterSaleDeductList(startTime, endTime)
            break
          }
        }

        this.isLoading = false

      },
      async getAfterSaleDeductList(startTime, endTime) {
        let res = await sendChromeAPIMessage({
          url: `api/merchant/fund/deduction/after-sales-compensation/query`,
          needMallId: true,
          mallId: this.mallId,
          data: {
            ...this.reqData,
            beginFundTime: startTime,
            endFundTime: endTime
          }})
        if (res.errorCode == 1000000) {
          for (let i = 0; i < res.result.resultList.length; i++) {
            let item = res.result.resultList[i]
            let flag = false
            for (let j = 0; j < item.productSkuIdList.length; j++) {
              for ( let k = 0; k < this.tableData.length; k++) {
                if (item.productSkuIdList[j] == this.tableData[k].productSkuId) {
                  flag = true
                  this.tableData[k].times++
                  this.tableData[k].deductionAmount = Math.round((this.tableData[k].deductionAmount + new Number(item.deductionAmount.digitalText))*100)/100
                  if (!this.tableData[k].skuCode) {
                    this.tableData[k].skuCode = item.skuExtCodeList[j]
                  }
                  break 
                }
              }
              if (!flag) {
                this.tableData.push({
                  productName: item.goodsNameList[j],
                  productSkuId: item.productSkuIdList[j],
                  deductionAmount: new Number(item.deductionAmount.digitalText),
                  skuCode: item.skuExtCodeList[j],
                  times: 1,
                  supplierPrice: ''
                })
                flag = true
              }
            }
          }
          if ((this.reqData.pageSize * this.reqData.pageNum) < res.result.total) {
            this.reqData.pageNum ++
            await this.getAfterSaleDeductList(startTime, endTime)
          }
        }
      },
      async getProductList(params) {
        let res = await sendChromeAPIMessage({
          url: 'bg-visage-mms/product/skc/pageQuery',
          needMallId: true,
          mallId: this.mallId,
          data: {
            ...params
        }})
        if (res.errorCode == 1000000) {
          res.result.pageItems.map((item) => {
            item.productSkuSummaries.map(item1 => {
              for (let i = 0; i < this.tableData.length; i++) {
                if (this.tableData[i].productSkuId == item1.productSkuId) {
                  this.tableData[i].supplierPrice = item1.supplierPrice / 100
                  this.tableData[i].productUrl = item1.thumbUrl
                  this.tableData[i].skcCode = item.extCode
                  this.tableData[i].skuCode = item1.extCode
                  break
                }
              }
            })
          })

          if ((params.page * params.pageSize) < res.result.total) {
            params.page ++
            await this.getProductList(params)
          }
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  .list {
    .title-right {
      display: flex;
      align-items: center;

      & > div:first-child {
        margin-right: 20px;
      }
    }
    ::v-deep.ai-list {
      .ai-list__content--right-wrapper {
        background: transparent;
        box-shadow: none;
        padding: 0!important;
      }
    }
  }
</style>