<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="type" @change="changeDataType" placeholder="请选择" size="small">
              <el-option
                key="0"
                label="销售数据"
                value="0">
              </el-option>
              <el-option
                key="1"
                label="近30天销售(按SKU)"
                value="1">
              </el-option>
              <el-option
                key="2"
                label="近30天销售(按SKC)"
                value="2">
              </el-option>
            </el-select>
          </div>
          <div>
            <label style="width:90px">店铺：</label>
            <el-select v-model="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>

        <ai-dialog
          title="导出SKU历史销量"
          :visible.sync="downloadSkuSaleNumberDlg"
          :close-on-click-modal="false"
          width="790px"
          append-to-body
          customFooter
          @close="handleClose">
          <el-form class="ai-form" :model="skuDownloadForm" label-width="160px" ref="skuDownloadForm">
            <el-form-item label="日期范围" style="width: 100%;" prop="date" :rules="[{ required: true, message: '请选择时间范围', trigger: 'blur' }]">
              <el-date-picker
                v-model="skuDownloadForm.date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-form>
          <div class="dialog-footer" slot="footer">
            <el-button @click="downloadSkuSaleNumberDlg = false">取 消</el-button>
            <el-button type="primary" @click="toDownloadSkuSaleNumber">确定</el-button>
          </div>
        </ai-dialog>
      </template>
    </ai-title>
    <template slot="content" v-if="type === '0'">
      <div class="top">
        <div class="item">
          <h2>今日销量/销售额</h2>
          <p>{{ todayTotal }}/{{ todayMoney }}</p>
        </div>
        <div class="item">
          <h2>今日利润/利润率</h2>
          <p>{{ profitMoney }}/{{ profitPercent }}</p>
        </div>
        <div class="item">
          <h2>可用库存总量(件)</h2>
          <p>{{ inventoryTotal }}</p>
        </div>
        <div class="item">
          <h2>可用库存总额</h2>
          <p>{{ inventoryMoney }}</p>
        </div>
        <div class="item">
          <h2><span>在途库存总量(件)<el-tooltip
                  effect="dark"
                  content="包括暂不可用库存以及已发货库存"
                  placement="right">
        <i class="el-icon-question"
           style="font-size: 16px; vertical-align: middle;"></i>
      </el-tooltip></span></h2>
          <p>{{ inroadTotal }}</p>
        </div>
        <div class="item">
          <h2><span>在途库存总额<el-tooltip
                  effect="dark"
                  content="(暂不可用库存+已发货库存)*申报价格"
                  placement="right">
        <i class="el-icon-question"
           style="font-size: 16px; vertical-align: middle;"></i>
      </el-tooltip></span></h2>
          <p>{{ inroadTotalMoney }}</p>
        </div>
      </div>
      <ai-card title="数据明细" style="padding-bottom: 40px;">
        <template #right>
          <div class="search-item" style="width: 160px;">
            <el-checkbox v-model="showTodaySale">只显示今日有销量</el-checkbox>
          </div>
          <el-button style="margin-right: 10px;" v-if="type === '0'" type="primary" @click="downloadSaleData">导出数据</el-button>
          <json-excel
            :data="skuSaleNumberList"
            v-show="false"
            :fields="skuSaleNumberFields"
            :before-generate = "startSkuSaleNumberDownload"
            name="SKU历史销量.xls"
            worksheet="SKU历史销量">
            <el-button type="primary" id="downloadSkuSaleNumber"></el-button>
          </json-excel>
          <el-button type="primary" :disabled="!mallId" @click="toDownload">导出SKU历史销量</el-button>
        </template>
        <ai-table
          ref="table0"
          :isShowPagination="false"
          :tableData="filteredData"
          height="700"
          :col-configs="colConfigs"
          :total="filteredData.length"
          style="margin-top: 8px;"
          @getList="() => {}">
        </ai-table>
      </ai-card>
    </template>
    <template slot="content" v-if="type === '1'">
      <ai-card title="数据明细" style="padding-bottom: 40px;">
        <template #right>
          <json-excel
            v-if="type === '1'"
            :data="last30DaySkuList"
            :fields="last30DaysSkuJsonFields"
            :before-generate = "startDownload"
            name="近30天销售数据_按SKU.xls"
            worksheet="近30天销售统计_按SKU">
            <el-button type="primary">导出数据</el-button>
          </json-excel>
        </template>
        <ai-table
          ref="table1"
          :isShowPagination="false"
          :tableData="last30DaySkuList"
          height="500"
          :col-configs="col30DaysSkuConfigs"
          :total="last30DaySkuList.length"
          style="margin-top: 8px;"
          @getList="() => {}">
        </ai-table>
      </ai-card>
    </template>
    <template slot="content" v-if="type === '2'">
      <ai-card title="数据明细" style="padding-bottom: 40px;">
        <template #right>
          <json-excel
            v-if="type === '2'"
            :data="last30DaySkcList"
            :fields="last30DaysSkcJsonFields"
            :before-generate = "startDownload"
            name="近30天销售数据_按SKC.xls"
            worksheet="近30天销售统计_按SKC">
            <el-button type="primary">导出数据</el-button>
          </json-excel>
        </template>
        <ai-table
          ref="table2"
          :isShowPagination="false"
          :tableData="last30DaySkcList"
          height="500"
          :col-configs="col30DaysSkcConfigs"
          :total="last30DaySkcList.length"
          style="margin-top: 8px;"
          @getList="() => {}">
        </ai-table>
      </ai-card>
    </template>

    
  </ai-list>
