<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-date-picker
              v-model="dateRange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']">
            </el-date-picker>
          </div>
          <el-button type="button" :class="'el-button el-button--primary'" @click="toSearch">查询</el-button>
        </div>
      </template>
    </ai-title>
    <template slot="content">
      <ai-card title="退货列表" style="padding-bottom: 40px;">
        <template #right>
          <el-button type="primary" @click="exportToExcel">导出</el-button>
        </template>
        <ai-table
          :isShowPagination="false"
          :tableData="tableData"
          :col-configs="colConfigs"
          height="700"
          style="margin-top: 8px;"
          @getList="() => {}">
        </ai-table>
      </ai-card>
    </template>
  </ai-list>
</template>

<script>
import {sendGeiwohuoAPIMessage} from '@/api/chromeApi'
import { Message } from 'element-ui'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

  export default {
    name: 'ReturnRecordShein',

    data () {
      return {
        isLoading: false,
        storeCode: '',
        colConfigs: [
          { prop: 'returnOrderNo', label: '单据号', align: 'left' },
          { prop: 'returnReasonTypeName', label: '发起原因', align: 'left' },
          { prop: 'returnReason', label: '说明', align: 'left' },
          { prop: 'returnOrderStatusName', label: '状态', align: 'left' },
          { prop: 'skc', label: 'SKC' },
          { prop: 'sku', label: 'SKU' },
          { prop: 'supplierCode', label: '供方货号', align: 'left' },
          { prop: 'supplierSku', label: 'SKU货号', align: 'left' },
          { prop: 'suffixZh', label: '属性集' },
          { prop: 'returnCount', label: '退货数量', align: 'left' },
          { prop: 'costPrice', label: '成本价格' },
          { prop: 'returnExpressCompanyName', label: '物流公司', align: 'left' },
          { prop: 'expressNoList', label: '物流单号', align: 'left' },
          { prop: 'addTime', label: '创建时间', align: 'left' }
        ],
        tableData: [],
        dateRange: [],
        reqData: {
          addTimeEnd: null,
          addTimeStart: null,
          page: 1,
          perPage: 200
        },
        productList: [],
        skcList: []
      }
    },

    mounted () {
      this.getStoreCode()
    },

    methods: {
      toSearch() {
        if (!this.dateRange) {
          Message.error("请选择时间范围")
          return
        }
        this.reqData.addTimeStart = this.dateRange[0]
        this.reqData.addTimeEnd = this.dateRange[1]
        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;
            }
            this.getList()
          }
        })
      },
      async getList () {
        this.isLoading = true
        this.reqData.page = 1
        this.tableData = []
        this.skcList = []
        await this.getOrderList()
        this.isLoading = false
      },
      async getOrderList() {
        let res = await sendGeiwohuoAPIMessage({
          url: `pfmp/returnOrder/page`,
          method: 'POST',
          data: this.reqData})
        if (res.code == '0') {
          for(let i = 0;i < res.info.data.length; i++) {
            let item = res.info.data[i];
            let data = {
              returnOrderNo: item.returnOrderNo,
              returnReasonTypeName: item.returnReasonTypeName,
              returnReason: item.returnReason,
              returnOrderStatusName: item.returnOrderStatusName,
              addTime: item.addTime,
              expressNoList: item.expressNoList,
              returnExpressCompanyName: item.returnExpressCompanyName,
              addTime: item.addTime
            }
            let detail = await sendGeiwohuoAPIMessage({
              url: `pfmp/returnOrder/getReturnOrderGoodsDetail`,
              method: 'POST',
              data: {
                "returnOrderId": item.id,
                "skcList": [],
                "supplierCode": "",
                "supplierSkuList": [],
                "platformSkuList": [],
                "page": 1,
                "perPage": 100
              }})

            if (detail.code == '0') {
              detail.info.data.map(item2 => {
                item2.details.map(item3 => {
                  let temp = {
                    ...data,
                    skc: item2.skc,
                    sku: item3.platformSku,
                    returnCount: item3.preReturnQuantity,
                    suffixZh: item3.suffixZh,
                    supplierSku: item3.supplierSku,
                    supplierCode: item2.supplierCode,
                    costPrice: null
                  }
                  this.tableData.push(temp)
                })
              })
            }
    
            
          }
          if (res.info.data.length == 200 && (res.info.meta.count > 200*this.currentPage)) {
            this.reqData.page++
            await this.$sleepSync(200)
            await this.getOrderList()
          } else {
            this.tableData.map(item => {
              item.costPrice = this.getCost(item.sku)
            })
          }
        } else if (res.code == 100004 || res.code == 20302) {
          this.$store.commit("setSheinAlertShow", true)
        }
      },
      async getStoreCode() {
        let res = await sendGeiwohuoAPIMessage({
          url: 'sso-prefix/auth/getUser?uuid=' + Date.now(),
          method: 'GET'
        })
        if (res.code == '0' && res.msg == "OK") {
          this.storeCode = res.info.merchantCode
          this.getPorductList()
        } else if (res.code == 100004 || res.code == 20302) {
          this.isLoading = false
          this.$store.commit("setSheinAlertShow", true)
        }
      },
      getCost(sku) {
        for (let i = 0; i < this.productList.length; i++) {
          if (sku == this.productList[i].sku) {
            return this.productList[i].costPrice
          }
        }
        return 0
      },
      getPorductList() {
        this.$http.post(`/api/skuCost/listAll`, null, {
          params: {
            mallId: this.storeCode
          }
        }).then(res => {
          if (res.code == 0) {
            this.productList = res.data
          }
        })
      },
      exportToExcel() {
        // 假设你有一个表格数据的数组
        const data = [
          ["单据号", "发起原因", "说明", "状态", "SKC", "SKU", "供方货号", "SKU货号", "属性集", "退货数量", "成本价格", "物流公司", "物流单号", "创建时间"]
        ]

        this.tableData.map(item => {
          data.push([item.returnOrderNo, item.returnReasonTypeName, item.returnReason, item.returnOrderStatusName, item.skc, item.sku, item.supplierCode, item.supplierSku, item.suffixZh, item.returnCount, item.costPrice, item.returnExpressCompanyName, item.expressNoList, item.addTime])
        })
  
        // 将数据转换为工作表
        const worksheet = XLSX.utils.aoa_to_sheet(data);
  
        // 创建工作簿并添加工作表
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  
        // 生成Excel文件
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  
        // 使用blob和FileReader创建一个Blob URL
        const dataBlob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
        const blobUrl = window.URL.createObjectURL(dataBlob);
  
        // 使用saveAs下载文件
        saveAs(dataBlob, '退货明细.xlsx');
  
        // 清理
        window.URL.revokeObjectURL(blobUrl);
      }
    }
  }
</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>
