<template>
  <ai-list class="list" v-loading="isLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <ai-title
      slot="title"
      title="发货单列表"
      isShowBottomBorder>
    </ai-title>
    <template slot="content">
      <ai-card title="发货单列表" style="padding-bottom: 40px;">
        <ai-table
          :isShowPagination="false"
          :tableData="orderList"
          :col-configs="colConfigs"
          height="700"
          style="margin-top: 8px;"
          @getList="() => {}">
          <el-table-column slot="options" label="操作" width="120px" show-overflow-tooltip align="center" fixed="right">
            <template slot-scope="{ row }">
              <div class="table-options">
                <el-button type="text" @click="downloadLabelInfo(row)">下载标签信息</el-button>
              </div>
            </template>
          </el-table-column>
        </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: 'sellerDeliveryNo', label: '发货单号', align: 'left' },
          { prop: 'orderTypeName', label: '类型', align: 'left' },
          { prop: 'deliveryAmountAll', label: '送货总数', align: 'left' },
          { prop: 'expressName', label: '物流公司名称', align: 'left' },
          { prop: 'takeParcelStatusName', label: '状态' },
          { prop: 'deliveryTime', label: '发货时间' }
        ],
        reqData: {
          "page": 1,
          "billStatusList": [],
          "deliveryTimeEnd": null,
          "deliveryTimeStart": null,
          "deliveryTypeList": [],
          "exportIds": [],
          "expressCodeList": [],
          "expressStatusList": [],
          "orderTypeList": [],
          "sellerDeliveryNoList": [],
          "sellerOrderNoList": [],
          "perPage": 10
        },
        labelInfoList: [],
        orderList: [],
        sellerDeliveryNo: null
      }
    },

    mounted () {
      this.getStoreCode()
      this.getList()
    },

    methods: {
      async getList () {
        this.isLoading = true
        this.reqData.page = 1
        this.tableData = []
        this.orderList = []
        await this.getOrderList()
        this.isLoading = false
      },
      async getOrderList() {

        let res = await sendGeiwohuoAPIMessage({
          url: `pfmp/delivery/list`,
          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 = {
              id: item.id,
              sellerDeliveryNo: item.sellerDeliveryNo,
              orderTypeName: item.orderTypeName,
              deliveryAmountAll: item.deliveryAmountAll,
              expressName: item.expressName,
              takeParcelStatusName: item.takeParcelStatusName,
              deliveryTime: item.deliveryTime
            }
            this.orderList.push(data)
          }
        } 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.getSheinLabelList()
        } else if (res.code == 100004 || res.code == 20302) {
          this.isLoading = false
          this.$store.commit("setSheinAlertShow", true)
        }
      },
      getSheinLabelList() {
        this.$http.post(`/api/sheinLabel/listAll`, null, {
          params: {
            mallId: this.storeCode
          }
        }).then(res => {
          if (res.code == 0) {
            this.labelInfoList = res.data
          }
        })
      },
      async downloadLabelInfo(row) {
        this.sellerDeliveryNo = row.sellerDeliveryNo
        let res = await sendGeiwohuoAPIMessage({
          url: `pfmp/delivery/detail?id=${row.id}`,
          method: 'GET'
        })
        if (res.code == '0' && res.msg == "OK") {
          let params = []
          for(let i = 0;i < res.info.orderList.length; i++) {
            let item = res.info.orderList[i]

            for (let j = 0; j < item.detail.length; j++) {
              params.push({
                orderNo: item.sellerOrderNo,
                printNumber: item.detail[j].orderQuantity,
                skuCode: item.detail[j].skuCode,
                supplierId: res.info.sellerId,
                supplierCode: item.supplierCode,
                subSuffixZh: item.detail[j].subSuffixZh,
                skc: item.skcName
              })
            }
          }

          let reqParams = []
          params.map(item => {
            reqParams.push({
              orderNo: item.orderNo,
              printNumber: item.printNumber,
              skuCode: item.skuCode,
              supplierId: item.supplierId
            })
          })

          let res1 = await sendGeiwohuoAPIMessage({
            url: `pfmp/order/printOrderBarCode`,
            method: 'POST',
            data: {
              printList: reqParams,
              type: 3
            }
          })

          if (res1.code == '0' && res1.msg == "OK") {
            let successList = res1.info.sucessList
            for (let i = 0; i < successList.length; i++) {
              for (let j = 0; j < params.length; j++) {
                if ((successList[i].skuCode == params[j].skuCode) && (successList[i].orderNo == params[j].orderNo)) {
                  successList[i].skc = params[j].skc
                  successList[i].printNumber = params[j].printNumber
                  successList[i].subSuffixZh = params[j].subSuffixZh
                  successList[i].supplierCode = params[j].supplierCode
                  break
                }
              }
            }
            const data = [
              ["文件名", "数量", "SKC", "SKU", "型号", "额定电压", "额定电流", "生产日期", "保质期", "SKC货号", "产品编码", "订单号", "属性集", "模板名称"]
            ]
            for (let i = 0; i < successList.length; i++) {
              for (let j = 0; j < this.labelInfoList.length; j++) {
                if (successList[i].skc == this.labelInfoList[j].skc) {
                  successList[i].model = this.labelInfoList[j].model
                  successList[i].ratedVoltage = this.labelInfoList[j].ratedVoltage
                  successList[i].ratedCurrent = this.labelInfoList[j].ratedCurrent
                  successList[i].productDate = this.labelInfoList[j].productDate
                  successList[i].warranty = this.labelInfoList[j].warranty
                  successList[i].templateName = this.labelInfoList[j].templateName
                  break
                }
              }
            }

            successList.map(item => {
              data.push([item.skc+"_"+item.orderNo+"_"+item.skuCode, item.printNumber, item.skc, item.skuCode, item.model, item.ratedVoltage, item.ratedCurrent, item.productDate, item.warranty, item.supplierCode, item.barcode, item.orderNo, item.subSuffixZh, item.templateName])
            })
      
            // 将数据转换为工作表
            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, this.sellerDeliveryNo + '.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>
