<template>
  <div>
    <ai-list class="list">
      <ai-title
        slot="title"
        title="普通备货单"
        tips="请先在当前浏览器登录“拼多多跨境卖家中心”，期间保持登录状态"
        isShowBottomBorder>
      </ai-title>
      <template slot="content">
        <ai-search-bar>
          <template #left>
            <el-button type="primary" @click="isShow = true">选择商品</el-button>
            <el-button type="primary" :loading="isBegin"  @click="beginRob">{{ isBegin ? '结束抢仓': '开始抢仓' }}</el-button>
          </template>
          <template #right>
            <el-button size="small" circle icon="el-icon-refresh-right" @click="getList"></el-button>
          </template>
        </ai-search-bar>
        <ai-table
          :tableData="tableData"
          :col-configs="colConfigs"
          :total="total"
          :isShowPagination="false"
          style="margin-top: 8px;"
          @selection-change="handleSelectionChange"
          @getList="getList">center
          <el-table-column slot="productName" width="480px" label="商品信息" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <div class="order-manage_productInfo__1pD83">
                <img :src="scope.row.productSkcPicture">
                <div class="right">

                <div>备货母单号: {{ scope.row.originalPurchaseOrderSn }}</div>
                <div>{{ scope.row.productName }}</div>
                <div>SKC: {{ scope.row.productSkcId }}</div>
                <div>货号: {{ scope.row.productSn }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column slot="robInfo" label="抢仓信息" show-overflow-tooltip 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 }}，下单数量：{{ 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" fixed="right" 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>
        </ai-table>
        <AiDialog
          title="选择商品"
          :visible.sync="isShow"
          :close-on-click-modal="false"
          width="1290px">
          <el-select v-model="mallId" placeholder="请选择" @click="getList">
            <el-option
              v-for="item in mallList"
              :key="item.mallId"
              :label="item.mallName"
              :value="item.mallName">
              {{ item.mallName }}
            </el-option>
          </el-select>
          <ai-table
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="total"
            :isShowPagination="false"
            style="margin-top: 8px;"
            @selection-change="handleSelectionChange"
            @getList="getList">center
            <el-table-column slot="productName" width="400px" label="商品信息" show-overflow-tooltip align="center">
              <template slot-scope="scope">
                <div class="order-manage_productInfo__1pD83">
                  <img :src="scope.row.productSkcPicture">
                  <div class="right">

                  <div>备货母单号: {{ scope.row.originalPurchaseOrderSn }}</div>
                  <div>{{ scope.row.productName }}</div>
                  <div>SKC: {{ scope.row.productSkcId }}</div>
                  <div>货号: {{ scope.row.productSn }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column slot="robInfo" label="抢仓信息" show-overflow-tooltip 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="400px" 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 }}，下单数量：{{ 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>
        </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: '备货单号', width: '180px', align: 'left' },
          { slot: 'productName' },
          { slot: 'className'},
          { slot: 'robInfo'},
          { slot: 'status' }
        ],
        mallId: '',
        tableData: [],
        total: 0,
        ids: [],
        isBegin: false,
        timer: null
      }
    },

    ...mapState(['mallName', 'mallList']),

    created () {
      this.getList()
    },

    activated () {
      this.getList()
    },

    methods: {
      getList () {
        sendChromeAPIMessage({
          url: 'oms/bg/venom/api/supplier/purchase/manager/querySubOrderList',
          needMallId: true,
          data: {
            "pageNo": 1,
            "pageSize": 100,
            "urgencyType": 0,
            "isCustomGoods": false,
            "statusList": [
              1
            ]
          }}).then((res) => {
            if (res.errorCode == 1000000) {
              res.result.subOrderForSupplierList = res.result.subOrderForSupplierList.filter((item) => {
                return item.isCanJoinDeliverPlatform;
              })
              this.tableData = res.result.subOrderForSupplierList.map((item) => {
                return {
                  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
                };
              })
            } else {
              Message.error("【拼多多】" + res.error_msg)
            }
        })
      },
      handleSelectionChange(val) {
        this.ids = [];
        val.forEach(e => {
          this.ids.push(e.subPurchaseOrderSn);
        });
      },
      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;
          for (let i = 0;i < this.timer.length; i++) {
            clearInterval(this.timer[i].timer);
          }
          return;
        }
        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;
            }
            if (res.data.type != 4 && this.$store.state.mallId != this.$store.state.userInfo.mallId) {
              Message.error('您当前登录的TEMU账号与会员绑定账号不一致')
              return;
            }
            if (this.ids.length <= 0) {
              Message.error('请选择抢仓商品');
              return;
            }
            this.isBegin = true;
            this.timer = [];

            for (let i = 0;i < this.ids.length; i++) {
              let t = setInterval(this.robFunc(this.ids[i]), 1000);
              this.timer.push({id: this.ids[i], timer: t})
            }

            let _this = this;
            let tt = setInterval(function() {
              if (_this.ids.length == 0) {
                _this.isBegin = false;
                clearInterval(tt);
              }
            }, 1000)
          } else {
            console.log("获取用户信息失败")
          }
        });

      },
      robFunc(sn) {
        let _this = this;
        return function() {
          _this.rob(sn);
        }
      },
      rob(sn) {
        sendChromeAPIMessage({
          url: 'oms/bg/venom/api/supplier/purchase/manager/joinDeliveryGoodsOrderPlatform',
          needMallId: true,
          data: {
            "subPurchaseOrderSn": sn
          }}).then((res) => {
            if (res.errorCode == 1000000) {
              for (let i = 0;i < this.ids.length; i++) {
                if (this.ids[i] == sn) {
                  this.ids.splice(i, 1)
                  break;
                }
              }

              let t = this.timer.filter((item) => {
                return item.id == sn;
              })
              if (t.length > 0) {
                clearInterval(t[0].timer)
              }

              for (let j = 0; j < this.tableData.length; j++) {
                if (this.tableData[j].subPurchaseOrderSn == sn) {
                  this.sendSms(this.tableData[j].productName);
                  this.sendNotification(this.tableData[j].productName);
                  this.tableData.splice(j, 1);
                  break;
                }
              }
            } else {
              for (let j = 0; j < this.tableData.length; j++) {
                if (this.tableData[j].subPurchaseOrderSn == sn) {
                  this.tableData[j].robTotal ++;
                  break;
                }
              }
            }
        })
      },
      sendSms(productName) {
        this.$http.post(`/api/sms/sendSuccessSms`, null, {
          params: {
            productName: productName
          }
        }).then(res => {
          console.log(res)
        })
      },
      sendNotification(productName) {
        sendChromeNotification({productName: productName})
      }
    }
  }
</script>

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

  .right {
    text-align: left;
  }
}
.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;
}

.order-manage_skuInfo__FW-Nd, .order-manage_skuInfo__FW-Nd .order-manage_contentInfo__1Cjd6 {
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    justify-content: center;
}

.order-manage_skuInfo__FW-Nd .order-manage_contentInfo__1Cjd6 {
    -webkit-flex-direction: column;
    -moz-box-orient: vertical;
    -moz-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    color: rgba(0,0,0,.4);
    -webkit-flex: 1 0 auto;
    -moz-box-flex: 1;
    -ms-flex: 1 0 auto;
    flex: 1 0 auto;
}

.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>
