<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 style="width:90px">店铺：</label>
            <el-select v-model="search.mallId" @change="changeMallId" 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>
            <el-button type="button" :class="'el-button el-button--primary'" @click="beginSync">同步</el-button>
          </div>
        </div>
      </template>
    </ai-title>
    <template slot="content">
      <div class="top">
        <div class="item">
          <h2><span><i class="el-icon-time"></i></span>最后一次同步时间</h2>
          <p>{{ lastSyncDate }}</p>
        </div>
        <div class="item">
          <h2>发货总量</h2>
          <p>{{ totalDelivery }}</p>
        </div>
      </div>
      <ai-card title="数据明细" style="padding-bottom: 40px;">
        <!--<template #right>
          <json-excel
            :data="last30Daylist"
            :fields="last30DaysJsonFields"
            :before-generate = "startDownload"
            name="近30天销售数据.xls"
            worksheet="近30天销售统计">
            <el-button type="primary">导出数据</el-button>
          </json-excel>
        </template>-->
        <ai-table
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="total"
            style="margin-top: 8px;"
            :current.sync="search.current" :size.sync="search.size"
            @getList="getDeliveryOrderList">
          </ai-table>
      </ai-card>
    </template>
  </ai-list>
</template>

<script>
import {sendChromeAPIMessage} from '@/api/chromeApi'
// import JsonExcel from 'vue-json-excel'
import {timestampToTime} from '@/utils/date'
import { Message } from 'element-ui'

  export default {
    name: 'ShippingList',

    data () {
      return {
        isLoading: false,
        list: [],
        colConfigs: [
          { prop: 'productName', label: '商品名称', align: 'left' },
          { prop: 'skcExtCode', label: '货号', align: 'left' },
          { prop: 'skcId', label: 'SKC ID', align: 'left' },
          { prop: 'logisticName', label: '物流公司', align: 'left' },
          { prop: 'logisticNumber', label: '物流单号', align: 'left' },
          { prop: 'totalNumber', label: '总件数', align: 'left' },
          { prop: 'deliveryTime', label: '发货时间', width: '180px', fixed: 'right'}
        ],
        currentPage: 1,
        pageSize: 100,

        tableData: [],
        total: 0,
        search: {
          current: 1,
          size: 10,
          mallId: ''
        },
        
        packageNumber: 0,
        lastSyncDate: '',
        totalDelivery: 0,
        lastDeliveryTimestamp: 0
      }
    },

    computed: {
    },

    /*components: {
      JsonExcel
    },*/

    created () {
    },

    methods: {
      changeDataType() {

      },
      getDeliveryOrderList () {
        this.$http.post('/api/deliveryOrder/page',null,{
            params: {
                ...this.search
            }
        }).then(res => {
            this.tableData = res.data.records
            this.total = res.data.total
        })
      },
      changeMallId() {
        if (!this.search.mallId) {
          Message.error("请先选择店铺")
          return
        }
        this.search.current = 1
        this.tableData = []
        this.getDeliveryOrderList()
        this.getInfo()
      },
      getInfo() {
        this.$http.post('/api/deliveryRecord/getLastSyncTime',null, {
          params: {mallId: this.search.mallId}
        }).then(res => {
          if (res.code === 0) {
            this.lastSyncDate = res.data?.lastSyncTime
          }
        })

        this.$http.post('/api/deliveryOrder/totalDelivery',null, {
          params: {mallId: this.search.mallId}
        }).then(res => {
          if (res.code === 0) {
            this.totalDelivery = res.data
          }
        })
      },
      beginSync() {
        if (!this.search.mallId) {
          Message.error("请先选择店铺")
          return
        }
        this.isLoading = true
        this.currentPage = 1
        this.packageNumber = 0
        this.$http.post('/api/deliveryRecord/start',null, {
          params: {mallId: this.search.mallId}
        }).then(res => {
          if (res.code === 0) {
            this.lastDeliveryTimestamp = res.data?.lastDeliveryTime
            this.getList()
          } else {
            this.isLoading = false
            Message.error("同步发货单失败")
          }
        }).catch(() => {
          this.isLoading = false
          Message.error("同步发货单失败")
        })
      },
      end() {
        this.$http.post('/api/deliveryRecord/end',null, {
          params: {mallId: this.search.mallId}
        }).then(res => {
          if (res.code === 0) {
            this.search.current = 1
            this.getDeliveryOrderList()
            this.getInfo()
          }
        })
      },
      getList () {
        let data = {
          "pageNo": this.currentPage,
          "pageSize": this.pageSize,
          "status": 2
        }
        if (this.lastDeliveryTimestamp) {
          data.deliverTimeFrom = this.lastDeliveryTimestamp * 1000
          data.deliverTimeTo = Date.now()
        }
        sendChromeAPIMessage({
          url: 'bgSongbird-api/supplier/deliverGoods/management/pageQueryDeliveryOrders',
          needMallId: true,
          mallId: this.search.mallId,
          anti: true,
          data: data}).then((res) => {
          if (res.errorCode == 1000000) {
            let list = []
            for(let i = 0;i < res.result.list.length; i++) {
              let item = res.result.list[i];
              let data = {};
              data.id = item.deliveryOrderSn
              data.productName = item.subPurchaseOrderBasicVO.productName;
              data.mallId = this.search.mallId
              data.skcId = item.subPurchaseOrderBasicVO.productSkcId;
              data.skcExtCode = item.subPurchaseOrderBasicVO.skcExtCode;
              data.logisticName = item.expressCompany
              data.logisticNumber = item.expressDeliverySn
              data.totalNumber = item.deliverSkcNum
              data.deliveryTime = timestampToTime(item.deliverTime)

              list.push(data)

              this.packageNumber = this.packageNumber + item.receivePackageNum
              setTimeout(() => {
                this.getSkuDetailList(data.id)
              }, 200 * i)
            }

            this.$http.post('/api/deliveryOrder/add',list).then(res => {
                console.log(res)
            })

            if (this.pageSize == res.result.list.length) {
              this.currentPage ++
              setTimeout(() => {
                this.getList()
              }, 1500)
            } else {
              if (this.currentPage == 1 && res.result.list.length == 0) {
                this.isLoading = false
              }
              this.end()
            }
          } else {
            setTimeout(() => {
              this.getList()
            }, 1500)
          }
        }).catch(() => {
          Message.error("同步发货单失败")
          this.isLoading = false
        })
      },
      getSkuDetailList(sn) {
        sendChromeAPIMessage({
          url: 'bgSongbird-api/supplier/deliverGoods/management/queryDeliveryOrderPackageDetailInfo',
          needMallId: true,
          mallId: this.search.mallId,
          anti: true,
          data: {deliveryOrderSn: sn}}).then((res) => {
          if (res.errorCode == 1000000) {
            let list = []
            for(let i = 0;i < res.result.deliveryOrderDetails.length; i++) {
              let item = res.result.deliveryOrderDetails[i]

              let data = {}
              data.deliveryOrderId = sn
              data.productSkuId = item.productSkuId
              data.productSkuNumber = item.deliverSkuNum

              list.push(data)
            }
            this.packageNumber = this.packageNumber - res.result.deliveryOrderDetails.length
            console.log(this.packageNumber)

            if (this.packageNumber < 10) {
              this.isLoading = false
              this.getInfo()
            }
            this.$http.post('/api/deliveryOrderDetail/add',list)
          } else {
            setTimeout(() => {
              this.getSkuDetailList(sn)
            }, 200)
          }
        })
      }
    }
  }
</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;
        }
      }
    }
  }
</style>
