<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>
          <json-excel
            :data="list"
            :fields="jsonFields"
            :before-generate = "startDownload"
            name="销售数据.xls"
            worksheet="销售统计">
            <el-button type="primary">导出数据</el-button>
          </json-excel>
        </template>
        <ai-table
          ref="table0"
          :isShowPagination="false"
          :tableData="list"
          height="500"
          :col-configs="colConfigs"
          :total="list.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'

  export default {
    name: 'ExportSaleData',

    data () {
      return {
        list: [],
        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: [],
        jsonFields: {
          "商品名称": "productName",
          "SPU": "productId",
          "SKC": "productSkcId",
          "SKU ID": "productSkuId",
          "SKU属性": "className",
          "SKU货号": "skuExtCode",
          "加入站点时长": "onSalesDurationOffline",
          "图片链接": "productSkcPicture",
          "申报价格(CNY)": {
            "field": "supplierPrice",
            callback: (value) => {
              return value /100;
            }
          },
          "开款核价状态": {
            "field": "isVerifyPrice",
            callback: (value) => {
              return value ? '核价通过': '核价未通过 / 无法备货';
            }
          },
          "缺货数量": "lackQuantity",
          "建议备货量": "adviceQuantity",
          "可售天数": "availableSaleDays",
          "库存可售天数": "availableSaleDaysFromInventory",
          "仓内库存可售天数": "warehouseAvailableSaleDays",
          "近7日用户加购数量": "inCartNumber7d",
          "用户累计加购数量": "inCardNumber",
          "已订阅待提醒到货": "nomsgSubsCntCntSth",
          "销售数据 - 今日": "todaySaleVolume",
          "销售数据 - 近7日": "lastSevenDaysSaleVolume",
          "销售数据 - 近30天": "lastThirtyDaysSaleVolume",
          "库存数据 - 仓内可用库存": "inventoryNumInfo.warehouseInventoryNum",
          "库存数据 - 仓内暂不可用库存": "inventoryNumInfo.waitOnShelfNum",
          "库存数据 - 已发货库存": "inventoryNumInfo.waitReceiveNum",
          "库存数据 - 已下单待发货库存": "inventoryNumInfo.waitDeliveryInventoryNum",
          "库存数据 - 待审核备货库存": "inventoryNumInfo.waitApproveInventoryNum",
          "VMI备货单数 - 待发货": "vmiOrderInfo.waitDeliveryNum",
          "VMI备货单数 - 在途单数": "vmiOrderInfo.transportationNum",
          "VMI备货单数 - 发货延迟": "vmiOrderInfo.deliveryDelayNum",
          "VMI备货单数 - 到货延迟": "vmiOrderInfo.arrivalDelayNum",
          "非VMI备货单数 - 待发货": "notVmiOrderInfo.waitDeliveryNum",
          "非VMI备货单数 - 在途单数": "notVmiOrderInfo.transportationNum",
          "非VMI备货单数 - 发货延迟": "notVmiOrderInfo.deliveryDelayNum",
          "非VMI备货单数 - 到货延迟": "notVmiOrderInfo.arrivalDelayNum",
          "备货逻辑": "purchaseConfig",
          "可用库存货值(CNY)": "productTotalPrice",
          "在途库存货值(CNY)": "inroadTotalPrice",
          "店铺名称": "mallName",
          "评分": "mark",
          "是否热销": 'hotTag',
          "生产建议信息 - 建议生产数": 'adviceProduceNum',
          "生产建议信息 - 剩余件数": 'availableProduceNum',
          "类目": 'category'
        },

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

    computed: {
      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: 'todaySale',
            label: '今日销量',
            width: '120px',
            align: 'center'
          },
          {
            prop: 'saleInfoWeek',
            label: '近7天销量',
            width: '120px',
            align: 'center'
          },
          {
            prop: 'saleInfoMonth',
            label: '本月销量',
            width: '120px',
            align: 'center'
          },
          {
            prop: 'saleInfoPreMonth',
            label: '上月销量',
            width: '120px',
            align: 'center'
          },
          
          {
            prop: 'purchaseConfig',
            label: '备货逻辑',
            width: '160px',
            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: {
      beforeGetList() {
        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

        this.isLoading = true
        this.getList()
      },
      getList () {
        sendGeiwohuoAPIMessage({
          url: 'gmpj/goods/goods/list',
          method: 'POST',
          data: {
            "mallStatusList": [
              1
            ],
            "page": this.currentPage,
            "perPage": this.pageSize
          }}).then((res) => {
          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.goodsThumb
              data.mallStatusName = item.mallStatusName
              data.supplierCode = item.supplierCode
              data.skc = item.skc

              for(let j = 0;j < item.sizes.length; j++) {
                let sku = item.sizes[j]
                data = {...data, 
                  ableSaleDays: sku.ableSaleDays,
                  cost: sku.cost,
                  purchaseConfig: (sku.operateTime?sku.operateTime:'/') + '+' + (sku.prepareDay?sku.prepareDay:'/'),
                  saleInfoMonth: sku.saleInfoMonth,
                  saleInfoPreMonth: sku.saleInfoPreMonth,
                  saleInfoWeek: sku.saleInfoWeek,
                  suffixZh: sku.suffixZh,
                  todaySale: sku.todaySale,
                  onWayNum: sku.onWayNum,
                  ivtNum: sku.ivtNum,
                  productTotalPrice: (sku.cost * sku.ivtNum).toFixed(2),
                  inroadTotalPrice: (sku.cost * sku.onWayNum).toFixed(2)}

                this.todayTotal += sku.todaySale
                this.todayMoney += new Number((sku.cost * sku.todaySale).toFixed(2))
                this.todayMoney = new Number(this.todayMoney.toFixed(2))
                this.inventoryTotal += sku.ivtNum
                this.inventoryMoney += new Number((sku.cost * sku.ivtNum).toFixed(2))
                this.inventoryMoney = new Number(this.inventoryMoney.toFixed(2))
                this.inroadTotal += sku.onWayNum
                this.inroadTotalMoney += new Number((sku.cost * sku.onWayNum).toFixed(2))
                this.inroadTotalMoney = new Number(this.inroadTotalMoney.toFixed(2))
                this.list.push(data);
              }
            }

            if (this.pageSize == res.info.list.length) {
              this.currentPage ++
              setTimeout(() => {
                this.getList()
              }, 1500)
            } else {
              this.isLoading = false
              Message.success('销售数据加载完成，可进行导出')
              this.$nextTick(() => { //在数据加载完，重新渲染表格
                this.$refs['table0'].doLayout();
              })
            }
          } else {
            setTimeout(() => {
              this.getList()
            }, 1500)
          }
        }).catch(() => {
          this.isLoading = false
        })
      },
      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;
            }
          }
        })
      }
    }
  }
</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>
