<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="form.mallId" @change="beforeGetList" 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 style="width:120px">出库时间：</label>
              <el-date-picker
                v-model="form.date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </template>
          <template #right>
            <el-button type="primary" @click="toLoad">查询</el-button>
          </template>
        </ai-search-bar>
        <ai-card title="数据明细" style="padding-bottom: 40px;">
          <template #right>
            <json-excel
              :data="tableData"
              :fields="jsonFields"
              :before-generate = "startDownload"
              name="退货明细.xls"
              worksheet="退货明细">
              <el-button type="primary">导出数据</el-button>
            </json-excel>
          </template>
          <ai-table
              :isShowPagination="false"
              :tableData="tableData"
              :col-configs="colConfigs"
              :total="total"
              height="500"
              style="margin-top: 8px;"
              @getList="getList">
              <el-table-column slot="productName" width="280px" label="商品信息" align="center">
                <template slot-scope="scope">
                  <div class="product">
                    <img :src="scope.row.thumbUrl">
                      <div class="right">
                        <div>SKC: {{ scope.row.productSkcId }}</div>
                        <div>属性集: {{ scope.row.secondarySaleSpec }}</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
            </ai-table>
        </ai-card>
        <ai-card title="数据统计" style="padding-bottom: 40px;">
          <template #right>
            <json-excel
                :data="sumTableData"
                :fields="sumJsonFields"
                name="退货统计.xls"
                worksheet="退货统计">
                <el-button type="primary" :disabled="sumTableData.length == 0">下载数据</el-button>
              </json-excel>
          </template>
          <ai-table
            :isShowPagination="false"
            :tableData="sumTableData"
            :col-configs="sumColConfigs"
            :total="sumTableData.length"
            height="500"
            style="margin-top: 8px;"
            @getList="() => {}">
          </ai-table>
        </ai-card>
      </div>
    </template>
  </ai-list>
