<template>
  <div>
    <ai-list class="list" v-loading="isLoading" :element-loading-text="loadingText">
      <ai-title
        slot="title"
        title="草稿箱管理"
        tips="请先在当前浏览器登录“拼多多跨境卖家中心”，期间保持登录状态"
        isShowBottomBorder>
        <template #rightBtn>
          <div class="title-right">
            <div>
              <label style="width:90px">店铺：</label>
              <el-select v-model="mallId" 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>
              <label style="width:90px">站点：</label>
              <el-select v-model="siteId" placeholder="请选择" size="small">
                <el-option
                  v-for="item in siteList"
                  :key="item.siteId"
                  :label="item.siteName"
                  :value="item.siteId">
                </el-option>
              </el-select>
            </div>
          </div>
        </template>
      </ai-title>
      <template slot="content">
        <div class="content">
          <ai-search-bar>
            <template #left>
              <el-button v-if="$store.state.mallName" type="button" :class="'el-button el-button--primary'" @click="batchSubmitConfig()">批量提交</el-button>
            </template>
            <template #right>
              <label style="width:140px; text-align: right;">起始页：</label>
              <el-input size="small"  placeholder="请输入起始页" style="width: 100px; display: inline" type="number" v-model="search.startPage"></el-input>
              <label style="width:140px; text-align: right;">结束页：</label>
              <el-input size="small"  placeholder="请输入起始页" style="width: 100px; display: inline" type="number" v-model="search.endPage"></el-input>
              <label style="width:120px">商品名称：</label>
              <el-input clearable size="small" style="display: inline" placeholder="请输入商品名称" v-model="search.productName"></el-input>
              <el-button type="primary" @click="toLoad">查询</el-button>
            </template>
          </ai-search-bar>
          <ai-table
            :tableData="tableData"
            :col-configs="colConfigs"
            style="margin-top: 8px;"
            @selection-change="handleSelectionChange"
            :isShowPagination="false">
          </ai-table>
        </div>
      </template>
    </ai-list>

    <ai-dialog
      title="配置参数"
      :visible.sync="dlgShow"
      :close-on-click-modal="false"
      width="790px"
      customFooter
      @close="dlgShow = false">
      <el-alert
        title="默认“承诺发货时效”为“2个工作日内发货”"
        type="success"
        :closable="false">
      </el-alert>
      <el-form class="ai-form" :model="configForm" label-width="160px" ref="configForm">
        <el-form-item label="运费模板" style="width: 100%;" prop="freightTemplateId" :rules="[{ required: true, message: '请选择运费模板', trigger: 'blur' }]">
          <el-select style="width: 380px" v-model="configForm.freightTemplateId" placeholder="请选择运费模板">
            <el-option
              v-for="item in freightTmplList"
              :key="item.freightTemplateId"
              :label="item.templateName"
              :value="item.freightTemplateId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货仓" style="width: 100%;" prop="wareHouseList" :rules="[{ required: true, message: '请选择发货仓', trigger: 'blur' }]">
          <el-select style="width: 380px" multiple v-model="configForm.wareHouseList" placeholder="请选择发货仓">
            <el-option
              v-for="item in wareHouseList"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
                prop="stockNumber"
                label="库存数量："
                :rules="[{ required: true, message: '请输入库存数量', trigger: 'blur' }]">
                <el-input size="small"  placeholder="请输入库存数量" type="number" v-model="configForm.stockNumber"></el-input>
        </el-form-item>
        <el-form-item
                prop="upMoney"
                label="上浮金额："
                :rules="[{ required: true, message: '请输入上浮金额', trigger: 'blur' }]">
                <el-input size="small"  placeholder="请输入上浮金额" type="number" v-model="configForm.upMoney"></el-input>
        </el-form-item>
        <el-form-item
                prop="brand"
                label="品牌：">
          <el-select style="width: 380px" clearable v-model="configForm.brandId" placeholder="请选择品牌">
            <el-option
              v-for="item in brandList"
              :key="item.vid"
              :label="item.brandNameEn"
              :value="item.vid">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="dlgShow = false">取 消</el-button>
        <el-button type="primary" @click="toBtachSubmit">确定</el-button>
      </div>
    </ai-dialog>
  </div>
</template>

