<template>
  <ai-list class="list" v-loading="isLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <ai-title
      slot="title"
      title="商品列表(ODM)"
      isShowBottomBorder>
    </ai-title>
    <template slot="content">
      <ai-search-bar>
        <template #left>
          <div class="search-item">
            <label>可售天数小于：</label>
            <el-input size="small" clearable placeholder="请输入SKC ID" v-model="search.ableSaleDays"></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" @click="exportToExcel">导出</el-button>
        </template>
        <ai-table
          :isShowPagination="false"
          :tableData="filteredData"
          :col-configs="colConfigs"
          height="600"
          style="margin-top: 8px;"
          @getList="() => {}">
          <el-table-column slot="goodsThumb" width="120px" label="商品图片" fixed="left">
            <template slot-scope="scope">
              <div>
                <el-image :src="scope.row.goodsThumb" style="width: 40px; height: 40px" class="image" :preview-src-list="[scope.row.goodsThumb]" />
              </div>
            </template>
          </el-table-column>
        </ai-table>
      </ai-card>
    </template>
  </ai-list>
</template>

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

  export default {
    name: 'ProductListOdm',

    data () {
      return {
        isLoading: false,
        list: [],
        mallId: '',
        colConfigs: [
          { slot: 'goodsThumb', label: '商品图片', align: 'left' },
          { prop: 'skc', label: 'SKC ID', align: 'left' },
          { prop: 'supplierCode', label: 'SKC货号', align: 'left' },
          { prop: 'sku', label: 'SKU ID', align: 'left' },
          { prop: 'suffixZh', label: '属性集', align: 'left' },
          { prop: 'num', label: '建议备货数量', align: 'left', sortable: true, 'sort-method': (a, b) => Number(a.num) - Number(b.num) },
          { prop: 'warningDaysNew', label: '备货预警天数', align: 'left' },
          { prop: 'ableSaleDays', label: '可售天数', align: 'left', sortable: true, 'sort-method': (a, b) => a.ableSaleDays - b.ableSaleDays },
          { prop: 'saleInfoWeek', label: '近7天销量', align: 'left', sortable: true, 'sort-method': (a, b) => a.saleInfoWeek - b.saleInfoWeek },
          { prop: 'saleInfoMonth', label: '本月销量', align: 'left', sortable: true, 'sort-method': (a, b) => a.saleInfoMonth - b.saleInfoMonth },
          { prop: 'saleInfoPreMonth', label: '上月销量', align: 'left', sortable: true, 'sort-method': (a, b) => a.saleInfoPreMonth - b.saleInfoPreMonth }
        ],
        search: {
          unSet: false,
          skc: '',
          sku: '',
          skcCode: ''
        },

        tableData: [],
        currentPage: 1,
      }
    },

    computed: {
      filteredData() {
        const filteredData = this.list.filter(item => {
          let flag1 = true
          if (this.search.ableSaleDays) {
            if ('' == item.ableSaleDays) flag1 = false
            else if (Number(item.ableSaleDays) > Number(this.search.ableSaleDays)) {
              flag1 = false
            }
          }

          return flag1
        })

        return filteredData
      }
    },

    mounted () {
      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;
          }
          this.getUserInfo()
          this.isLoading = true
          this.getList()
        }
      })
    },

    methods: {
      async getUserInfo() {
        let res = await sendGeiwohuoAPIMessage({
          url: 'sso-prefix/auth/getUser?uuid=' + Date.now(),
          method: 'GET'
        })
        if (res.code == '0' && res.msg == "OK") {
          this.mallId = res.info.merchantCode
        } else if (res.code == 100004 || res.code == 20302) {
          this.isLoading = false
          this.$store.commit("setSheinAlertShow", true)
        }
      },
      async getList () {
        let res = await sendGeiwohuoAPIMessage({
          url: `gmpj/goods/goods/list`,
          method: 'POST',
          data: {
            mallStatusList: [
              1
            ],
            page: this.currentPage,
            perPage: 100
          }})
        if (res.code == '0') {
          for(let i = 0;i < res.info.list.length; i++) {
            let item = res.info.list[i];
            let data = {
              goodsThumb: item.goodsThumb,
              skc: item.skc,
              supplierCode: item.supplierCode
            }
            
            for (let j = 0; j < item.sizes.length; j++) {
              let sku = item.sizes[j]
              data = {...data, 
                sku: sku.skuCode,
                suffixZh: sku.suffixZh,
                ableSaleDays: sku.ableSaleDays,
                saleInfoWeek: sku.saleInfoWeek,
                saleInfoMonth: sku.saleInfoMonth,
                warningDaysNew: item.warningDaysNew,
                saleInfoPreMonth: sku.saleInfoPreMonth
              }

              if (item.warningDaysNew > 0) {
                data.num = ((item.warningDaysNew - Number(sku.ableSaleDays)) * (sku.saleInfoWeek / 7)).toFixed(2)
                if (data.num < 0) {
                  data.num = 0
                }
              }

              this.list.push(data)
            }
          }
          if (res.info.list.length == 100 && (res.info.count > 100*this.currentPage)) {
            this.currentPage++
            await this.sleepSync(200)
            await this.getList()
          } else {
            this.isLoading = false
          }
        } else if (res.code == 100004 || res.code == 20302) {
          this.isLoading = false
          this.$store.commit("setSheinAlertShow", true)
        }
      },
      sleepSync(milliseconds) {
        return new Promise(resolve => setTimeout(resolve, milliseconds));
      },
      exportToExcel() {
        // 假设你有一个表格数据的数组
        const data = [
          ["商品图片", "SKC", "SKC货号", "SKU", "属性集", "建议备货数量", " 备货预警天数", "可售天数", "近7天销量", "本月销量", "上月销量"]
        ]

        this.filteredData.map(item => {
          data.push([item.goodsThumb, item.skc, item.supplierCode, item.sku, item.suffixZh, item.num, item.warningDaysNew, item.ableSaleDays, item.saleInfoWeek, item.saleInfoMonth, item.saleInfoPreMonth])
        })
  
        // 将数据转换为工作表
        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>