</template>

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

  export default {
    name: 'ReturnDetail',

    data () {
      return {
        isLoading: false,
        colConfigs: [
          { prop: 'productSpuId', label: 'SPU', width: '120px', align: 'left', fixed: 'left' },
          { prop: 'productSkcId', label: 'SKC', width: '120px', align: 'left', fixed: 'left' },
          { prop: 'productSkuId', label: 'SKU', width: '120px', align: 'left', fixed: 'left' },
          { prop: 'skuExtCode', label: 'SKU属性', width: '120px', align: 'left', fixed: 'left' },
          { slot: 'productName', label: '商品信息' },
          { prop: 'purchaseSubOrderSn', label: '备货单号',width: '180px', align: 'left' },
          { prop: 'expressDeLiverySn', label: '运单号',width: '180px', align: 'left' },
          { prop: 'orderTypeDesc', label: '退货原因',width: '220px', align: 'left' },
          { prop: 'packageSn', label: '退货包裹号', width: '200px',align: 'left' },
          { prop: 'quantity', label: 'SKU件数',width: '100px', },
          { prop: 'cost', label: '成本单价' },
          { prop: 'outboundTime', label: '出库时间', width: '160px'}
        ],
        sumColConfigs: [
          { prop: 'productSkcId', label: 'SKC', align: 'left', fixed: 'left' },
          { prop: 'productSkuId', label: 'SKU', align: 'left', fixed: 'left' },
          { prop: 'skuExtCode', label: 'SKU属性', align: 'left', fixed: 'left' },
          { prop: 'secondarySaleSpec', label: '属性集', align: 'left', fixed: 'left' },
          { prop: 'quantity', label: 'SKU总件数', sortable: true, 'sort-method': (a, b) => a.quantity - b.quantity },
          { prop: 'costPrice', label: '成本价', sortable: true, 'sort-method': (a, b) => a.costPrice - b.costPrice},
          { prop: 'costAmount', label: '成本总额', sortable: true, 'sort-method': (a, b) => a.costAmount - b.costAmount}
        ],
        jsonFields: {
          "SPU": "productSpuId",
          "SKC": "productSkcId",
          "SKU": "productSkuId",
          "SKU属性": "skuExtCode",
          "图片地址": "thumbUrl",
          "属性集": "secondarySaleSpec",
          "备货单号": "purchaseSubOrderSn",
          "运单号": "expressDeLiverySn",
          "退货原因": "orderTypeDesc",
          "退货包裹号": "packageSn",
          "SKU件数": "quantity",
          "成本单价": "cost",
          "出库时间": "outboundTime"
        },
        sumJsonFields: {
          "SKC": "productSkcId",
          "SKU": "productSkuId",
          "SKU属性": "skuExtCode",
          "图片地址": "thumbUrl",
          "属性集": "secondarySaleSpec",
          "SKU总件数": "quantity",
          "成本价": "costPrice",
          "成本总额": "costAmount"
        },
        form: {
          mallId: '',
          date: ''
        },
        currentPage: 1,
        pageSize: 100,

        tableData: [],
        sumTableData: [],
        costList: [],
        total: 0,
        search: {
          current: 1,
          size: 10,
          mallId: ''
        }
      }
    },

    computed: {
    },

    components: {
      JsonExcel
    },

    created () {
    },

    methods: {
      changeDataType() {

      },
      beforeGetList() {
        this.$userCheck(this.form.mallId).then(() => {
          
        }).catch((err) => {
          this.form.mallId = ''
        })
      },
      toLoad() {
        if (!this.form.mallId) {
          Message.error("请先选择店铺")
          return
        }
        if (!this.form.date) {
          Message.error("请选择时间范围")
          return
        }
        this.currentPage = 1
        this.tableData = []
        this.sumTableData = []

        let startTime = this.form.date[1].getTime() - 30 * 24 * 60 * 60 * 1000
        if (startTime < this.form.date[0].getTime()) {
           startTime = this.form.date[0].getTime()
        }
        this.getList(startTime, this.form.date[1].getTime() + 86400*1000 - 1)
      },
      getList (startTime, endTime) {
        sendChromeAPIMessage({
          url: 'dunland/api/gmp/returnSupplier/package/pageReturnPackageSkuDetailList',
          needMallId: true,
          mallId: this.form.mallId,
          data: {
            pageNo: this.currentPage,
            pageSize: 100,
            outboundTimeEnd: endTime,
            outboundTimeStart: startTime
          }}).then((res) => {
          if (res.errorCode == 1000000) {
            for(let i = 0;i < res.result.packageDetailDTOList.length; i++) {
              let item = res.result.packageDetailDTOList[i];
              let data = {};
              data.productSpuId = item.productSpuId
              data.productSkcId = item.productSkcId
              data.productSkuId = item.productSkuId
              
              data.secondarySaleSpec = item.secondarySaleSpec
              data.thumbUrl = item.thumbUrl
              data.purchaseSubOrderSn = item.purchaseSubOrderSn
              data.orderTypeDesc = item.orderTypeDesc + '-' + item.reasonDesc.join(',') + '，备注：' + (item.remark ? item.remark: '--')
              data.packageSn = item.packageSn
              data.quantity = item.quantity
              data.outboundTime = timestampToTime(item.outboundTime)
              data.cost = null
              
              this.tableData.push(data)
            }
            if (100 == res.result.packageDetailDTOList.length) {
              this.currentPage ++
              setTimeout(() => {
                this.getList(startTime, endTime)
              }, 1500)
            } else {
              if (startTime > this.form.date[0].getTime()) {
                let startTimeTemp = startTime - 30 * 24 * 60 * 60 * 1000
                if (startTimeTemp < this.form.date[0].getTime()) {
                  startTimeTemp = this.form.date[0].getTime()
                }
                let endTimeTemp = endTime - 30 * 24 * 60 * 60 * 1000
                this.currentPage = 1
                this.getList(startTimeTemp, endTimeTemp)
              } else {
                this.getDeliverySn(1)
                
                this.getSkuCostList()
                this.isLoading = false
              }
            }
          } else {
            setTimeout(() => {
              this.getList(startTime, endTime)
            }, 1500)
          }
        }).catch(() => {
          this.isLoading = false
        })
      },
      async getDeliverySn(pageNo) {
        let arr = []
        this.tableData.map(item => {
          if (arr.indexOf(item.packageSn) == -1) {
            arr.push(item.packageSn)
          }
        })
        let res1 = await sendChromeAPIMessage({
          url: 'dunland/api/gmp/returnSupplier/package/pageQueryReturnSupplierPackage',
          needMallId: true,
          mallId: this.form.mallId,
          data: {
            pageNo: pageNo,
            pageSize: 100,
            returnSupplierPackageNos: arr
          }})
        if (res1.success) {
          res1.result.items.map(item => {
            for (let i = 0; i < this.tableData.length; i++) {
              if (this.tableData[i].packageSn == item.returnSupplierPackageNo) {
                this.tableData[i].expressDeLiverySn = item.expressDeLiverySn
              }
            }
          })
        }
        this.tableData = JSON.parse(JSON.stringify(this.tableData))
        if (res1.result.items.length == 100) {
          await getDeliverySn(pageNo + 1)
        }
      },
      async getSkuExtCode(pageNo) {
        let arr = []
        this.tableData.map(item => {
          if (arr.indexOf(item.productSkuId) == -1) {
            arr.push(item.productSkuId)
          }
        })
        let res1 = await sendChromeAPIMessage({
          url: 'bg-visage-mms/labelcode/pageQuery',
          needMallId: true,
          mallId: this.form.mallId,
          data: {
            page: pageNo,
            pageSize: 100,
            productSkuIdList: arr
          }})
        if (res1.success) {
          res1.result.pageItems.map(item => {
            for (let i = 0; i < this.tableData.length; i++) {
              if (this.tableData[i].productSkuId == item.labelCodeVO.productSkuId) {
                this.tableData[i].skuExtCode = item.labelCodeVO.skuExtCode
              }
            }
          })
        }
        this.tableData = JSON.parse(JSON.stringify(this.tableData))
        if (res1.result.pageItems.length == 100) {
          await getSkuExtCode(pageNo + 1)
        }
      },
      calcAmount() {
        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
              break
            }
          }

          let flag = false
          for (let i = 0; i < this.sumTableData.length; i++) {
            if (item.productSkuId == this.sumTableData[i].productSkuId) {
              this.sumTableData[i].quantity += item.quantity
              flag = true
              break
            }
          }
          if (!flag) {
            this.sumTableData.push({
              productSkcId: item.productSkcId,
              productSkuId: item.productSkuId,
              skuExtCode: item.skuExtCode,
              secondarySaleSpec: item.secondarySaleSpec,
              thumbUrl: item.thumbUrl,
              quantity: item.quantity,
              costPrice: null,
              costAmount: null
            })
          }
        })
        this.sumTableData.map(item => {
          for (let i = 0; i < this.costList.length; i++) {
            if (this.costList[i].sku == item.productSkuId) {
              item.costPrice = this.costList[i].costPrice
              item.costAmount = Math.round(this.costList[i].costPrice * item.quantity * 100) / 100
              break
            }
          }
        })
      },
      async getSkuCostList() {
        await this.getSkuExtCode(1)
        let res = await this.$http.post(`/api/skuCost/listAll`, null, {
          params: {
            mallId: this.form.mallId
          }
        })
        if (res.code == 0) {
          this.costList = res.data
          this.calcAmount()
        }
      },
      startDownload() {
        this.$http.post('/api/malluser/info').then(res => {
          if (res.code == 0) {
            this.$store.commit('setUserInfo', res.data)
            if (res.data.flag != 1) {
              Message.error('您的账号未激活或已失效，请激活后使用')
              this.$store.commit('setActiveDlgShow', true)
              return;
            }
          }
        })
      }
    }
  }
</script>

<style scoped lang="scss">
.product {
  display: flex;
  align-items: center;
  justify-content: center;

  .right {
    flex: 1;
    text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  img {
    width: 60px;
    margin-right: 10px;
  }
}
  .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>
