<template>
  <ai-list class="list" v-loading="isLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <ai-title
      slot="title"
      title="售后统计"
      tips="请事先在“成本管理”维护好成本，否则部分计算不准确"
      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="reqData.afsApplyYear"
                type="year"
                value-format='yyyy'
                placeholder="选择年">
              </el-date-picker>
            </div>
            <div class="search-item">
              <label>扣罚倍数：</label>
              <el-select v-model="reqData.punishRatioList" multiple placeholder="请选择" size="small">
                <el-option
                  v-for="item in punishRatioOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </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, sendTemuSellerAgentMessage } from '@/api/chromeApi'
import {timestampToTime} from '@/utils/date'
import JsonExcel from 'vue-json-excel'

  export default {
    name: 'AfterSaleStat',

    data () {
      return {
        mallId: '',
        reqData: {
          pageNo: 1,
          pageSize: 100,
          afsApplyYear: '2024',
          punishRatioList: []
        },
        punishRatioOptions: [
          {label: '0', value: '0'},
          {label: '1', value: '1'},
          {label: '1.5', value: '1.5'},
          {label: '2.5', value: '2.5'},
          {label: '5', value: '5'},
        ],
        colConfigs: [
          { slot: 'productName', label: '商品名称', width: '400px', align: 'left', fixed: 'left' },
          { prop: 'skcCode', label: 'SKC货号', align: 'left', height: '40px', fixed: 'left' },
          { prop: 'productSkuId', label: 'SKU ID', align: 'left' },
          { prop: 'skuCode', label: 'SKU货号', align: 'left' },
          { prop: 'rawQualityScore', label: '品质分', align: 'left', sortable: true, 'sort-method': (a, b) => a.rawQualityScore - b.rawQualityScore },
          { prop: 'punishRatio', label: '扣罚总倍数', align: 'left', sortable: true, 'sort-method': (a, b) => a.punishRatio - b.punishRatio },
          { 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: 'deductionAmount', label: '预计扣款', align: 'left', sortable: true, 'sort-method': (a, b) => a.deductionAmount - b.deductionAmount },
          { 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",
          "图片URL": "productUrl",
          "SKC货号": "skcCode",
          "SKU ID": "productSkuId",
          "SKU货号": "skuCode",
          "品质分": "rawQualityScore",
          "扣罚总倍数": "punishRatio",
          "扣罚次数": "times",
          "供货价": "supplierPrice",
          "预计扣款": "deductionAmount",
          "成本": "cost",
          "相当于X件白卖": "profitTimes"
        },
        costList: []
      }
    },
    components: {
      JsonExcel
    },
    methods: {
      beforeGetList() {
        this.$userCheck(this.mallId).then(() => {
          this.toLoad()
        }).catch((err) => {
          this.mallId = ''
        })
      },
      async toLoad() {
        if (!this.mallId) {
          Message.error("请选择店铺")
          return
        }
        this.reqData.pageNo = 1
        this.tableData = []
        this.currentIndex = 0
        this.isLoading = true
        await this.getAfterSalesList('101')
        this.reqData.pageNo = 1
        await this.getAfterSalesList('202')
        this.reqData.pageNo = 1
        await this.getAfterSalesList('102')
        
        let skuIds = []
        this.tableData.map(item => {
          skuIds.push(item.productSkuId)
        })
        this.reqData.pageNo = 1

        await this.getProductList({page: this.reqData.pageNo,
          pageSize: this.reqData.pageSize}, skuIds)
          
          this.costList = []
          await this.getSkuCostList()
          this.isLoading = false
      },
      async getAfterSalesList(zone) {
        this.reqData.bizDrType = zone
        let res = await sendTemuSellerAgentMessage({
          url: `mms/api/appalachian/afs/queryPageV2`,
          needMallId: true,
          mallId: this.mallId,
          data: this.reqData})
        if (res.errorCode == 1000000) {
          for (let i = 0; i < res.result.list.length; i++) {
            let item = res.result.list[i]
            let flag = false
            for (let j = 0; j < item.productSkuId.length; j++) {
              for ( let k = 0; k < this.tableData.length; k++) {
                if (item.productSkuId[j] == this.tableData[k].productSkuId) {
                  flag = true
                  this.tableData[k].times++
                  this.tableData[k].punishRatio = this.tableData[k].punishRatio + new Number(item.punishRatio)
                  break 
                }
              }
              if (!flag) {
                this.tableData.push({
                  productName: item.goodsName,
                  productUrl: '',
                  skcCode: '',
                  productSkuId: item.productSkuId[j],
                  punishRatio: new Number(item.punishRatio),
                  rawQualityScore: item.rawQualityScore,
                  skuCode: '',
                  times: 1,
                  cost: '',
                  supplierPrice: '',
                  deductionAmount: null,
                  profitTimes: ''
                })
                flag = true
              }
            }
          }
          if ((this.reqData.pageSize * this.reqData.pageNo) < res.result.total) {
            this.reqData.pageNo ++
            await this.getAfterSalesList(zone)
          }
        } else if (res.error_code == 40001) {
          this.isLoading = false
          this.$store.commit("setTemuAlertShow", true)
        }
      },
      async getProductList(params, skuIds) {
        let productSkuIds = []
        let i = (params.page - 1) * params.pageSize
        let j = 0
        for (; i < skuIds.length; i++) {
          productSkuIds.push(skuIds[i])
          j ++
          if (j == params.pageSize) break
        }
        if (productSkuIds.length == 0) return
        let res = await sendChromeAPIMessage({
          url: 'bg-visage-mms/product/skc/pageQuery',
          needMallId: true,
          mallId: this.mallId,
          data: {
            page: 1,
            pageSize: params.pageSize,
            productSkuIds
        }})
        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].deductionAmount = Math.round((item1.supplierPrice / 100 * this.tableData[i].punishRatio) * 100)/ 100
                  this.tableData[i].productUrl = item1.thumbUrl
                  this.tableData[i].skcCode = item.extCode
                  this.tableData[i].skuCode = item1.extCode
                  break
                }
              }
            })
          })

          params.page ++
          await this.getProductList(params, skuIds)
        }
      },
      async getSkuCostList() {
        this.$http.post(`/api/skuCost/listAll`, null, {
          params: {
            mallId: this.mallId
          }
        }).then(res => {
          if (res.code == 0) {
            this.costList = res.data
            this.tableData.map(item => {
              for (let i = 0; i < this.costList.length; i++) {
                if (item.productSkuId == this.costList[i].sku) {
                  item.cost = this.costList[i].costPrice
                  item.profitTimes = Math.round((item.supplierPrice * item.punishRatio + item.cost * item.times) / (item.supplierPrice - item.cost) * 100) / 100
                }
              }
            })
          }
        })
      },
    }
  }
</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>