<template>
  <ai-list class="list" v-loading="isLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading">
    <ai-title
      slot="title"
      title="希音标签信息"
      isShowBottomBorder>
    </ai-title>
    <template slot="content">
      <ai-search-bar>
        <template #left>
          <div class="search-item">
            <el-checkbox v-model="search.unSet">只显示未填写</el-checkbox>
          </div>
          <div class="search-item">
            <label>SKC ID：</label>
            <el-input size="small" clearable placeholder="请输入SKC ID" v-model="search.skc"></el-input>
          </div>
        </template>
        <template #right>
          <!--<el-button type="primary" @click="toLoad">加载</el-button>-->
        </template>
      </ai-search-bar>
      <ai-card title="SKC明细" style="padding-bottom: 40px;">
        <template #right>
          <el-button type="primary" @click="exportToExcel">导出</el-button>
          <el-button type="primary" @click="toUpload">导入</el-button>
        </template>
        <ai-table
          :isShowPagination="false"
          :tableData="filteredData"
          :col-configs="colConfigs"
          height="600"
          style="margin-top: 8px;"
          @getList="() => {}">
          <el-table-column slot="options" label="操作" width="80px" show-overflow-tooltip align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button
                size="small"
                type="success"
                icon="el-icon-circle-check"
                @click="edit(row)"
              ></el-button>
            </template>
          </el-table-column>
        </ai-table>
      </ai-card>

      <AiDialog
        title="标签信息导入"
        :visible.sync="sheinLabelDlgShow"
        :close-on-click-modal="false"
        customFooter
        width="1290px">
        <el-form :model="sheinLabelForm" ref="sheinLabelForm" label-width="180px" class="form">
          <el-form-item label="上传excel" prop="file" :rules="[{ required: true, message: '请上传文件', trigger: 'blur' }]" style="width: 100%;">
            <ai-uploader isImport v-model="sheinLabelForm.file" fileType="file" :limit="1"
                        acceptType=".xlsx," :clearable="false">
              <template #trigger>
                <el-button icon="iconfont iconfangda">选择文件</el-button>
              </template>
              <template #tips>最多上传1个文件,单个文件最大10MB，仅支持Excel格式</template>
            </ai-uploader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="sheinLabelDlgShow = false">关 闭</el-button>
          <el-button type="primary" @click="importConfirm">确 定</el-button>
        </span>
      </AiDialog>
    </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: 'LabelInfoShein',

    data () {
      return {
        isLoading: false,
        list: [],
        mallId: '',
        colConfigs: [
          { prop: 'skc', label: 'SKC ID', align: 'left' },
          { prop: 'supplierCode', label: 'SKC货号', align: 'left' },
          { prop: 'model', label: '型号', align: 'left' },
          { prop: 'ratedVoltage', label: '额定电压', align: 'left' },
          { prop: 'ratedCurrent', label: '额定电流', align: 'left' },
          { prop: 'productDate', label: '生产日期', align: 'left' },
          { prop: 'warranty', label: '保质期', align: 'left' },
          { prop: 'templateName', label: '模板名称', align: 'left' }
        ],
        search: {
          unSet: false,
          skc: ''
        },

        tableData: [],
        currentPage: 1,

        sheinLabelList: [],

        sheinLabelDlgShow: false,
        sheinLabelForm: {
          file: null
        }
      }
    },

    computed: {
      filteredData() {
        const filteredData = this.list.filter(item => {
          let flag1 = true, flag2 = true
          if (this.search.unSet) {
            if (item.templateName) flag1 = false
          }
          if (this.search.skc) {
            if (!item.skc.toLowerCase().includes(this.search.skc.toLowerCase())) {
              flag2 = false
            }
          }

          return flag1 && flag2
        })

        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: `spmp-api-prefix/spmp/product/list?page_num=${this.currentPage}&page_size=100`,
          method: 'POST',
          data: {
            language: "zh-cn",
            search_abandon_product: false,
            sort_type: 1
          }})
        if (res.code == '0') {
          for(let i = 0;i < res.info.data.length; i++) {
            let item = res.info.data[i];
            let data = {}
            
            for (let j = 0; j < item.skc_info_list.length; j++) {
              let skc = item.skc_info_list[j]
              data = {skc: skc.skc_name,
                supplierCode: skc.supplier_code,
                model: null,
                ratedVoltage: null,
                ratedCurrent: null,
                productDate: null,
                warranty: null,
                templateName: null
              }

              this.list.push(data)
            }
          }
          if (res.info.data.length == 100 && (res.meta.count > 100*this.currentPage)) {
            this.currentPage++
            await this.sleepSync(200)
            await this.getList()
          } else {
            this.getSkcLabelInfoList()
          }
        } 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));
      },
      getSkcLabelInfoList() {
        this.$http.post(`/api/sheinLabel/listAll`, null, {
          params: {
            mallId: this.mallId
          }
        }).then(res => {
          if (res.code == 0) {
            this.sheinLabelList = res.data
            for (let i = 0; i < this.sheinLabelList.length; i++) {
              for (let j = 0; j < this.list.length; j++) {
                if (this.sheinLabelList[i].skc == this.list[j].skc) {
                  this.list[j].model = this.sheinLabelList[i].model
                  this.list[j].ratedVoltage = this.sheinLabelList[i].ratedVoltage
                  this.list[j].ratedCurrent = this.sheinLabelList[i].ratedCurrent
                  this.list[j].productDate = this.sheinLabelList[i].productDate
                  this.list[j].warranty = this.sheinLabelList[i].warranty
                  this.list[j].templateName = this.sheinLabelList[i].templateName
                }
              }
            }
            this.isLoading = false
          }
        })
      },
      handleSave(row) {
        this.$http.post(`/api/sheinLabel/addOrUpdate`, [{
          mallId: this.mallId,
          costPrice: row.editValue,
          skc: row.skc,
          sku: row.sku
        }]).then((res) => {
          if (res.code == 0) {
            row.edit = false
            row.costPrice = row.editValue
            row.profitPercent = Math.round((row.price - row.costPrice) / row.price * 10000) / 100
            Message.success("修改成功")
          }
        })
      },
      toUpload() {
        this.sheinLabelDlgShow = true
      },
      importConfirm() {
        this.$refs.sheinLabelForm.validate((valid) => {
          const data = new FormData()
          data.append('file', this.sheinLabelForm.file[0].raw);
          this.$http.post(`/api/sheinLabel/import`, data).then(res => {
            if (res.code === 0) {
              this.sheinLabelDlgShow = false
              this.$message.success('导入成功')
              this.currentPage = 1
              this.list = []
              this.isLoading = true
              this.getList()
            }
          })
        })
      },
      exportToExcel() {
        // 假设你有一个表格数据的数组
        const data = [
          ["店铺ID", "SKC ID", "SKC货号", "型号", "额定电压", "额定电流", "生产日期", "保质期", "模板名称"]
        ]

        this.filteredData.map(item => {
          data.push([this.mallId, item.skc, item.supplierCode, item.model, item.ratedVoltage, item.ratedCurrent, item.productDate, item.warranty, item.templateName])
        })
  
        // 将数据转换为工作表
        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, 'SKC标签信息列表.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>