<script>
import {sendChromeAPIMessage} from '@/api/chromeApi'
import {timestampToTime} from '@/utils/date'
import {transformSubmitForHalf} from '@/utils/product'
import { Message, MessageBox } from 'element-ui'

  export default {
    name: 'Draft',
    data () {
      return {
        mallId: '',
        siteId: '',
        siteList: [],
        search: {
          startPage: 1,
          endPage: 10,
          productName: ''
        },
        colConfigs: [
          { type: "selection", width: '70px', align: 'left', fixed: 'left'},
          { prop: 'spuId', label: 'SPU ID', width: '100px', align: 'left' },
          { prop: 'productName', label: '商品名称', align: 'left' },
          { prop: 'category', label: '商品分类', align: 'left'},
          { prop: 'bindSites', label: '经营站点', width: '120px', align: 'left'},
          { prop: 'updatedAt', label: '修改时间', width: '180px', fixed: 'right'}
        ],
        isLoading: false,
        page: 1,
        pageSize: 100,
        tableData: [],

        dlgShow: false,

        configForm: {
          sendGoodsSecond: 172800,
          freightTemplateId: '',
          stockNumber: 5,
          siteList: [],
          upMoney: 0.0,
          wareHouseList: [],
          brandId: '',
          brandName: ''
        },

        wareHouseList: [],
        freightTmplList: [],

        ids: [],

        sites: [],
        loadingText: '拼命加载中……',

        successNumber: 0,
        errorNumber: 0,
        brandList: [],
        selectBrand: {}
      }
    },
    created () {
      this.getSiteList()
    },

    methods: {
      toLoad() {
        if (!this.mallId) {
          Message.error("请选择店铺")
          return
        }
        if (!this.siteId) {
          Message.error("请选择站点")
          return
        }
        if (!this.search.startPage || (this.search.startPage < 1)) {
          Message.error("起始页不能为空，且不能小于1")
          return
        }
        if (!this.search.endPage || (this.search.startPage < 1)) {
          Message.error("结束页不能为空")
          return
        }
        if (this.search.startPage > this.search.endPage) {
          Message.error("起始页不能大于结束页")
          return
        }
        this.isLoading = true
        this.loadingText = '拼命加载中……'
        this.tableData = []
        this.page = this.search.startPage
        this.getDraftList()
      },
      async getDraftList () {
        let sites = []
        if (this.siteId) {
          sites.push(this.siteId)
        }
        let res = await sendChromeAPIMessage({
          url: 'bg-visage-mms/product/draft/pageQuery',
          needMallId: true,
          mallId: this.mallId,
          data: {
            page: this.page,
            pageSize: this.pageSize,
            ...this.search,
            bindSiteIds: sites
        }})

        if (res.success && res.errorCode == 1000000) {
          res.result.pageItems.map(item => {
            let category = ''
            for (let i = 1; i < 11; i++) {
              if (item.categories['cat'+i].catName) {
                category += '->' + item.categories['cat'+i].catName
              } else {
                break
              }
            }
            category = category.substring(2)
            let site = []
            let siteId = []
            item.copyFromFullyToSemiInfo.bindSites.map(item1 => {
              site.push(item1.siteName)
              siteId.push(item1.siteId)
            })
            this.tableData.push({
              spuId: item.productDraftId, 
              productName: item.productName, 
              category: category,
              bindSites: site.join(','),
              bindSiteIds: siteId.join(','),
              updatedAt: timestampToTime(item.updatedAt)
            })
          })

          if (this.page == 1 && res.result.pageItems.length == 0) {
            this.isLoading = false
          }
          else if (res.result.pageItems.length == this.pageSize && this.page < this.search.endPage) {
            this.page ++
            this.getDraftList()
          } else {
            this.isLoading = false
          }
        }
      },
      async batchSubmitConfig() {
        if (this.ids.length <= 0) {
          Message.error('请选择要提交的商品');
          return;
        }

        this.sites = []
        this.sites.push(this.siteId)

        this.configForm.siteList = this.sites
        this.freightTmplList = []
        this.wareHouseList = []
        this.configForm.freightTemplateId = ''
        this.configForm.wareHouseList = []
        await this.getFreightTmplList(this.sites)
        await this.getWareahouseList(this.sites)
        await this.getBrandList()
        this.dlgShow = true
      },
      async toBtachSubmit() {
        this.$refs.configForm.validate((valid) => {
          if (valid) {
            if (this.configForm.brandId) {
              this.brandList.map(item => {
                if (item.vid == this.configForm.brandId) {
                  this.selectBrand = item
                } 
              })
            }
            this.isLoading = true
            this.dlgShow = false
            this.successNumber = 0
            this.errorNumber = 0
            this.submitSpu(0)
          }
        })
      },
      async submitSpu(idx) {
        if (idx == this.ids.length) {
          this.isLoading = false
          MessageBox.alert('总共提交' + this.ids.length + '个商品，成功' + this.successNumber + '个，失败' + this.errorNumber + '个', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.toLoad()
            }
          })
          return
        } else {
          this.loadingText = '正在提交第' + (idx+1) + '/' + this.ids.length + '个商品，成功' + this.successNumber + '个，失败' + this.errorNumber + '个'
        }
        let spuId = this.ids[idx]
        let res = await sendChromeAPIMessage({
          url: 'bg-visage-mms/product/draft/query',
          needMallId: true,
          mallId: this.mallId,
          data: {
            productDraftId: spuId
        }})
        if (res.success && res.errorCode == 1000000) {
          let catId = this.getCategoryId(res.result)
          let brandProperty = await this.queryProperty(catId)

          let content = transformSubmitForHalf(res.result, this.configForm, spuId)

          if (this.configForm.brandId && brandProperty) {
            let flag = false
            content.productPropertyReqs.map(item => {
              if (item.propName == '品牌名') {
                flag = true
                item.pid = brandProperty.pid
                item.refPid = brandProperty.refPid
                item.templatePid = brandProperty.templatePid
                item.propValue = this.selectBrand.brandNameEn
                item.vid = this.selectBrand.vid
              }
            })
            if (!flag) {
              content.productPropertyReqs.push({
                "templatePid": brandProperty.templatePid,
                "pid": brandProperty.pid,
                "refPid": brandProperty.refPid,
                "propName": "品牌名",
                "vid": this.selectBrand.vid,
                "propValue": this.selectBrand.brandNameEn,
                "valueUnit": "",
                "valueExtendInfo": "",
                "numberInputValue": ""
              })
            }
          }

          let res1 = await sendChromeAPIMessage({
            url: 'bg-visage-mms/product/add',
            needMallId: true,
            mallId: this.mallId,
            data: content})
          
          if (res1.success && res1.errorCode == 1000000) {
            this.successNumber += 1
          } else {
            this.errorNumber += 1
          }
          setTimeout(() => {
            idx ++
            this.submitSpu(idx)
          }, 1000)
        }
      },
      async getFreightTmplList(siteId) {
        let res = await sendChromeAPIMessage({
          url: 'bg-visage-mms/freight/template/list',
          needMallId: true,
          mallId: this.mallId,
          data: {
            siteIds: siteId
          }})

        if (res.success && res.errorCode == 1000000) {
          res.result.freightTmplSimpleList.map(item => {
            this.freightTmplList.push({
              freightTemplateId: item.freightTemplateId,
              templateName: item.templateName
            })
          })
        }
      },
      async getWareahouseList(siteId) {
        let res = await sendChromeAPIMessage({
          url: 'marvel-mms/cn/api/kiana/starlaod/btg/sales/stock/querySiteCanSelectWarehouseList',
          needMallId: true,
          mallId: this.mallId,
          data: {
            siteIdList: siteId
          }})

        if (res.success && res.errorCode == 1000000) {
          res.result.warehouseDTOList.map(item => {
            item.validWarehouseList.map(item1 => {
              this.wareHouseList.push({
                warehouseId: item1.warehouseId,
                warehouseName: item1.warehouseName
              })
            })
          })
        }
      },
      handleSelectionChange(val) {
        this.ids = [];
        val.forEach(e => {
          this.ids.push(e.spuId);
        });
      },
      async getSiteList() {
        let res = await sendChromeAPIMessage({
          url: 'bg-visage-mms/config/common/site/query',
          needMallId: true,
          mallId: this.$store.state.mallList[0].mallId,
          data: {}})
        if (res.success && res.errorCode == 1000000) {
          this.siteList = res.result.siteBaseList.filter(item => {
            return item.matchSemiManaged
          })
        }
      },
      async getBrandList() {
        let res = await sendChromeAPIMessage({
          url: 'bg-anniston-mms/category/brand/property/value/pageQuery',
          needMallId: true,
          mallId: this.mallId,
          data: {
            "page": 1,
            "pageSize": 50
          }})
        if (res.success && res.errorCode == 1000000) {
          this.brandList = res.result.pageItems
        }
      },
      async queryProperty(catId) {
        let res = await sendChromeAPIMessage({
          url: 'bg-anniston-mms/category/template/query',
          needMallId: true,
          mallId: this.mallId,
          data: {
            "catId": catId,
            "productCreateTime": null,
            "langList": [
              "en"
            ]
          }})
        if (res.success && res.errorCode == 1000000) {
          let properties = res.result.properties.filter(item => {
            return item.name == '品牌名'
          })
          if (properties && properties.length > 0) {
            return properties[0]
          } else {
            return null
          }
        }
      },
      getCategoryId(obj) {
        let i = 1
        while(true) {
          if (!obj.categories['cat'+i].catId) {
            break
          }
          i++
        }
        return obj.categories['cat'+(i-1)].catId
      }
    }
  }
</script>

<style scoped lang="scss">
</style>
