<template>
  <ai-list class="Template">
    <ai-title
      slot="title"
      title="管理SKU"
      isShowBack
      isShowBottomBorder
      @onBackClick="$router.go(-1)">
    </ai-title>
    <template slot="content">
      <ai-search-bar>
        <template #left>
          <el-button type="primary" size="small" @click="isShow = true">添加</el-button>
        </template>
        <template #right>
        </template>
      </ai-search-bar>
      <ai-table
        :tableData="tableData"
        :col-configs="colConfigs"
        :total="total"
        :current.sync="search.current"
        :size.sync="search.size"
        style="margin-top: 8px;"
        @getList="getList"
        @selection-change="handleSelectionChange">
        <el-table-column slot="productName" width="300px" :show-overflow-tooltip='true' label="商品名称"  fixed="left">
          <template slot-scope="scope">
            <div>
              <el-image :src="scope.row.mainImageUrl" style="width: 40px; height: 40px" class="image" :preview-src-list="[scope.row.mainImageUrl]" />
              {{ scope.row.productName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column slot="options" label="操作" align="center" fixed="right" width="140px">
          <template v-slot="{ row }">
            <div class="table-options">
              <el-button type="text" @click="toAdd(row.url)">编辑</el-button>
              <el-button type="text" @click="toDetail(row.url)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </ai-table>
      <ai-dialog
        :visible.sync="isShow"
        title="添加SKU"
        width="1400px"
        @confirm="onConfirm">
        <div class="search-item__wrapper">
          <div class="left">
            <div class="search-item">
              <label>添加方式：</label>
              <el-radio-group v-model="addType" size="small" @change="onSearchRest">
                <el-radio-button label="1">按类目添加</el-radio-button>
                <el-radio-button label="2">按SKC添加</el-radio-button>
                <el-radio-button label="3">按SKU添加</el-radio-button>
              </el-radio-group>
            </div>
            <div class="search-item">
              <label>店铺：</label>
              <el-select v-model="skuSearch.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>
            </div>
          </div>
          <div class="right"></div>
        </div>
        <div class="search-item__wrapper">
          <div class="left">
            <div class="search-item" v-show="addType === '1'">
              <label>商品分类：</label>
              <el-cascader
                style="width: 280px;"
                v-model="targetCatId"
                :props="props"
                size="small"
                filterable
                :show-all-levels="false"
                collapse-tags
                clearable>
              </el-cascader>
              <el-button style="margin-left: 10px;" @click="onCateChange" size="small" :disabled="!skuSearch.mallId" :loading="isLoading">查询</el-button>
            </div>
          <div class="search-item" v-show="addType === '2'">
            <label>SKC：</label>
            <el-input
              v-model="skuReqParams.SKC"
              style="width: 250px"
              size="small"
              v-throttle="() => {getSkuList()}"
              placeholder="多个查询请用户逗号分割"
              clearable
              @clear="getSkuList()"
              suffix-icon="iconfont iconSearch">
            </el-input>
            <el-button style="margin-left: 10px;" @click="getSkuList" size="small" :disabled="!skuSearch.mallId" :loading="isLoading">查询</el-button>
          </div>
          <div class="search-item" v-show="addType === '3'">
            <label>SKU：</label>
            <el-input
              v-if="addType === '3'"
              v-model="skuReqParams.SKU"
              style="width: 250px"
              size="small"
              v-throttle="() => {getSkuList()}"
              placeholder="多个查询请用户逗号分割"
              clearable
              @clear="getSkuList()"
              suffix-icon="iconfont iconSearch">
            </el-input>
            <el-button style="margin-left: 10px;" @click="getSkuList" size="small" :disabled="!skuSearch.mallId" :loading="isLoading">查询</el-button>
          </div>
          </div>
        </div>
        <ai-table
          height="370"
          :tableData="skuList"
          :col-configs="colConfigs"
          :total="skuTotal"
          :current.sync="skuSearch.current"
          :size.sync="skuSearch.size"
          style="margin-top: 8px;"
          @getList="getSkuList"
          :pageSizes="[10, 20, 50, 100, 500, 1000]"
          v-loading="isLoading"
          :isShowPagination="false">
          <el-table-column slot="productName" width="300px" :show-overflow-tooltip="true" label="商品名称"  fixed="left">
            <template slot-scope="scope">
              <div>
                <el-image :src="scope.row.mainImageUrl" style="width: 40px; height: 40px" class="image" :preview-src-list="[scope.row.mainImageUrl]" />
                {{ scope.row.productName }}
              </div>
            </template>
          </el-table-column>
        </ai-table>
      </ai-dialog>
    </template>
  </ai-list>
</template>

<script>
  import { sendChromeAPIMessage } from '@/api/chromeApi'
  export default {
    name: 'SkuManage',

    data () {
      return {
        colConfigs: [
          { type: 'selection' },
          // { slot: 'productName', label: '商品名称', width: '300px', align: 'left', fixed: 'left' },
          // { prop: 'category', label: '分类', width: '140px', align: 'left', fixed: 'left' },
          { prop: 'mallName', label: '店铺名称', align: 'left' },
          { prop: 'labelCode', label: '条码编码', align: 'center' },
          // { prop: 'productSkcId', label: 'SKC', align: 'left' },
          { prop: 'productSkuId', label: 'SKU', align: 'center' },
          // { prop: 'extCode', label: 'SKC货号', align: 'left' },
          { prop: 'skuExtCode', label: 'SKU货号',  align: 'center' },
          { prop: 'skuSpecName', label: '次销售属性', align: 'center' }
        ],
        tableData: [],
        total: 0,
        search: {
          current: 1,
          size: 100
        },
        skuSearch: {
          current: 1,
          size: 100,
          mallId: ''
        },
        skuTotal: 0,
        skuList: [],
        isShow: false,
        skuReqParams: {
          page: 1,
          pageSize: 100,
          SKC: '',
          SKU: ''
        },
        isLoading: false,
        addType: '1',
        props: {
          value: 'catId',
          label: 'catName',
          multiple: true,
          checkStrictly: true,
          lazy: true,
          lazyLoad (value, resolve) {
            sendChromeAPIMessage({
              url: 'bg-anniston-mms/category/children/list',
              needMallId: true,
              data: {
                parentCatId: value.level === 0 ? '' : value.value
              }
            }).then(res => {
              if (res.errorCode === 1000000) {
                resolve(res.result.categoryNodeVOS.map(v => {
                  return {
                    ...v,
                    leaf: v.isLeaf
                  }
                }))
              }
            })
          }
        },
        targetCatId: []
      }
    },

    computed: {
      currMall () {
        if (!this.$store.state.mallList.length) {
          return {}
        }

        return this.$store.state.mallList.filter(v => v.mallId === this.skuSearch.mallId)[0]
      }
    },

    created () {
      this.getList()
    },

    methods: {
      toAdd () {
        this.$router.push('/addLabelsTemplate')
      },

      onSearchRest() {
        this.skuReqParams.SKC = ''
        this.skuReqParams.SKU = ''
      },

      handleSelectionChange(e) {
        console.log(e)
      },

      getSKCList(catIds, page) {
        return new Promise(resolve => {
          sendChromeAPIMessage({
            url: 'bg-visage-mms/product/skc/pageQuery',
            needMallId: true,
            mallId: this.skuSearch.mallId,
            anti: true,
            data: {
              page: 1,
              pageSize: 200,
              catIds: catIds
            }
          }).then(res => {
            if (res.errorCode == 1000000) {
              resolve({
                list: res.result.pageItems.map(v => v.productSkcId),
                isHasNext: page * 200 < res.result.total
              })
            } else {
              resolve({ list: [], isHasNext: false })
            }
          }).catch(() => {
            resolve({ list: [], isHasNext: false })
          })
        })
      },

      async onCateChange() {
        let page = 1
        let list = []
        let isHasNext = true
        this.isLoading = true
        while (isHasNext) {
          const result = await this.getSKCList([].concat(this.targetCatId.flat()), page)
          page = page + 1
          isHasNext = result.isHasNext ? true : false
          list.push(...result.list)

          await this.$sleepSync(5000)
        }

        const skcList = [...new Set(list)]
        const len = Math.ceil(skcList.length / 100)
        for (let i = 0; i < len; i++) {
          this.skuReqParams.page = 1
          this.skuReqParams.SKC = [...new Set(list)].slice(i * 100, i * 100 + 100).join(',')
          await this.requestSKUList()
          await this.$sleepSync(2000)
        }
      },

      requestSKUList() {
        this.isLoading = true
        return sendChromeAPIMessage({
          url: 'bg-visage-mms/labelcode/pageQuery',
          needMallId: true,
          mallId: this.skuSearch.mallId,
          anti: true,
          data: {
            page: this.skuReqParams.page,
            pageSize: 200,
            productSkcIdList: (['2', '1'].includes(this.addType)) ? this.skuReqParams.SKC.split(',') : [],
            productSkuIdList: this.addType === '3' ? this.skuReqParams.SKU.split(',') : []
          }
        }).then(async (res) => {
          if (res.errorCode == 1000000) {
            const list = res.result.pageItems.map(v => {
              return {
                mallId: this.skuSearch.mallId,
                mallName: this.currMall.mallName,
                productName: v.productName,
                productSkuId: v.labelCodeVO.productSkuId,
                labelCode: v.labelCodeVO.labelCode,
                skuExtCode: v.labelCodeVO.skuExtCode,
                skuSpecName: v.productSkuSpecList.map(item => {
                  return item.specName
                }).join(',')
              }
            })
            this.skuTotal = res.result.total
            this.skuList.push(...list)

            if (res.result.total > this.skuList.length) {
              this.skuReqParams.page++
              await this.$sleepSync(5000)
              await this.requestSKUList()
            } else {
              this.isLoading = false
            }
          }
        })
      },

      getSkuList () {
        if (!this.skuSearch.mallId) {
          return this.$message.error('请选择店铺')
        }

        this.$userCheck(this.skuSearch.mallId).then(() => {
          this.skuList = []
          this.skuReqParams.page = 1
          this.isLoading = true

          this.requestSKUList()
        }).catch(() => {
          this.skuSearch.mallId = ''
        })
      },

      getList () {
        this.$http.post('/api/learning/pluginPage', null, {
          params: {
            ...this.search
          }
        }).then(res => {
          if (res.code === 0) {
            this.tableData = res.data.records
            this.total = res.data.total
          }
        })
      },

      onConfirm () {

      }
    }
  }
</script>

<style scoped lang="scss">
  .Template {
    .search-item__wrapper {
      display: flex;
      align-items: center;
      justify-content: space-between;

      &>div {
        display: flex;
        align-items: center;
      }
    }
  }
</style>
