<template>
  <div>
    <ai-list class="list" v-loading="isLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
      <ai-title
        slot="title"
        title="抢仓发货"
        tips="请先在当前浏览器登录“拼多多跨境卖家中心”，期间保持登录状态"
        isShowBottomBorder>
      </ai-title>
      <template slot="content">
        <ai-search-bar>
          <template #left>
            <el-dropdown @command="handleClick">
              <el-button type="primary" :disabled="isBegin">添加备货单</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="byStore">按店铺添加</el-dropdown-item>
                <el-dropdown-item command="loadAll">一键添加所有</el-dropdown-item>
              </el-dropdown-menu>
              <!--<el-button type="primary" :disabled="isBegin" @click="isShow = true">添加备货单</el-button>
              <el-button type="primary" :disabled="isBegin" @click="loadAll">一键加载全部</el-button>-->
            </el-dropdown>
            <el-button v-if="!isBegin" type="button" :class="'el-button el-button--primary'" @click="beginRobConfirm">开始抢仓</el-button>
            <el-button v-else type="button" :icon="isBegin? 'el-icon-loading': ''" :class="isBegin ? 'el-button el-button--danger': 'el-button el-button--primary'" @click="beginRob()">{{  `结束抢仓(${choosedList.length}/${robTotal})` }}</el-button>
            
          </template>
          <template #right>
            <el-badge v-if="networkErrorCount > 0" :value="networkErrorCount" style="margin-right: 10px">
              <div class="tips">
                <div></div>
              </div>
            </el-badge>
            <el-badge v-if="errorList.length > 0" :value="errorList.length" style="margin-right: 10px">
              <div class="errorTips" style="cursor: pointer" @click="errorDlgShow = true">
                <div></div>
              </div>
            </el-badge>
            <el-badge :value="successList.length" class="item">
              <el-button :icon="'el-icon-tickets'" @click="successDlgShow = true" circle></el-button>
            </el-badge>
          </template>
        </ai-search-bar>
        <ai-table
          :tableData="choosedList"
          :col-configs="robColConfigs"
          :total="total"
          :isShowPagination="false"
          style="margin-top: 8px;">
          <el-table-column slot="productName" width="480px" label="商品信息" align="center">
            <template slot-scope="scope">
              <div class="product">
                <img :src="scope.row.productSkcPicture">
                  <div class="right">
                    <div>备货母单号: {{ scope.row.originalPurchaseOrderSn }}</div>
                    <el-tooltip effect="dark" :content="scope.row.productName" placement="top-start">
                      <div class="textoverflow">{{ scope.row.productName }}</div>
                    </el-tooltip>
                    <div>SKC: {{ scope.row.productSkcId }}</div>
                    <div>货号: {{ scope.row.productSn }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column slot="robInfo" label="抢仓信息" width="140px" show-overflow-tooltip fixed="right" align="center">
            <template slot-scope="scope">
              <div data-testid="beast-core-box" style="margin-right: 2px;">
                已抢仓 <div style="color: red; display: inline;">{{ scope.row.robTotal }}</div> 次
              </div>
            </template>
          </el-table-column>
          <el-table-column slot="className" label="SKU信息" width="440px" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <div class="order-manage_skuInfo__FW-Nd" v-for="(item, index) in scope.row.detailList" :key="index">
                <div>
                  <div data-testid="beast-core-box" class="outerWrapper-1-3-1 outerWrapper-d18-1-3-20 index-module__image-preview___2fiZX">
                    <div class="index-module__img___p3B1N" :style="getStyle(item.thumbUrlList[0])"></div>
                  </div>
                </div>
                <div class="order-manage_contentInfo__1Cjd6" style="max-width: 150px;">
                  <div class="order-manage_title__1VTO5">属性：{{ item.className }}</div>
                  <div>下单数量：{{ item.purchaseQuantity }}</div>
                  <div>SKU ID： {{ item.productSkuId }}</div>
                  <div class="order-manage_productSku__XP_ke">SKU 货号： {{ item.extCode }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column slot="status" label="状态" show-overflow-tooltip align="center" width="120px">
            <template slot-scope="scope">
              <div data-testid="beast-core-box" class="outerWrapper-1-3-1 outerWrapper dot-module__dot___M-RuH " style="margin-right: 2px;">
                <div class="dot-module__circle___2l2UV" style="background-color: var(--pc-dot-warn-bg-color,#ff6800);"></div>待发货
              </div>
            </template>
          </el-table-column>
          <el-table-column slot="options" label="操作" width="80px" v-if="!isBegin" show-overflow-tooltip align="center" fixed="right">
            <template slot-scope="{ row }">
              <div class="table-options">
                <el-button type="text" @click="remove(row.subPurchaseOrderSn)">移除</el-button>
              </div>
            </template>
            </el-table-column>
        </ai-table>
        <AiDialog
          title="添加备货单"
          :visible.sync="isShow"
          :close-on-click-modal="false"
          customFooter
          @confirm="onConfirm"
          width="1290px">
          <ai-search-bar>
            <template #left>
              <div class="search-item">
                <label style="width:90px">店铺：</label>
                <el-select v-model="mallId" placeholder="请选择" @change="mallChange">
                  <el-option
                    v-for="item in mallList"
                    :key="item.mallId"
                    :label="item.mallName"
                    :value="item.mallId">
                    {{ item.mallName }}
                  </el-option>
                </el-select>
              </div>
              <div class="search-item">
                <label style="width:90px">SKC：</label>
                <el-input size="small" style="display: inline" placeholder="请输入SKC，多个SKC用,隔开" v-model="skc"></el-input>
              </div>
              <div class="search-item">
                <label style="width:90px">备货单号：</label>
                <el-input size="small" style="display: inline" placeholder="请输入备货单号，多个备货单号用,隔开" v-model="searchSns"></el-input>
              </div>
            </template>
            <template #right>
              <el-button type="primary" @click="search()">查询</el-button>
            </template>
          </ai-search-bar>
          <ai-table
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="total"
            :isShowPagination="false"
            style="margin-top: 8px;"
            v-loading="isDlgLoading"
            @selection-change="onChooseChange">
            <el-table-column slot="productName" width="400px" label="商品信息" align="center">
              <template slot-scope="scope">
                <div class="product">
                  <img :src="scope.row.productSkcPicture">
                  <div class="right">
                    <div>备货母单号: {{ scope.row.originalPurchaseOrderSn }}</div>
                    <el-tooltip effect="dark" :content="scope.row.productName" placement="top-start">
                      <div class="textoverflow">{{ scope.row.productName }}</div>
                    </el-tooltip>
                    <div>SKC: {{ scope.row.productSkcId }}</div>
                    <div>货号: {{ scope.row.productSn }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column slot="className" label="SKU信息" width="440px" show-overflow-tooltip align="center">
              <template slot-scope="scope">
                <div class="order-manage_skuInfo__FW-Nd" v-for="(item, index) in scope.row.detailList" :key="index">
                  <div>
                    <div data-testid="beast-core-box" class="outerWrapper-1-3-1 outerWrapper-d18-1-3-20 index-module__image-preview___2fiZX">
                      <div class="index-module__img___p3B1N" :style="getStyle(item.thumbUrlList[0])"></div>
                    </div>
                  </div>
                  <div class="order-manage_contentInfo__1Cjd6">
                    <div>属性：{{ item.className }}</div>
                    <div>下单数量：{{ item.purchaseQuantity }}</div>
                    <div>SKU ID： {{ item.productSkuId }}</div>
                    <div class="order-manage_productSku__XP_ke">SKU 货号： {{ item.extCode }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </ai-table>
          <span slot="footer" class="dialog-footer">
            <el-button @click="isShow = false">关 闭</el-button>
            <el-button type="primary" @click="onConfirm">添加</el-button>
          </span>
        </AiDialog>

        <AiDialog
          title="抢单成功列表"
          :visible.sync="successDlgShow"
          :close-on-click-modal="false"
          customFooter
          width="1290px">
          <label style="width:90px">店铺：</label>
          <el-select clearable v-model="successMallId" placeholder="请选择">
            <el-option
              v-for="item in mallList"
              :key="item.mallId"
              :label="item.mallName"
              :value="item.mallId">
              {{ item.mallName }}
            </el-option>
          </el-select>
          <ai-table
            :tableData="successData"
            :col-configs="successColConfigs"
            :total="total"
            height="500"
            :isShowPagination="false"
            style="margin-top: 8px;">
          </ai-table>
          <span slot="footer" class="dialog-footer">
            <el-button @click="successDlgShow = false">关 闭</el-button>
          </span>
        </AiDialog>

        <AiDialog
          title="抢仓异常列表"
          :visible.sync="errorDlgShow"
          :close-on-click-modal="false"
          customFooter
          width="1290px">
          <ai-table
            :tableData="errorList"
            :col-configs="errorListColConfigs"
            :total="errorList.length"
            height="500"
            :isShowPagination="false"
            style="margin-top: 8px;">
            <el-table-column slot="url" label="处理" show-overflow-tooltip align="center">
              <template slot-scope="{ row }">
                <div>
                  <a class="el-link el-link--primary" v-if="row.url" :href="row.url" target="_blank">去处理</a>
                </div>
              </template>
            </el-table-column>
            <el-table-column slot="options" label="操作" width="80px" show-overflow-tooltip align="center" fixed="right">
              <template slot-scope="{ row }">
                <div class="table-options">
                  <el-button type="text" @click="removeError(row.sn)">移除</el-button>
                </div>
              </template>
            </el-table-column>
          </ai-table>
          <span slot="footer" class="dialog-footer">
            <el-button @click="errorDlgShow = false">关 闭</el-button>
          </span>
        </AiDialog>

        <AiDialog
          title="抢仓设置"
          :visible.sync="robDlgShow"
          :close-on-click-modal="false"
          customFooter
          height="500px"
          width="700px">
            <el-alert
              title="抢仓速度 = 频率 + 0~变动值之间的随机数，如频率设置为1.5秒，变动值为500毫秒，则抢仓速度为1.5秒~2秒。"
              type="success"
              :closable="false">
            </el-alert>
            <el-form :model="robForm" ref="robForm" label-width="180px" class="form">
              <el-form-item
                prop="step"
                label="频率："
                :rules="[{ required: true, message: '请选择抢仓频率', trigger: 'blur' }]">
                <ai-select :selectList="$dict.getDict('rob_frequency')" v-model="robForm.step"></ai-select>
              </el-form-item>
              <el-form-item
                prop="randomValue"
                label="变动值(毫秒)："
                :rules="[{ required: true, message: '请输入变动值', trigger: 'blur' }]">
                <el-input size="small"  placeholder="请输入变动值" type="number" v-model="robForm.randomValue"></el-input>
              </el-form-item>

              <el-form-item
                prop="isCreateDeliveryBill"
                label="是否创建发货单："
                :rules="[{ required: true, message: '请选择是否创建发货单', trigger: 'blur' }]">
                <el-radio-group v-model="robForm.isCreateDeliveryBill" size="medium">
                  <el-radio :label="false">否</el-radio>
                  <el-radio :label="true">是</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                prop="isModifyMaxNum"
                label="是否修改为最大发货数："
                :rules="[{ required: true, message: '请选择是否修改为最大发货数', trigger: 'blur' }]">
                <el-radio-group :disabled="!robForm.isCreateDeliveryBill" v-model="robForm.isModifyMaxNum" size="medium">
                  <el-radio :label="false">否</el-radio>
                  <el-radio :label="true">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          
          <span slot="footer" class="dialog-footer">
            <el-button @click="robDlgShow = false">关 闭</el-button>
            <el-button type="primary" @click="beforeBegin">开 始</el-button>
          </span>
        </AiDialog>

        <AiDialog
          title="警告"
          :visible.sync="isShowWarning"
          :close-on-click-modal="false"
          customFooter
          height="400px"
          width="400px">
          <span style="color: red; height: 30px; font-size: large; display: block">{{ warningText }}</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="isShowWarning = false">我知道了</el-button>
          </span>
        </AiDialog>
      </template>
    </ai-list>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import {sendChromeAPIMessage, sendChromeNotification} from '@/api/chromeApi'
  import { Message } from 'element-ui'
  export default {
    name: 'NormalSendGoods',

    data () {
      return {
        isShow: false,
        colConfigs: [
          { type: "selection", width: '70px', align: 'left' },
          { prop: 'subPurchaseOrderSn', label: '备货单号', align: 'left' },
          { slot: 'productName' },
          { slot: 'className'},
          { slot: 'robInfo'},
          { slot: 'status' }
        ],
        robColConfigs: [
          { prop: 'subPurchaseOrderSn', width: '180px', label: '备货单号', align: 'left' },
          { slot: 'productName' },
          { prop: 'mallName', label: '店铺来源', align: 'center' },
          { slot: 'className'},
          { slot: 'robInfo'},
          { slot: 'status' }
        ],
        successColConfigs: [
          { prop: 'subPurchaseOrderSn', width: '180px', label: '备货单号', align: 'left' },
          { prop: 'mallName', label: '店铺来源', width: '180px', align: 'center' },
          { prop: 'productName', label: '商品名称', "show-overflow-tooltip": true, width: '580px' },
          { prop: 'productSn', label: '货号' }
        ],
        errorListColConfigs: [
          { prop: 'sn', width: '180px', label: '备货单号', align: 'left' },
          { prop: 'mallName', label: '店铺名称', width: '180px', align: 'center' },
          { prop: 'errorMsg', label: '错误信息', width: '380px', align: 'center' },
          { slot: 'url' }
        ],
        mallId: '',
        mallName: '',
        skc: '',
        searchSns: '',
        tableData: [],
        total: 0,
        isBegin: false,
        choosedList: [],
        choosedSnMallList: [],
        arr: [],
        robTotal: 0,
        pageSize: 100,
        currentPage: 1,
        robForm: {
          step: "500",
          randomValue: 500,
          isCreateDeliveryBill: false,
          isModifyMaxNum: false
        },
        loadMallIndex: 0,
        loadMode: 0,     // 加载模式，0表示单个店铺加载，1表示一键加载

        // 网络超时次数
        networkErrorCount: 0,

        successDlgShow: false,
        successMallId: '',
        successList: [],

        // 加载数据
        isLoading: false,
        isDlgLoading: false,

        // 警告弹窗
        isShowWarning: false,
        warningText: '',

        robDlgShow: false,

        addressList: [],
        errorList: [],
        errorDlgShow: false
      }
    },

    computed: {
      ...mapState(['mallList']),
      successData() {
        if (!this.successMallId) {
          return this.successList
        }
        return this.successList.filter(item => {
          return item.mallId == this.successMallId
        })
      }
    },

    created () {
      this.$dict.load('rob_frequency');
    },
    activated () {
      this.addressList = []
      this.toGetAddressInfo();
    },

    methods: {
      onChooseChange (e) {
        this.arr = e
      },
      mallChange() {
        this.$userCheck(this.mallId).then(() => {
          let mallInfo = this.mallList.filter(item => {
            return item.mallId == this.mallId
          })
          this.mallName = mallInfo[0].mallName

          // 下载数据
          this.loadMode = 0
          this.tableData = []
          this.currentPage = 1
          this.isDlgLoading = true
          this.getList(this.tableData, this.mallId, this.mallName, 1)
        }).catch((err) => {
          console.log(err)
        })
      },
      search() {
        if (!this.mallId) {
          Message.error('请选择店铺')
          return
        }
        // 下载数据
        this.loadMode = 0
        this.tableData = []
        this.currentPage = 1
        this.isDlgLoading = true
        this.getList(this.tableData, this.mallId, this.mallName, 1)
      },
      toGetAddressInfo() {
        this.addressList = []
        this.getAddressInfo()
      },
      async getAddressInfo() {
        if (!this.mallList) {
          Message.error('获取默认发货地址失败，请刷新重试')
          return
        }
        for (let index = 0; index < this.mallList.length; index++) {
          let mallInfo = this.mallList[index]
          while(true) {
            let res = await sendChromeAPIMessage({
              url: 'bgSongbird-api/supplier/address/queryDeliveryAddressInfo',
              needMallId: true,
              mallId: mallInfo.mallId,
              data: {}})
            if (res.errorCode == 1000000) {
              let addressArr = res.result.deliveryAddressInfoList.filter(i => {
                return i.isDefault
              })
              if (addressArr.length > 0) {
                this.addressList.push({
                  mallId: mallInfo.mallId,
                  addressId: addressArr[0].id
                })
              } else {
                Message.error("店铺【" + mallInfo.mallName + "】未设置默认发货地址，将无法自动创建发货单")
              }
              break
            }
          }
        }
      },
      onConfirm () {
        if (this.arr.length == 0) {
          Message.error("请选择备货单")
          return
        }
        this.arr.map(item => {
          let temp = this.choosedList.filter(i => {
            return i.subPurchaseOrderSn == item.subPurchaseOrderSn
          })
          if (temp.length == 0) {
            this.choosedList.push(item)
          }
        })
        Message.success("添加成功，可继续添加")
      },
      loadAll() {
        this.$userCheck().then(() => {
          this.choosedList = []
          this.currentPage = 1
          this.isLoading = true
          if (this.$store.state.userInfo.type == 3) {
            this.loadMode = 0
            this.getList(this.choosedList, this.$store.state.mallId, this.$store.state.mallName, 1)
          } else {
            this.loadMallIndex = 0
            this.loadMode = 1
            this.getList(this.choosedList, this.mallList[this.loadMallIndex].mallId, this.mallList[this.loadMallIndex].mallName, 1)
          }
        });
      },

      handleClick (e) {
        if (e === 'byStore') {
          this.isShow = true
        } else if (e === 'loadAll') {
          this.loadAll()
        }
      },
      beginRobConfirm() {
        if (this.choosedList.length <= 0) {
          Message.error('请先添加备货单');
          return;
        }
        this.robDlgShow = true
      },
      beforeBegin() {
        this.$refs.robForm.validate((valid) => {
          if (valid) {
            this.networkErrorCount = 0
            this.robDlgShow = false
            this.errorList = []
            this.beginRob()
          }
        })
      },
      getList (data, mallId, mallName, currentPage) {
        sendChromeAPIMessage({
          url: 'oms/bg/venom/api/supplier/purchase/manager/querySubOrderList',
          needMallId: true,
          mallId: mallId,
          data: {
            "pageNo": currentPage,
            "pageSize": this.pageSize,
            "urgencyType": 0,
            "isCustomGoods": false,
            "statusList": [
              1
            ],
            productSkcIdList: this.skc? this.skc.split(','): null,
            subPurchaseOrderSnList: this.searchSns? this.searchSns.split(','): null
          }}).then((res) => {
            if (res.errorCode == 1000000) {
              let length = res.result.subOrderForSupplierList.length
              res.result.subOrderForSupplierList = res.result.subOrderForSupplierList.filter((item) => {
                return item.isCanJoinDeliverPlatform;
              })
              res.result.subOrderForSupplierList.map((item) => {
                let temp = data.filter(i => {
                  return i.subPurchaseOrderSn == item.subPurchaseOrderSn
                })
                if (temp.length == 0) {
                  data.push({
                    robTotal: 0,
                    subPurchaseOrderSn: item.subPurchaseOrderSn,
                    originalPurchaseOrderSn: item.originalPurchaseOrderSn,
                    productName: item.productName,
                    productSn: item.productSn,
                    productSkcId: item.productSkcId,
                    productSkcPicture: item.productSkcPicture,
                    status: item.status,
                    detailList: item.skuQuantityDetailList,
                    category: item.category,
                    mallId: mallId,
                    mallName: mallName
                  })
                }
              })

              if (this.pageSize == length) {
                currentPage ++
                this.getList(data, mallId, mallName, currentPage)
              } else {
                if (this.loadMode == 1) {
                  this.loadMallIndex ++
                  if (this.loadMallIndex < this.mallList.length) {
                    this.getList(data, this.mallList[this.loadMallIndex].mallId, this.mallList[this.loadMallIndex].mallName, 1)
                  } else {
                    this.isLoading = false
                    this.isDlgLoading = false
                    Message.success("所有店铺备货单已加载完成")
                  }
                } else {
                  this.isLoading = false
                  this.isDlgLoading = false
                }
              }
            } else {
              this.getList(data, mallId, mallName, currentPage)
            }
        })
      },
      remove(sn) {
        for (let i = 0; i < this.choosedList.length; i++) {
          if (this.choosedList[i].subPurchaseOrderSn == sn) {
            this.choosedList.splice(i, 1)
            break
          }
        }
      },
      removeError(sn) {
        for (let i = 0; i < this.errorList.length; i++) {
          if (this.errorList[i].sn == sn) {
            this.errorList.splice(i, 1)
            break
          }
        }
      },
      getStyle(url) {
        return "background-image: url(" + url + "); width: 72px; height: 72px; cursor: pointer; border-radius: 6px; border: 1px solid rgba(0, 0, 0, 0.14);";
      },
      beginRob() {
        if (this.isBegin) {
          this.isBegin = false;
          return;
        }

        this.choosedSnMallList = this.choosedList.map(item => {
          return {sn: item.subPurchaseOrderSn, mallId: item.mallId}
        })

        this.robTotal = this.choosedList.length
        this.isBegin = true;

        this.rob()

        let _this = this;
        let tt = setInterval(function() {
          if (_this.choosedList.length == 0) {
            _this.isBegin = false;
            clearInterval(tt);
          }
        }, 1000)
      },
      robFunc(sn, mallId) {
        let _this = this;
        return function() {
          _this.rob(sn, mallId);
        }
      },
      rob() {
        let obj = this.choosedSnMallList.shift()
        if (!obj || !this.isBegin) {
          return
        }
        let sn = obj.sn
        let mallId = obj.mallId
        sendChromeAPIMessage({
          url: 'oms/bg/venom/api/supplier/purchase/manager/joinDeliveryGoodsOrderPlatform',
          needMallId: true,
          anti: true,
          mallId: mallId,
          data: {
            "subPurchaseOrderSn": sn
          }}).then((res) => {
            if (res.errorCode == 1000000 && res.result.isSuccess) {              
              for (let j = 0; j < this.choosedList.length; j++) {
                if (this.choosedList[j].subPurchaseOrderSn == sn) {
                  this.successList.push(this.choosedList[j])
                  this.addSuccessInfo(this.choosedList[j]);
                  this.sendNotification(this.choosedList[j]);
                  this.choosedList.splice(j, 1);

                  for (let k = 0; k < this.errorList.length; k++) {
                    if (this.errorList[k].sn == sn) {
                      this.errorList.splice(k, 1);
                      break
                    }
                  }
                  break;
                }
              }

              // 如果需要创建发货单
              if (this.robForm.isCreateDeliveryBill) {
                this.createDeliveryBill(sn, mallId)
              }
            } else {
              this.choosedSnMallList.push(obj)
              for (let j = 0; j < this.choosedList.length; j++) {
                if (this.choosedList[j].subPurchaseOrderSn == sn) {
                  this.choosedList[j].robTotal ++;
                  break;
                }
              }
            }
            if (!res.errorCode && res.error_code && (res.error_code == 40001)) {
              this.isShowWarning = true
              this.warningText = '“卖家中心”已退出登录，抢单停止'
              this.isBegin = false
            }
            if (!res.errorCode && res.error_code && (res.error_code == 40002)) {
              this.isShowWarning = true
              this.warningText = '账号异常，请更换“卖家中心”账号'
            }
            if (res.errorCode == 1000000 && !res.result.isSuccess) {
              if (res.result.errorInfoList[0]) {
                if (res.result.errorInfoList[0].errorCode == -10007) {
                  let temp = this.errorList.filter(item => {
                    return item.sn == sn
                  })
                  if (temp.length == 0) {
                    let mallInfo = this.mallList.filter(item1 => {
                      return item1.mallId == mallId
                    })
                    let mallName = mallInfo[0].mallName
                    this.errorList.push({
                      sn: res.result.errorInfoList[0].id,
                      errorMsg: res.result.errorInfoList[0].errorMsg,
                      mallName: mallName,
                      url: 'https://agentseller.temu.com' + res.result.errorInfoList[0].extraInfoMap?.url
                    })
                  }
                }
              }
            }
            if (this.isBegin) {
              // 继续抢
              setTimeout(() => {
                this.rob()
              }, parseInt(this.robForm.step) + Math.floor(Math.random() * parseInt(this.robForm.randomValue)))
            }
            
        })
      },
      createDeliveryBill(sn, mallId) {
        sendChromeAPIMessage({
          url: 'bgSongbird-api/supplier/deliverGoods/platform/pageQuerySubPurchaseOrder',
          needMallId: true,
          anti: true,
          mallId: mallId,
          data: {
            "pageNo": 1,
            "pageSize": 10,
            "subPurchaseOrderSnList": [
              sn
            ]
          }}).then((res) => {
            if (res.errorCode == 1000000) {
              if (res.result.list.length == 0) {
                setTimeout(() => { this.createDeliveryBill(sn, mallId)}, 1000)
                return
              }
              let data = res.result.list[0]
              let deliverOrderDetailInfos = data.orderDetailVOList.map(item => {
                if (this.robForm.isModifyMaxNum) {
                  return {
                    productSkuId: item.productSkuId,
                    deliverSkuNum: item.skuDeliveryQuantityMaxLimit
                  }
                } else {
                  return {
                    productSkuId: item.productSkuId,
                    deliverSkuNum: item.productSkuPurchaseQuantity
                  }
                }
              })
              let packageInfos = []
              data.orderDetailVOList.map(item => {
                let packageDetailSaveInfos = []
                if (this.robForm.isModifyMaxNum) {
                  packageDetailSaveInfos.push({
                    productSkuId: item.productSkuId,
                    skuNum: item.skuDeliveryQuantityMaxLimit
                  })
                  
                } else {
                  packageDetailSaveInfos.push({
                    productSkuId: item.productSkuId,
                    skuNum: item.productSkuPurchaseQuantity
                  })
                }
                packageInfos.push({packageDetailSaveInfos: packageDetailSaveInfos})
              })

              let addressInfo = this.addressList.filter(k => {
                return k.mallId == mallId
              })
              let deliveryOrderCreateInfos = []
              deliveryOrderCreateInfos.push({
                deliverOrderDetailInfos: deliverOrderDetailInfos,
                subPurchaseOrderSn: data.subPurchaseOrderBasicVO.subPurchaseOrderSn,
                deliveryAddressId: addressInfo[0].addressId,
                packageInfos: packageInfos
              })

              let deliveryOrderCreateGroupList = []
              deliveryOrderCreateGroupList.push({
                deliveryOrderCreateInfos: deliveryOrderCreateInfos,
                receiveAddressInfo: data.subPurchaseOrderBasicVO.receiveAddressInfo,
                subWarehouseId: data.subPurchaseOrderBasicVO.subWarehouseId
              })

              this.createDeliveryOrder(mallId, deliveryOrderCreateGroupList)
            } else {
              setTimeout(() => { this.createDeliveryBill(sn, mallId)}, 1000)
            }
          })
      },
      createDeliveryOrder(mallId, data) {
        sendChromeAPIMessage({
          url: 'bgSongbird-api/supplier/deliverGoods/platform/createDeliveryOrderGroupSimpleByAddress',
          needMallId: true,
          anti: true,
          mallId: mallId,
          data: {deliveryOrderCreateGroupList: data}}).then((res) => {
            if (res.errorCode == 1000000) {
              console.log(res)
            } else {
              setTimeout(() => { this.createDeliveryOrder(mallId, data)}, 1000)
            }
          })
      },
      createDeliveryBillFun(sn, mallId) {
        let _this = this;
        return function() {
          _this.createDeliveryBill(sn, mallId);
        }
      },
      addSuccessInfo(obj) {
        this.$http.post(`/api/successInfo/add`, {
            productName: obj.productName,
            subPurchaseOrderSn: obj.subPurchaseOrderSn,
            mallId: obj.mallId,
            mallName: obj.mallName,
            categoryName: obj.category
          }).then(res => {
          console.log(res)
        })
      },
      sendNotification(obj) {
        sendChromeNotification({productName: obj.productName, mallName: obj.mallName})
      }
    }
  }
</script>

<style scoped lang="scss">
.product {
  display: flex;
  align-items: center;
  justify-content: center;

  .right {
    flex: 1;
    text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  img {
    width: 60px;
    margin-right: 10px;
  }
}

.tips {
  position: relative;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(243, 8, 8, .4);

  @keyframes warn {
    0% {
      transform: translate(-50%, -50%) scale(0);
      opacity: 1;
    }

    100% {
      transform: translate(-50%, -50%) scale(1.1);
      opacity: 0;
    }
  }

  div {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 11;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    animation: warn 0.9s ease-out;
    animation-iteration-count: infinite;
    box-shadow: 1px 1px 30px #EF2D02;
    transform: translate(-50%, -50%) scale(0.2);
    transition: all ease-in-out 0.6s;
    background: rgba(243, 8, 8, .6);
  }
}


.errorTips {
  position: relative;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgb(255, 0, 0);

  @keyframes warn {
    0% {
      transform: translate(-50%, -50%) scale(0);
      opacity: 1;
    }

    100% {
      transform: translate(-50%, -50%) scale(1.1);
      opacity: 0;
    }
  }

  div {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 11;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    animation: warn 0.9s ease-out;
    animation-iteration-count: infinite;
    box-shadow: 1px 1px 30px #EF2D02;
    transform: translate(-50%, -50%) scale(0.2);
    transition: all ease-in-out 0.6s;
    background: rgba(255, 0, 0, .6);
  }
}

.order-manage_productInfo__1pD83>img {

    width: 60px;
    margin-right: 10px;
}
.order-manage_productInfo__1pD83 {
  min-height: 60px;
  padding-left: 70px;
  position: relative;
}

.order-manage_productInfo__1pD83>div:nth-child(2) {
    color: rgba(0,0,0,.8);
}

.outerWrapper {
    margin: 4px 4px 0px 0px;
}

.dot-module__dot___M-RuH .dot-module__circle___2l2UV {
    flex-shrink: 0;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 8px;
}

.dot-module__dot___M-RuH {
  display: inline-flex;
  align-items: center;
}

.index-module__image-preview___2fiZX .index-module__img___p3B1N {
    width: 60px;
    height: 60px;
    margin-right: 10px;
    background-repeat: no-repeat;
    background-size: cover;
    background-color: #f5f5f5;
    font-size: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: var(--bc-Table-emptyTextColor);
    position: relative;
}

.textoverflow {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

.order-manage_skuInfo__FW-Nd {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;

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

  .order-manage_contentInfo__1Cjd6 {
    display: flex;
    flex-direction: column;
    text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 240px;
  }
}


.order-manage_skuInfo__FW-Nd .order-manage_contentInfo__1Cjd6 .order-manage_title__1VTO5 {
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    color: rgba(0,0,0,.8);
}
</style>