</template>

<script>
import { mapState } from 'vuex'
import {sendChromeAPIMessage} from '@/api/chromeApi'
import JsonExcel from 'vue-json-excel'
import {formatDate} from '@/utils/date'
import { Message } from 'element-ui'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

  export default {
    name: 'ExportSaleData',

    data () {
      return {
        list: [],
        last30DaySkcList: [],
        last30DaySkuList: [],
        mallId: '',
        mallName: '',
        type: '0',
        isLoading: false,
        pageSize: 50,
        currentPage: 1,
        todayTotal: 0,
        todayMoney: 0.0,
        profitMoney: 0.0,
        profitPercent: 0,
        inventoryTotal: 0,
        inventoryMoney: 0.0,
        inroadTotal: 0,
        inroadTotalMoney: 0.0,
        costList: [],
        startDate: '',
        endDate: '',
        skuIds: [],
        
        skuSaleNumberFields: {},
        skuSaleNumberList: [],
        downloadSkuSaleNumberDlg: false,
        skuDownloadForm: {
          date: ''
        },
        showTodaySale: false
      }
    },

    computed: {
      ...mapState(['mallList']),
      filteredData() {
        const filteredData = this.list.filter(item => {
          if (this.showTodaySale) {
            return item.todaySaleVolume > 0
          }
          return true
        })

        return filteredData
      },
      colConfigs () {
        return [
          {
            prop: 'productName',
            label: '商品名称',
            "show-overflow-tooltip": true,
            width: '280px',
            align: 'left',
            fixed: 'left'
          },
          {
            prop: 'mallName',
            label: '店铺名称',
            "show-overflow-tooltip": true,
            width: '120px',
            align: 'left',
            fixed: 'left'
          },
          {
            prop: 'mark',
            label: '评分',
            "show-overflow-tooltip": true,
            width: '80px',
            align: 'left'
          },
          {
            prop: 'hotTag',
            label: '是否热销',
            "show-overflow-tooltip": true,
            width: '80px',
            align: 'left'
          },
          {
            prop: 'productId',
            label: 'SPU',
            width: '120px',
            align: 'center'
          },
          {
            prop: 'productSkcId',
            label: 'SKC',
            width: '120px',
            align: 'center'
          },
          {
            prop: 'productSkuId',
            label: 'SKU ID',
            width: '120px',
            align: 'center'
          },
          {
            prop: 'className',
            label: 'SKU属性',
            align: 'center'
          },
          {
            prop: 'skuExtCode',
            label: 'SKU货号',
            width: '120px',
            align: 'center'
          },
          {
            prop: 'todaySaleVolume',
            label: '今日销量',
            width: '120px',
            align: 'center',
            sortable: true,
            'sort-method': (a, b) => {
              return a.todaySaleVolume - b.todaySaleVolume
            }
          },
          {
            prop: 'lastSevenDaysSaleVolume',
            label: '近7天',
            width: '120px',
            align: 'center',
            sortable: true,
            'sort-method': (a, b) => {
              return a.lastSevenDaysSaleVolume - b.lastSevenDaysSaleVolume
            }
          },
          {
            prop: 'lastThirtyDaysSaleVolume',
            label: '近30天',
            width: '120px',
            align: 'center',
            sortable: true,
            'sort-method': (a, b) => {
              return a.lastThirtyDaysSaleVolume - b.lastThirtyDaysSaleVolume
            }
          },
          {
            prop: 'saleMoney',
            label: '销售额',
            width: '120px',
            align: 'center'
          },
          {
            prop: 'profitMoney',
            label: '利润',
            width: '120px',
            align: 'center',
            sortable: true,
            'sort-method': (a, b) => {
              return a.profitMoney - b.profitMoney
            }
          },
          {
            prop: 'profitPercent',
            label: '利润率(%)',
            width: '120px',
            align: 'center'
          },
          {
            prop: 'onSalesDurationOffline',
            label: '加入站点时长',
            width: '160px',
            align: 'center'
          },
          {
            prop: 'isVerifyPrice',
            label: '开款核价状态',
            width: '160px',
            align: 'center',
            format: v => v ? '核价通过': '核价未通过 / 无法备货'
          },
          {
            prop: 'supplierPrice',
            label: '申报价格(CNY)',
            width: '160px',
            align: 'center',
            format: v => v / 100,
            fixed: "right"
          },
          {
            prop: 'warehouseInventoryNum',
            label: '仓内可用库存',
            width: '160px',
            align: 'center',
            sortable: true,
            'sort-method': (a, b) => {
              return a.warehouseInventoryNum - b.warehouseInventoryNum
            }
          },
          {
            prop: 'productTotalPrice',
            label: '可用库存货值(CNY)',
            width: '180px',
            align: 'center',
            fixed: "right",
            sortable: true,
            'sort-method': (a, b) => {
              return a.productTotalPrice - b.productTotalPrice
            }
          },
          {
            prop: 'purchaseConfig',
            label: '备货逻辑',
            align: 'center',
            width: '120px',
            fixed: "right",
            sortable: true,
            'sort-method': (a, b) => {
              if (a.purchaseConfig > b.purchaseConfig) {
                return 1
              } else if (a.purchaseConfig == b.purchaseConfig) {
                return 0
              } else {
                return -1
              }
            }
          }


        ]
      },
      col30DaysSkcConfigs () {
        let config = [
          {
            prop: 'productName',
            label: '商品名称',
            "show-overflow-tooltip": true,
            width: '300px',
            align: 'left',
            fixed: 'left'
          },
          {
            prop: 'mallName',
            label: '店铺名称',
            "show-overflow-tooltip": true,
            width: '120px',
            align: 'left',
            fixed: 'left'
          },
          {
            prop: 'productId',
            label: 'SPU',
            width: '120px',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'productSkcId',
            label: 'SKC',
            width: '120px',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'skcExtCode',
            label: 'SKC货号',
            width: '120px',
            align: 'center',
            fixed: 'left'
          }
        ]

        let date = new Date()
        date.setDate(date.getDate())
        for (let i = 0; i < 30; i++) {
          date.setDate(date.getDate() - 1)
          let dateStr = formatDate(date)
          config.push({
            prop: dateStr,
            label: dateStr,
            width: '100px',
            align: 'center',
            sortable: true,
            'sort-method': (a, b) => {
              if (a > b) {
                return 1
              } else if (a == b) {
                return 0
              } else {
                return -1
              }
            }})
        }

        return config
      },
      last30DaysSkcJsonFields () {
        let jsonFields = {
          "商品名称": "productName",
          "店铺名称": "mallName",
          "SPU": "productId",
          "SKC": "productSkcId",
          "SKC货号": "skcExtCode",
          "图片链接": "productSkcPicture"
        }

        let date = new Date()
        date.setDate(date.getDate() )
        for (let i = 0; i < 30; i++) {
          date.setDate(date.getDate() - 1)
          let dateStr = formatDate(date)
          jsonFields[dateStr] = dateStr
        }

        return jsonFields
      },
      col30DaysSkuConfigs () {
        let config = [
          {
            prop: 'productName',
            label: '商品名称',
            "show-overflow-tooltip": true,
            width: '300px',
            align: 'left',
            fixed: 'left'
          },
          {
            prop: 'mallName',
            label: '店铺名称',
            "show-overflow-tooltip": true,
            width: '120px',
            align: 'left',
            fixed: 'left'
          },
          {
            prop: 'productId',
            label: 'SPU',
            width: '120px',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'productSkcId',
            label: 'SKC',
            width: '120px',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'skcExtCode',
            label: 'SKC货号',
            width: '120px',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'supplierPrice',
            label: '申报价格',
            width: '120px',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'productSkuId',
            label: 'SKU ID',
            width: '120px',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'skuExtCode',
            label: 'SKU货号',
            width: '120px',
            align: 'center',
            fixed: 'left'
          }
        ]

        let date = new Date()
        date.setDate(date.getDate())
        for (let i = 0; i < 30; i++) {
          date.setDate(date.getDate() - 1)
          let dateStr = formatDate(date)
          config.push({
            prop: dateStr,
            label: dateStr,
            width: '100px',
            align: 'center',
            sortable: true,
            'sort-method': (a, b) => {
              if (a > b) {
                return 1
              } else if (a == b) {
                return 0
              } else {
                return -1
              }
            }})
        }

        return config
      },
      last30DaysSkuJsonFields () {
        let jsonFields = {
          "商品名称": "productName",
          "店铺名称": "mallName",
          "SPU": "productId",
          "SKC": "productSkcId",
          "SKC货号": "skcExtCode",
          "SKU ID": "productSkuId",
          "SKU货号": "skuExtCode",
          "申报价格": "supplierPrice",
          "图片链接": "productSkcPicture"
        }

        let date = new Date()
        date.setDate(date.getDate() )
        for (let i = 0; i < 30; i++) {
          date.setDate(date.getDate() - 1)
          let dateStr = formatDate(date)
          jsonFields[dateStr] = dateStr
        }

        return jsonFields
      }
    },

    components: {
      JsonExcel
    },

    created () {
      let date = new Date()
      date.setDate(date.getDate() - 30)
      this.startDate = formatDate(date)
      date.setDate(date.getDate() + 29)
      this.endDate = formatDate(date)
    },

    methods: {
      changeDataType() {
        this.$nextTick(() => { //在数据加载完，重新渲染表格
            this.$refs['table'+this.type].doLayout();
        })
      },
      beforeGetList() {
        this.list = []
        this.currentPage = 1
        this.todayMoney = 0.0
        this.todayTotal = 0
        this.profitMoney = 0.0
        this.profitPercent = 0
        this.inventoryMoney = 0.0
        this.inventoryTotal = 0
        this.inroadTotalMoney = 0.0
        this.inroadTotal = 0
        if (!this.mallId) {
          Message.error("请先选择店铺")
          return
        }
        let mallInfo = this.mallList.filter(item => {
          return item.mallId == this.mallId
        })
        this.mallName = mallInfo[0].mallName

        this.isLoading = true
        this.$userCheck(this.mallId).then(() => {
          this.last30DaySkcList = []
          this.getSkuCostList()
          this.getList()
        }).catch((err) => {
          this.mallId = ''
          console.log(err)
          this.isLoading = false
        })
      },
      getSkuCostList() {
        this.$http.post(`/api/skuCost/listAll`, null, {
          params: {
            mallId: this.mallId
          }
        }).then(res => {
          if (res.code == 0) {
            this.costList = res.data
          }
        })
      },
      getList () {
        sendChromeAPIMessage({
          url: 'marvel-mms/cn/api/kiana/venom/sales/management/listWarehouse',
          needMallId: true,
          anti: true,
          mallId: this.mallId,
          data: {
            pageNo: this.currentPage,
            pageSize: this.pageSize,
            isLack: 0,
            priceAdjustRecentDays: 7
        }}).then((res) => {
          if (res.errorCode == 1000000) {
            for(let i = 0;i < res.result.subOrderList.length; i++) {
              let item = res.result.subOrderList[i];
              let data = {};
              data.productName = item.productName;
              data.category = item.category;
              data.productId = item.productId;
              data.productSkcId = item.productSkcId;
              data.skcExtCode = item.skcExtCode;
              data.purchaseConfig = item.purchaseConfig;
              data.productSkcPicture = item.productSkcPicture;
              data.mark = item.mark.toFixed(1)
              data.hotTag = item.hotTag ? '是': '否'
              data.mallName = this.mallName;

              this.last30DaySkcList.push({
                productName: item.productName,
                mallName: this.mallName,
                productId: item.productId,
                productSkcId: item.productSkcId,
                skcExtCode: item.skcExtCode,
                productSkcPicture: item.productSkcPicture
              })

              if (item.onSalesDurationOffline == 0) {
                data.onSalesDurationOffline = '-天'
              } else {
                data.onSalesDurationOffline = item.onSalesDurationOffline + '天'
              }


              for(let j = 0;j < item.skuQuantityDetailList.length; j++) {
                let costPrice = this.getCostPrice(item.skuQuantityDetailList[j].productSkuId)
                let saleMoney = Math.round(item.skuQuantityDetailList[j].todaySaleVolume * item.skuQuantityDetailList[j].supplierPrice) /100
                let profitMoney = Math.round(item.skuQuantityDetailList[j].todaySaleVolume * (item.skuQuantityDetailList[j].supplierPrice / 100 - costPrice) * 100) /100
                let profitPercent = Math.round(profitMoney / saleMoney * 10000) /100
                data = {...data, ...item.skuQuantityDetailList[j],
                  saleMoney: saleMoney,
                  profitMoney: profitMoney,
                  profitPercent: profitPercent,
                  productTotalPrice: ((item.skuQuantityDetailList[j].supplierPrice / 100) * item.skuQuantityDetailList[j].inventoryNumInfo.warehouseInventoryNum).toFixed(2),
                  inroadTotalPrice: ((item.skuQuantityDetailList[j].supplierPrice / 100) * (item.skuQuantityDetailList[j].inventoryNumInfo.waitOnShelfNum + item.skuQuantityDetailList[j].inventoryNumInfo.waitReceiveNum)).toFixed(2),
                  warehouseInventoryNum: item.skuQuantityDetailList[j].inventoryNumInfo.warehouseInventoryNum}
                  
                  this.todayTotal += item.skuQuantityDetailList[j].todaySaleVolume
                  this.profitMoney += item.skuQuantityDetailList[j].todaySaleVolume * (item.skuQuantityDetailList[j].supplierPrice / 100 - costPrice)
                  this.todayMoney += (item.skuQuantityDetailList[j].supplierPrice / 100) * item.skuQuantityDetailList[j].todaySaleVolume
                  this.inventoryTotal += item.skuQuantityDetailList[j].inventoryNumInfo.warehouseInventoryNum
                  this.inventoryMoney += (item.skuQuantityDetailList[j].supplierPrice / 100) * item.skuQuantityDetailList[j].inventoryNumInfo.warehouseInventoryNum
                  this.inroadTotal += (item.skuQuantityDetailList[j].inventoryNumInfo.waitOnShelfNum + item.skuQuantityDetailList[j].inventoryNumInfo.waitReceiveNum)
                  this.inroadTotalMoney += (item.skuQuantityDetailList[j].supplierPrice / 100) * (item.skuQuantityDetailList[j].inventoryNumInfo.waitOnShelfNum + item.skuQuantityDetailList[j].inventoryNumInfo.waitReceiveNum)
                  this.adviceProduceNum = item.skuQuantityDetailList[j].adviceProduceNum || '-'
                  this.availableProduceNum = item.skuQuantityDetailList[j].availableProduceNum || '-'
                  this.list.push(data);
              }
              
            }
            if (this.pageSize == res.result.subOrderList.length) {
              this.currentPage ++
              setTimeout(() => {
                this.getList()
              }, 1500)
            } else {
              this.profitMoney = Math.round(this.profitMoney * 100) / 100
              this.todayMoney = Math.round(this.todayMoney * 100) / 100
              this.profitPercent = Math.round((this.profitMoney / this.todayMoney) * 10000) /100 + '%'
              this.inventoryMoney = Math.round(this.inventoryMoney * 100) / 100
              this.inroadTotalMoney = Math.round(this.inroadTotalMoney * 100) / 100

              this.isLoading = false
              Message.success('销售数据加载完成，可进行导出')

              // 初始化SKC数据列表
              this.last30DaySkcList = this.last30DaySkcList.map(item => {
                let date = new Date()
                date.setDate(date.getDate() - 31)
                for (let i = 0; i < 30; i++) {
                  date.setDate(date.getDate() + 1)
                  let dateStr = formatDate(date)
                  item[dateStr] = 0
                }
                return item
              })

              // 初始化SKU数据列表
              this.last30DaySkuList = this.list.map(item => {
                let temp = {
                  productName: item.productName,
                  mallName: this.mallName,
                  productId: item.productId,
                  productSkcId: item.productSkcId,
                  productSkuId: item.productSkuId,
                  skuExtCode: item.skuExtCode,
                  skcExtCode: item.skcExtCode,
                  productSkcPicture: item.productSkcPicture,
                  supplierPrice: this.getSupplierPrice(item.productSkuId)
                }
                let date = new Date()
                date.setDate(date.getDate() - 31)
                for (let i = 0; i < 30; i++) {
                  date.setDate(date.getDate() + 1)
                  let dateStr = formatDate(date)
                  temp[dateStr] = 0
                }
                return temp
              })
              this.skuIds = this.list.map(item => {
                return item.productSkuId
              })
              this.getSkuDetailList(0)
            }
          } else {
            setTimeout(() => {
              this.getList()
            }, 1500)
            // Message.error("【拼多多】" + res.errorMsg + ", 请重新尝试加载")
          }
        }).catch(() => {
          this.isLoading = false
        })
      },
      getSkuDetailList (page) {
        let tempSkuId = []
        let i = page * 500
        let j = 0
        for (; i < this.skuIds.length; i++) {
          tempSkuId.push(this.skuIds[i])
          j ++
          if (j == 500) break
        }
        if (tempSkuId.length == 0) return
        sendChromeAPIMessage({
          url: 'oms/bg/venom/api/supplier/sales/management/querySkuSalesNumber',
          needMallId: true,
          mallId: this.mallId,
          data: {
            "productSkuIds": tempSkuId,
            "startDate": this.startDate,
            // "startDate": '2023-01-17',
            "endDate": this.endDate
          }}).then((res) => {
          if (res.errorCode == 1000000) {
            for (let i = 0; i < res.result.length; i++) {
              for (let j = 0; j < this.last30DaySkuList.length; j++) {
                if (this.last30DaySkuList[j].productSkuId == res.result[i].prodSkuId) {
                  this.last30DaySkuList[j][res.result[i].date] = res.result[i].salesNumber

                  for (let k = 0; k < this.last30DaySkcList.length; k++) {
                    if (this.last30DaySkcList[k].productSkcId == this.last30DaySkuList[j].productSkcId) {
                      this.last30DaySkcList[k][res.result[i].date] = this.last30DaySkcList[k][res.result[i].date] + res.result[i].salesNumber
                      break
                    }
                  }
                  break
                }
              }
            }
            this.getSkuDetailList(page + 1)
          } else {
            setTimeout(() => {
              this.getSkuDetailList(page)
            }, 1500)
          }
        })
      },

      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;
            }
          }
        })
      },
      toDownload() {
        this.downloadSkuSaleNumberDlg = true
      },
      startSkuSaleNumberDownload() {

      },
      handleClose() {
        this.downloadSkuSaleNumberDlg = false
      },
      async toDownloadSkuSaleNumber() {
        this.downloadSkuSaleNumberDlg = false
        this.isLoading = true
        if (!this.skuDownloadForm.date) {
          Message.error("请选择时间")
          return
        }
        let beginDateStr = formatDate(this.skuDownloadForm.date[0])
        let endDateStr = formatDate(this.skuDownloadForm.date[1])

        let temp = {}
        temp = {
          'SKC': 'skc',
          'SKU': 'sku',
          'SKU货号': 'skuExtCode',
          '申报价格': 'supplierPrice'
        }
        let beginTime = new Date(this.skuDownloadForm.date[0])
        let endTime = new Date(this.skuDownloadForm.date[1])
        for (; beginTime.getTime() <= endTime.getTime(); ) {
          let dateStr = formatDate(endTime)
          temp[dateStr] = dateStr

          endTime.setDate(endTime.getDate() - 1)
        }
        this.skuSaleNumberFields = temp

        let tempSkuList = this.list.filter(item => {
          return item.onSalesDurationOffline != '-天'
        })
        let tempSkuIds = []
        tempSkuList.map(i => {
          tempSkuIds.push(i.productSkuId) 
        })

        this.skuSaleNumberList = []
        this.list.map(item => {
          if (item.onSalesDurationOffline != '-天') {
            let temp = {
              sku: item.productSkuId,
              skc: item.productSkcId,
              skuExtCode: item.skuExtCode,
              supplierPrice: this.getSupplierPrice(item.productSkuId)
            }
            beginTime = new Date(this.skuDownloadForm.date[0])
            endTime = new Date(this.skuDownloadForm.date[1])

            for (; beginTime.getTime() <= endTime.getTime(); ) {
              let dateStr = formatDate(endTime)
              temp[dateStr] = 0

              endTime.setDate(endTime.getDate() - 1)
            }

            this.skuSaleNumberList.push(temp)
          }
        })

        let reqSkusIds = [], pageSize = 200
        for (let i = 0; i < tempSkuIds.length; i++) {
          reqSkusIds.push(tempSkuIds[i])
          if (reqSkusIds.length % pageSize == 0 || ((i+1) == tempSkuIds.length)) {
            let res = await sendChromeAPIMessage({
              url: 'oms/bg/venom/api/supplier/sales/management/querySkuSalesNumber',
              needMallId: true,
              mallId: this.mallId,
              data: {
                "productSkuIds": reqSkusIds,
                "startDate": beginDateStr,
                "endDate": endDateStr
            }})

            if (res.success) {
              res.result.map(item => {
                for (let i = 0; i < this.skuSaleNumberList.length; i++) {
                  if (this.skuSaleNumberList[i].sku == item.prodSkuId) {
                    this.skuSaleNumberList[i][item.date] = item.salesNumber
                    break
                  }
                }
              })
            } else {
              this.isLoading = false
              Message.error("获取SKU历史销量数据失败")
              break
            }

            if ((i+1) == tempSkuIds.length) {
              document.getElementById('downloadSkuSaleNumber').click()
              this.isLoading = false
            }
            reqSkusIds = []
          }
        }
      },
      getSupplierPrice(productSkuId) {
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].productSkuId == productSkuId) {
            return this.list[i].supplierPrice / 100
          }
        }
        return 0
      },
      getCostPrice(productSkuId) {
        for (let i = 0; i < this.costList.length; i++) {
          if (this.costList[i].sku == productSkuId) {
            return this.costList[i].costPrice
          }
        }
        return 0
      },
      async downloadSaleData() {
        let res = await this.$http.post('/api/malluser/info')
        if (res.code == 0) {
          this.$store.commit('setUserInfo', res.data)
          if (res.data.flag != 1) {
            Message.error('您的账号未激活或已失效，请激活后使用')
            this.$store.commit('setActiveDlgShow', true)
            return;
          }
        }

        // 假设你有一个表格数据的数组
        const data = [
          ["商品名称", "SPU", "SKC", "SKU ID", "SKU属性", "SKU货号", "加入站点时长", "图片链接", "申报价格(CNY)", "开款核价状态", "缺货数量", 
          "建议备货量", "可售天数", "库存可售天数", "仓内库存可售天数","近7日用户加购数量", "用户累计加购数量", "已订阅待提醒到货", "销售数据 - 今日", 
          "销售数据 - 近7天", "销售数据 - 近30天", "销售数据 - 今日销售额", "销售数据 - 利润", "销售数据 - 利润率", "库存数据 - 仓内可用库存", 
          "库存数据 - 仓内暂不可用库存", "库存数据 - 已发货库存", "库存数据 - 已下单待发货库存", "库存数据 - 待审核备货库存", "VMI备货单数 - 待发货", 
          "VMI备货单数 - 在途单数", "VMI备货单数 - 发货延迟", "VMI备货单数 - 到货延迟", "非VMI备货单数 - 待发货", "非VMI备货单数 - 在途单数", 
          "非VMI备货单数 - 发货延迟", "非VMI备货单数 - 到货延迟", "备货逻辑", "可用库存货值(CNY)", "在途库存货值(CNY)", "店铺名称", "评分",
          "是否热销", "生产建议信息 - 建议生产数", "生产建议信息 - 剩余件数", "类目"]
        ]

        this.list.map(item => {
          data.push([item.productName, item.productId, item.productSkcId, item.productSkuId, item.className, item.skuExtCode, item.onSalesDurationOffline, item.productSkcPicture, item.supplierPrice/ 100, item.isVerifyPrice? '核价通过': '核价未通过 / 无法备货', item.lackQuantity,
          item.adviceQuantity, item.availableSaleDays, item.availableSaleDaysFromInventory, item.warehouseAvailableSaleDays, item.inCartNumber7d, item.inCardNumber, item.nomsgSubsCntCntSth, item.todaySaleVolume,
          item.lastSevenDaysSaleVolume, item.lastThirtyDaysSaleVolume, item.saleMoney, item.profitMoney, item.profitPercent, item.inventoryNumInfo?.warehouseInventoryNum, 
          item.inventoryNumInfo?.waitOnShelfNum, item.inventoryNumInfo?.waitReceiveNum, item.inventoryNumInfo?.waitDeliveryInventoryNum, item.inventoryNumInfo?.waitApproveInventoryNum, item.vmiOrderInfo?.waitDeliveryNum,
          item.vmiOrderInfo?.transportationNum, item.vmiOrderInfo?.deliveryDelayNum, item.vmiOrderInfo?.arrivalDelayNum, item.notVmiOrderInfo?.waitDeliveryNum, item.notVmiOrderInfo?.transportationNum,
          item.notVmiOrderInfo?.deliveryDelayNum, item.notVmiOrderInfo?.arrivalDelayNum, item.purchaseConfig, item.productTotalPrice, item.inroadTotalPrice, item.mallName, item.mark,
          item.hotTag, item.adviceProduceNum, item.availableProduceNum, item.category])
        })
  
        // 将数据转换为工作表
        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;
      }
    }

    .top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 24px;

      .item {
        flex: 1;
        margin-right: 20px;
        padding: 16px 24px;
        background: #FFF;
        box-shadow: 0px 4px 6px -2px rgba(15, 15, 21, 0.15);
        border-radius: 4px;

        &:last-child {
          margin-right: 0;
        }

        &:nth-of-type(1) {
          color: #2266ff;
        }

        &:nth-of-type(2) {
          color: #f8b426;
        }
        &:nth-of-type(3) {
          color: #21aa99;
        }
        &:nth-of-type(4) {
          color: #F46;
        }
        &:nth-of-type(5) {
          color: #11A265;
        }
        h2 {
          margin-bottom: 30px;
          font-size: 16px;
          color: #999;
        }

        p {
          font-weight: 600;
          font-size: 28px;
        }
      }
    }
  }
.like {
    cursor: pointer;
    font-size: 25px;
    display: inline-block;
  }
</style>
