<template>
  <ai-list class="list" v-loading="isLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <ai-title
      slot="title"
      title="商品条码管理"
      tips="每页为100条商品数据"
      isShowBottomBorder>
      <template #rightBtn>
        <div class="title-right">
          <div>
            <label style="width:90px">店铺：</label>
            <el-select v-model="form.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>
      </template>
    </ai-title>
    <template slot="content">
      <div class="content">
        <ai-search-bar>
          <template #left>
            <div class="search-item">
              <label>起始页：</label>
              <el-input size="small"  placeholder="请输入起始页" type="number" v-model="startPage"></el-input>
            </div>
            <div class="search-item">
              <label>结束页：</label>
              <el-input size="small"  placeholder="请输入起始页" type="number" v-model="endPage"></el-input>
            </div>
            <div class="search-item">
              <label>SKC：</label>
              <el-input size="small"  placeholder="请输入SKC，多个用逗号隔开" v-model="skcs"></el-input>
            </div>
          </template>
          <template #right>
            <el-button type="primary" @click="toLoad">加载</el-button>
          </template>
        </ai-search-bar>
        <ai-card title="数据明细" style="padding-bottom: 40px;">
          <template #right>
            <el-button type="primary" :disabled="tableData.length == 0" @click="exportWaitUploadToExcel">导出当前</el-button>
            <el-button type="primary" @click="exportAllToExcel">导出所有店铺</el-button>
          </template>
          <ai-table
            :isShowPagination="false"
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="tableData.length"
            height="700"
            style="margin-top: 8px;"
            @getList="() => {}">

            <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-card>
      </div>
    </template>
  </ai-list>
</template>

