<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">
      <div class="top">
        <div class="item">
          <h2>今日销量</h2>
          <p>{{ todayTotal }}</p>
        </div>
        <div class="item">
          <h2>今日销售额</h2>
          <p>{{ todayMoney }}</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>
          <div class="search-item">
            <el-button type="primary" @click="exportToExcel">导出数据</el-button>
          </div>
        </template>
        <ai-table
          ref="table0"
          :isShowPagination="false"
          :tableData="filteredData"
          height="700"
          :col-configs="colConfigs"
          :total="filteredData.length"
          style="margin-top: 8px;"
          @getList="() => {}">
          <el-table-column slot="goodsThumb" width="120px" label="商品图片" fixed="left">
            <template slot-scope="scope">
              <div>
                <el-image :src="scope.row.goodsThumb" style="width: 40px; height: 40px" class="image" :preview-src-list="[scope.row.goodsThumb]" />
              </div>
            </template>
          </el-table-column>
        </ai-table>
      </ai-card>
    </template>

    
  </ai-list>
</template>

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

  export default {
    name: 'ExportSaleData',

    data () {
      return {
        list: [],
        mallId: '',
        isLoading: false,
        pageSize: 100,
        currentPage: 1,
        todayTotal: 0,
        todayMoney: 0.0,
        inventoryTotal: 0,
        inventoryMoney: 0.0,
        inroadTotal: 0,
        inroadTotalMoney: 0.0,
        deliveryTotal: 0,
        deliveryMoney: 0.0,
        startDate: '',
        endDate: '',
        skuIds: [],
        showTodaySale: false,

        skuSaleNumberFields: {},
        skuSaleNumberList: [],
        downloadSkuSaleNumberDlg: false,
        skuDownloadForm: {
          date: ''
        },
        costList: []
      }
    },

    computed: {
      filteredData() {
        const filteredData = this.list.filter(item => {
          if (this.showTodaySale) {
            return item.todaySale > 0
          }
          return true
        })

        return filteredData
      },
      colConfigs () {
        return [
          {slot: 'goodsThumb',label: '图片'},
          {prop: 'supplierCode',label: '货号',width: '120px',align: 'center',fixed: 'left'},
          {prop: 'suffixZh',label: '规格',width: '160px',align: 'center',fixed: 'left'},
          {prop: 'categoryName',label: '分类',"show-overflow-tooltip": true,width: '100px'},
          {prop: 'mallStatusName',label: '状态',width: '120px',align: 'center'},
          {prop: 'skc',label: 'SKC',width: '160px',align: 'center'},
          {prop: 'ableSaleDays',label: '可售天数',align: 'center'},
          {prop: 'cost',label: '价格',width: '120px',align: 'center'},
          {prop: 'costPrice',label: '成本',width: '120px',align: 'center'},
          {prop: 'todaySale',label: '今日销量',width: '120px',align: 'center',sortable: true,'sort-method': (a, b) => {
              return a.todaySale - b.todaySale
            }},
          {prop: 'todayProfit',label: '利润',width: '120px',align: 'center',sortable: true,'sort-method': (a, b) => {
              return a.todayProfit - b.todayProfit
            }},
          {prop: 'saleInfoWeek',label: '近7天销量',width: '120px',align: 'center'},
          {prop: 'saleInfoMonth',label: '本月销量',width: '120px',align: 'center'},
          {prop: 'onWayNum',label: '在途数量',width: '160px',align: 'center'},
          {prop: 'ivtNum',label: '库存数量',width: '160px',align: 'center'},
          {prop: 'productTotalPrice',label: '库存货值(CNY)',width: '180px',align: 'center',fixed: "right",sortable: true,'sort-method': (a, b) => {
              return a.productTotalPrice - b.productTotalPrice
            }
          },
          {prop: 'inroadTotalPrice',label: '在途货值(CNY)',width: '180px',align: 'center',fixed: "right",sortable: true,'sort-method': (a, b) => {
              return a.inroadTotalPrice - b.inroadTotalPrice
            }
          },
          {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
              }
            }
          }
        ]
      }
    },

    components: {
      JsonExcel
    },

    mounted () {
      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.beforeGetList()
        }
      })
    },

    methods: {
      async getUserInfo() {
        let res = await sendGeiwohuoAPIMessage({
          url: 'sso-prefix/auth/getUser?uuid=' + Date.now(),
          method: 'GET'
        })
        if (res.code == '0' && res.msg == "OK") {
          this.mallId = res.info.merchantCode
        } else if (res.code == 100004 || res.code == 20302) {
          this.isLoading = false
          this.$store.commit("setSheinAlertShow", true)
        }
      },
      async beforeGetList() {
        await this.getUserInfo()
        this.list = []
        this.currentPage = 1
        this.todayMoney = 0.0
        this.todayTotal = 0
        this.inventoryMoney = 0.0
        this.inventoryTotal = 0
        this.inroadTotalMoney = 0.0
        this.inroadTotal = 0

        await this.getSkuCostList()
        this.isLoading = true
        this.getList([])
      },
      async getList (skcList) {
        let res = await sendGeiwohuoAPIMessage({
          url: 'idms/goods-skc/list',
          method: 'POST',
          data: {
            "pageNumber": this.currentPage,
            "pageSize": this.pageSize,
            "supplierCodes": "",
            "skcs": "",
            "spu": "",
            "c7dSaleCntBegin": "",
            "c7dSaleCntEnd": "",
            "goodsLevelIdList": [],
            "supplyStatus": "",
            "shelfStatus": "",
            "categoryIdList": [],
            "skcStockBegin": "",
            "skcStockEnd": "",
            "skuStockBegin": "",
            "skuStockEnd": "",
            "skcSaleDaysBegin": "",
            "skcSaleDaysEnd": "",
            "skuSaleDaysBegin": "",
            "skuSaleDaysEnd": "",
            "planUrgentCountBegin": "",
            "planUrgentCountEnd": "",
            "shelfDateBegin": "",
            "shelfDateEnd": "",
            "stockWarnStatusList": [],
            "labelFakeIdList": [],
            "tspIdList": [],
            "sortBy7dSaleCnt": 2
          }})
          if (res.code == '0' && res.msg == "OK") {
            for(let i = 0;i < res.info.list.length; i++) {
              let item = res.info.list[i];
              let data = {};
              data.categoryName = item.categoryName
              data.goodsThumb = item.picUrl
              data.mallStatusName = item.shelfStatus.name
              data.supplierCode = item.supplierCode
              data.skc = item.skc

              skcList.push(item.skc)

              for(let j = 0;j < item.skuList.length; j++) {
                let sku = item.skuList[j]
                if (sku.attr == '合计') continue
                let temp = {...data, 
                  ableSaleDays: sku.saleDays,
                  cost: sku.price,
                  skuCode: sku.skuCode,
                  purchaseConfig: (sku.goodsDate?sku.goodsDate:'/') + '+' + (sku.stockDays?sku.stockDays:'/'),
                  saleInfoMonth: sku.c30dSaleCnt,
                  saleInfoWeek: sku.c7dSaleCnt,
                  suffixZh: sku.attr,
                  todaySale: sku.totalSaleVolume,
                  onWayNum: sku.transit,
                  ivtNum: sku.stock,
                  costPrice: null,
                  todayProfit: null,
                  productTotalPrice: null,
                  inroadTotalPrice: null}

                this.todayTotal += temp.todaySale
                // this.todayMoney += Math.round((temp.cost * temp.todaySale)*100)/100
                // this.todayMoney = Math.round(this.todayMoney * 100) / 100
                this.inventoryTotal += temp.ivtNum
                // this.inventoryMoney += Math.round((temp.cost * temp.ivtNum)*100)/100
                // this.inventoryMoney = Math.round(this.inventoryMoney*100)/100
                this.inroadTotal += temp.onWayNum
                // this.inroadTotalMoney += Math.round((temp.cost * temp.onWayNum)*100)/100
                // this.inroadTotalMoney = Math.round(this.inroadTotalMoney*100)/100
                this.list.push(temp);
                
              }
            }
            if (this.pageSize == res.info.list.length) {
              this.currentPage ++
              setTimeout(() => {
                this.getList(skcList)
              }, 1500)
            } else {
              let res1 = await sendGeiwohuoAPIMessage({
                url: `idms/goods-skc/price`,
                method: 'POST',
                data: skcList})
              if (res1.code == '0') {
                for (let key in res1.info) {
                  for (let i = 0; i < this.list.length; i++) {
                    if (key == this.list[i].skuCode) {
                      this.list[i].cost = res1.info[key]
                      break
                    }
                  }
                }
              }
              for (let i = 0; i < this.list.length; i++) {
                this.list[i].productTotalPrice = Math.round((this.list[i].cost * this.list[i].ivtNum)*100)/100
                this.list[i].inroadTotalPrice = Math.round((this.list[i].cost * this.list[i].onWayNum)*100)/100
                this.todayMoney += Math.round((this.list[i].cost * this.list[i].todaySale)*100)/100
                this.todayMoney = Math.round(this.todayMoney * 100) / 100
                this.inventoryMoney += Math.round((this.list[i].cost * this.list[i].ivtNum)*100)/100
                this.inventoryMoney = Math.round(this.inventoryMoney*100)/100
                this.inroadTotalMoney += Math.round((this.list[i].cost * this.list[i].onWayNum)*100)/100
                this.inroadTotalMoney = Math.round(this.inroadTotalMoney*100)/100

                for (let j = 0; j < this.costList.length; j++) {
                  if (this.list[i].skuCode == this.costList[j].sku) {

                    this.list[i].costPrice = this.costList[j].costPrice
                    this.list[i].todayProfit = Math.round((this.list[i].cost - this.costList[j].costPrice) * this.list[i].todaySale * 100) / 100
                    break
                  }
                }
              }
              this.isLoading = false
              Message.success('销售数据加载完成，可进行导出')
              this.$nextTick(() => { //在数据加载完，重新渲染表格
                this.$refs['table0'].doLayout();
              })
            }
          } else if (res.code == 100004 || res.code == 20302) {
            this.isLoading = false
            this.$store.commit("setSheinAlertShow", true)
          } else {
            setTimeout(() => {
              this.getList()
            }, 1500)
          }
      },
      async getSkuCostList() {
        let res = await this.$http.post(`/api/skuCost/listAll`, null, {
          params: {
            mallId: this.mallId
          }
        })
        if (res.code == 0) {
          this.costList = res.data
        }
      },
      exportToExcel() {
        // 假设你有一个表格数据的数组
        const data = [
          ["图片地址", "货号", "规格", "分类", "状态", "SKC", "可售天数", "价格", "成本", "今日销量", "利润", "近7天销量", "本月销量", "在途数量", "库存数量", "库存货值", "在途货值", "备货逻辑"]
        ]

        this.filteredData.map(item => {
          data.push([item.goodsThumb, item.supplierCode, item.suffixZh, item.categoryName, item.mallStatusName, item.skc, item.ableSaleDays, item.cost, item.costPrice, item.todaySale, item.todayProfit, item.saleInfoWeek, item.saleInfoMonth, item.onWayNum, item.ivtNum, item.productTotalPrice, item.inroadTotalPrice, item.purchaseConfig])
        })
  
        // 将数据转换为工作表
        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>
