<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>订单状态：</label>
            <el-select v-model="reqData.status" multiple placeholder="请选择" size="small">
              <el-option
                v-for="item in statusList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <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-search-bar>
        <template #left>
          <el-radio-group v-model="type" @change="changeTab">
            <el-radio-button label="urgent">急采</el-radio-button>
            <el-radio-button label="normal">备货</el-radio-button>
          </el-radio-group>
        </template>
        <template #right>
        </template>
      </ai-search-bar>
      <ai-card :title="type == 'urgent' ? '急采订单列表': '备货订单列表'" 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: 'OrderListShein',

    data () {
      return {
        isLoading: false,
        storeCode: '',
        type: 'urgent',
        colConfigs: [
          { prop: 'orderNo', label: '订单号', align: 'left' },
          { prop: 'skc', label: 'SKC ID', align: 'left' },
          { prop: 'skuCode', label: 'SKU ID', align: 'left' },
          { prop: 'supplierCode', label: '货号', align: 'left' },
          { prop: 'supplierSku', label: 'SKU货号', align: 'left' },
          { prop: 'suffixZh', label: '属性集' },
          { prop: 'price', label: '申报价格' },
          { prop: 'costPrice', label: '成本价格' },
          { prop: 'orderQuantity', label: '下单数量', align: 'left' },
          { prop: 'needQuantity', label: '需求数量', align: 'left' },
          { prop: 'deliveryQuantity', label: '送货数量', align: 'left' },
          { prop: 'groundingQuantity', label: '正品数量', align: 'left' },
          { prop: 'defectiveQuantity', label: '次品数量', align: 'left' },
          { prop: 'addTime', label: '下单时间', align: 'left' }
        ],
        tableData: [],
        dateRange: [],
        reqData: {
          "page": 1,
          "allocateTimeEnd": null,
          "allocateTimeStart": null,
          "deliveryNo": null,
          "deliveryNos": [],
          "deliveryTimeEnd": "",
          "deliveryTimeStart": "",
          "finishTimeEnd": "",
          "finishTimeStart": "",
          "ids": [],
          "inspectionTimeEnd": "",
          "inspectionTimeStart": "",
          "launchTimeEnd": "",
          "launchTimeStart": "",
          "mode": "",
          "orderColumn": "",
          "orderType": 1,
          "overdueTypes": [],
          "prepareTypes": [],
          "requestDeliveryTimeEnd": "",
          "requestDeliveryTimeStart": "",
          "requestTakeParcelTimeEnd": "",
          "requestTakeParcelTimeStart": "",
          "reserveDeliveryTimeEnd": "",
          "reserveDeliveryTimeStart": "",
          "sellerOrderNo": null,
          "sellerOrderNos": [],
          "skcName": null,
          "skcNames": [],
          "sourceOrderNoArray": [],
          "status": [
            2,
            5
          ],
          "suffixZh": "",
          "supplierCode": null,
          "supplierCodes": [],
          "supplierSkuList": [],
          "supplierSku": null,
          "skuCodeList": [],
          "skuCode": null,
          "perPage": 200
        },
        statusList: [
          {id: 2, name: '待发货'},
          {id: 3, name: '已送货'},
          {id: 4, name: '已收货'},
          {id: 5, name: '已退货'},
          {id: 6, name: '已完成'},
          {id: 7, name: '已上架'},
          {id: 8, name: '已作废'},
        ],
        currentPage: 1,
        productList: []
      }
    },

    mounted () {
      this.getStoreCode()
    },

    methods: {
      toSearch() {
        if (!this.dateRange) {
          Message.error("请选择时间范围")
          return
        }
        this.reqData.allocateTimeStart = this.dateRange[0]
        this.reqData.allocateTimeEnd = 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()
          }
        })
      },
      changeTab() {
        this.tableData = []
      },
      async getList () {
        this.isLoading = true
        this.reqData.page = 1
        this.tableData = []
        if (this.type == 'urgent') {
          this.reqData.orderType = '1'
        } else {
          this.reqData.orderType = '2'
        }
        await this.getOrderList()
        this.isLoading = false
      },
      async getOrderList() {
        let res = await sendGeiwohuoAPIMessage({
          url: `pfmp/order/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 = {
              orderNo: item.orderId,
              supplierCode: item.goods.supplierCode,
              statusName: item.statusName,
              skc: item.goods.skcName,
              imgPath: item.goods.imgPath,
              addTime: item.addTime
            }
            for (let j = 0; j < item.detail.length; j++) {
              data = {...data, 
                skuCode: item.detail[j].skuCode,
                price: item.detail[j].supplyPrice,
                orderQuantity: item.detail[j].orderQuantity,
                needQuantity: item.detail[j].needQuantity,
                deliveryQuantity: item.detail[j].deliveryQuantity,
                groundingQuantity: item.detail[j].groundingQuantity,
                defectiveQuantity: item.detail[j].defectiveQuantity,
                costPrice: null,
                supplierSku: item.detail[j].supplierSku,
                suffixZh: item.detail[j].suffixZh}
                
                this.tableData.push(data)
            }
    
          }
          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.skuCode)
            })
          }
        } 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 ID", "SKU ID", "图片地址", "货号", "SKU货号", "属性集", "申报价格", "成本价格", "下单数量","需求数量","送货数量", "正品数量", "次品数量", "下单时间"]
        ]

        this.tableData.map(item => {
          data.push([item.orderNo, item.skc, item.skuCode, item.imgPath, item.supplierCode, item.supplierSku, item.suffixZh, item.price, item.costPrice, item.orderQuantity, item.needQuantity, item.deliveryQuantity, item.groundingQuantity, item.defectiveQuantity, 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>