<script>
import { Message } from 'element-ui'
import {sendChromeAPIMessage} from '@/api/chromeApi'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

  export default {
    name: 'ProductLabel',

    data () {
      return {
        form: {
          mallId: ''
        },
        startPage: 1,
        endPage: 10,
        skcs: null,
        reqData: {
          page: 1,
          pageSize: 100
        },
        colConfigs: [
          { slot: 'productName', label: '商品名称', width: '300px', align: 'left', fixed: 'left' },
          { prop: 'category', label: '分类', width: '140px', align: 'left', fixed: 'left' },
          { prop: 'labelCode', label: '条码编码', align: 'left' },
          { prop: 'productSkcId', label: 'SKC', align: 'left' },
          { prop: 'productSkuId', label: 'SKU', align: 'left' },
          { prop: 'extCode', label: 'SKC货号', align: 'left' },
          { prop: 'skuExtCode', label: 'SKU货号',  align: 'left' },
          { prop: 'skcSpecName', label: '主销售属性',  align: 'left' },
          { prop: 'skuSpecName', label: '次销售属性', width: '100px', align: 'left' }
        ],
        isLoading: false,
        tableData: [],
        currentIndex: 0
      }
    },
    created () {
    },
    methods: {
      beforeGetList() {
        this.$userCheck(this.form.mallId).then(() => {
          this.toLoad()
        }).catch((err) => {
          this.form.mallId = ''
        })
      },
      toLoad() {
        if (!this.form.mallId) {
          Message.error("请选择店铺")
          return
        }
        if (!this.startPage || (this.startPage < 1)) {
          Message.error("起始页不能为空，且不能小于1")
          return
        }
        if (!this.endPage || (this.startPage < 1)) {
          Message.error("结束页不能为空")
          return
        }
        if (this.startPage > this.endPage) {
          Message.error("起始页不能大于结束页")
          return
        }
        if (this.skcs) {
          this.reqData.productSkcIdList = this.skcs.split(',')
        }
        this.$userCheck(this.form.mallId).then(() => {
          this.reqData.page = this.startPage
          this.tableData = []
          this.currentIndex = 0
          this.isLoading = true
          this.load()
        }).catch((err) => {
          this.form.mallId = ''
        })
      },
      load() {
        sendChromeAPIMessage({
          url: 'bg-visage-mms/labelcode/pageQuery',
          needMallId: true,
          mallId: this.form.mallId,
          anti: true,
          data: this.reqData}).then((res) => {
            if (res.errorCode == 1000000) {
              for(let i = 0;i < res.result.pageItems.length; i++) {
                let item = res.result.pageItems[i];
                let data = {};
                data.productName = item.productName
                data.mainImageUrl = item.displayImage
                data.productSkcId = item.labelCodeVO.productSkcId
                data.productSkuId = item.labelCodeVO.productSkuId
                data.labelCode = item.labelCodeVO.labelCode
                data.extCode = item.labelCodeVO.skcExtCode
                data.skuExtCode = item.labelCodeVO.skuExtCode
                data.category = item.leafCat.catName

                let temp = item.productSkcSpecList.map(item2 => {
                  return item2.specName
                })
                data.skcSpecName = temp.join(',')

                temp = item.productSkuSpecList.map(item2 => {
                  return item2.specName
                })
                data.skuSpecName = temp.join(',')

                this.tableData.push(data)

              }
              if (res.result.pageItems.length == this.reqData.pageSize && this.reqData.page < this.endPage) {
                this.reqData.page ++
                this.load()
              } else {
                this.isLoading = false
              }
            }
          })
      },
      async exportAllToExcel() {
        this.isLoading = true
        let list = []
        for (let j = 0; j < this.$store.state.mallList.length; j++) {
          let page = 1
          while(true) {
            let res = await sendChromeAPIMessage({
              url: 'bg-visage-mms/labelcode/pageQuery',
              needMallId: true,
              mallId: this.$store.state.mallList[j].mallId,
              anti: true,
              data: {
                page: page,
                pageSize: 100
              }})
            if (res.errorCode == 1000000) {
              for(let i = 0;i < res.result.pageItems.length; i++) {
                let item = res.result.pageItems[i];
                let data = {};
                data.productName = item.productName
                data.mainImageUrl = item.displayImage
                data.productSkcId = item.labelCodeVO.productSkcId
                data.productSkuId = item.labelCodeVO.productSkuId
                data.labelCode = item.labelCodeVO.labelCode
                data.extCode = item.labelCodeVO.skcExtCode
                data.skuExtCode = item.labelCodeVO.skuExtCode
                data.category = item.leafCat.catName
                data.displayImage = item.displayImage
                data.mallName = this.$store.state.mallList[j].mallName

                let temp = item.productSkcSpecList.map(item2 => {
                  return item2.specName
                })
                data.skcSpecName = temp.join(',')

                temp = item.productSkuSpecList.map(item2 => {
                  return item2.specName
                })
                data.skuSpecName = temp.join(',')

                list.push(data)
              }

              if (res.result.pageItems.length == 100) {
                page ++
              } else {
                break
              }
            }
            await this.$sleepSync(200)
          }
        }

        // 假设你有一个表格数据的数组
        const data = [
          ["商品名称", "分类", "条码编码", "SKC","SKU", "SKC货号", "SKU货号", "主销售属性", "次销售属性", "模板名称", "店铺名称", "图片"]
        ]

        list.map(item => {
          data.push([item.productName, item.category, item.labelCode, item.productSkcId, item.productSkuId, item.extCode, item.skuExtCode, item.skcSpecName, item.skuSpecName, "", item.mallName, item.displayImage])
        })
  
        // 将数据转换为工作表
        const worksheet = XLSX.utils.aoa_to_sheet(data);
  
        // 创建工作簿并添加工作表
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  
        // 生成Excel文件
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  
        // 使用blob和FileReader创建一个Blob URL
        const dataBlob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
        const blobUrl = window.URL.createObjectURL(dataBlob);
  
        // 使用saveAs下载文件
        saveAs(dataBlob, '商品条码列表.xlsx');
  
        // 清理
        window.URL.revokeObjectURL(blobUrl);

        this.isLoading = false

      },
      exportWaitUploadToExcel() {
        // 假设你有一个表格数据的数组
        const data = [
          ["商品名称", "分类", "条码编码", "SKC","SKU", "SKC货号", "SKU货号", "主销售属性", "次销售属性"]
        ]

        this.tableData.map(item => {
          data.push([item.productName, item.category, item.labelCode, item.productSkcId, item.productSkuId, item.extCode, item.skuExtCode, item.skcSpecName, item.skuSpecName])
        })
  
        // 将数据转换为工作表
        const worksheet = XLSX.utils.aoa_to_sheet(data);
  
        // 创建工作簿并添加工作表
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  
        // 生成Excel文件
        const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  
        // 使用blob和FileReader创建一个Blob URL
        const dataBlob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
        const blobUrl = window.URL.createObjectURL(dataBlob);
  
        // 使用saveAs下载文件
        saveAs(dataBlob, '商品条码列表.xlsx');
  
        // 清理
        window.URL.revokeObjectURL(blobUrl);
      }
    }
  }
</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;
      }
    }
  }
</style>