<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>
          <el-radio-group v-model="certStatus" @change="getList">
            <el-radio-button label="refused">已驳回</el-radio-button>
            <el-radio-button label="waitUpload">待补充</el-radio-button>
          </el-radio-group>
        </template>
        <template #right>
        </template>
      </ai-search-bar>
      <ai-card v-if="certStatus == 'refused'" title="已驳回证书列表" style="padding-bottom: 40px;">
        <template #right>
          <el-button type="primary" @click="exportRefusedToExcel">导出</el-button>
        </template>
        <ai-table
          :isShowPagination="false"
          :tableData="refusedList"
          :col-configs="refusedColConfigs"
          height="700"
          style="margin-top: 8px;"
          @getList="() => {}">
          <el-table-column slot="auditStatus" width="120px" label="状态" align="left">
            <template slot-scope="scope">
              <div style="color: red">
                审批失败
              </div>
            </template>
          </el-table-column>
          <el-table-column slot="certName" label="证书名称" align="left">
            <template slot-scope="scope">
              <a v-for="item in scope.row.certName" :href="item.certificate_url" target="_blank">{{ item.certificate_url_name }}</a>
            </template>
          </el-table-column>
        </ai-table>
      </ai-card>
      <ai-card v-if="certStatus == 'waitUpload'" title="待补充证书列表" style="padding-bottom: 40px;">
        <template #right>
          <el-button type="primary" @click="exportWaitUploadToExcel">导出</el-button>
        </template>
        <ai-table
          :isShowPagination="false"
          :tableData="waitUploadList"
          :col-configs="waitUploadColConfigs"
          height="700"
          style="margin-top: 8px;"
          @getList="() => {}">
        </ai-table>
      </ai-card>
    </template>
  </ai-list>
</template>

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

  export default {
    name: 'CertCenterShein',

    data () {
      return {
        isLoading: false,
        mallId: '',
        certStatus: 'refused',
        waitUploadList: [],
        waitUploadColConfigs: [
          { prop: 'spu', label: 'SPU', align: 'left' },
          { prop: 'productName', label: '商品标题', align: 'left' },
          { prop: 'skc', label: 'SKC ID', align: 'left' },
          { prop: 'mainAttrName', label: '主规格', align: 'left' },
          { prop: 'certificateTypeName', label: '证书类型', align: 'left' },
          { prop: 'mergeSiteName', label: '管控地区', align: 'left' },
          { prop: 'subSite', label: '管控子站点', align: 'left' },
          { prop: 'uploadEndTime', label: '上传截止时间', align: 'left' }
        ],
        refusedList: [],
        refusedColConfigs: [
          { prop: 'spu', label: 'SPU', align: 'left' },
          { prop: 'productName', label: '商品标题', align: 'left' },
          { prop: 'skc', label: 'SKC ID', align: 'left' },
          { prop: 'mainAttrName', label: '主规格', align: 'left' },
          { slot: 'auditStatus', label: '状态' },
          { prop: 'certificateTypeName', label: '证书类型', align: 'left' },
          { slot: 'certName', label: '证书名称' },
          { prop: 'refusedReason', label: '审核备注', align: 'left' },
          { prop: 'mergeSiteName', label: '管控地区', align: 'left' },
          { prop: 'subSite', label: '管控子站点', align: 'left' }
        ],

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

    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.getList()
        }
      })
    },

    methods: {
      async getList () {
        this.isLoading = true
        this.currentPage = 1
        if (this.certStatus == 'refused') {
          this.refusedList = []
          await this.getRefusedList()
        } else {
          this.waitUploadList = []
          await this.getWaitUploadList()
        }
        this.isLoading = false
      },
      async getWaitUploadList() {
        let res = await sendGeiwohuoAPIMessage({
          url: `spmp-api-prefix/spmp/certificate/get_skc_certificate_miss_list?page_num=${this.currentPage}&page_size=200`,
          method: 'POST',
          data: {}})
        if (res.code == '0') {
          for(let i = 0;i < res.info.data.length; i++) {
            let item = res.info.data[i];
            let mainSite = []
            let subSite = []
            item.merge_site_info_list.map(e => {
              mainSite.push(e.merge_site_name)
              subSite = subSite.concat(e.sub_site_list)
            })
            let data = {spu: item.spu_name,
              productName: item.skc_name_cn,
              skc: item.skc_name,
              mainAttrName: item.main_attribute_name,
              uploadEndTime: item.upload_end_time,
              mergeSiteName: mainSite.join(','),
              certificateTypeName: item.certificate_type_name,
              subSite: subSite.join(',')
            }
    
            this.waitUploadList.push(data)
          }
          if (res.info.data.length == 200 && (res.info.meta.count > 200*this.currentPage)) {
            this.currentPage++
            await this.sleepSync(200)
            await this.getWaitUploadList()
          }
        } else if (res.code == 100004 || res.code == 20302) {
          this.$store.commit("setSheinAlertShow", true)
        }
      },
      async getRefusedList() {
        let res = await sendGeiwohuoAPIMessage({
          url: `spmp-api-prefix/spmp/certificate/get_skc_certificate_list?page_num=${this.currentPage}&page_size=200`,
          method: 'POST',
          data: {
            audit_status: 3
          }})
        if (res.code == '0') {
          for(let i = 0;i < res.info.data.length; i++) {
            let item = res.info.data[i];
            let mainSite = []
            let subSite = []
            item.merge_site_info_list.map(e => {
              mainSite.push(e.merge_site_name)
              subSite = subSite.concat(e.sub_site_list)
            })
            let data = {
              pqmsCertificateSn: item.pqms_certificate_sn,
              auditStatus: item.audit_status,
              spu: item.spu_name,
              productName: item.skc_name_cn,
              skc: item.skc_name,
              mainAttrName: item.main_attribute_name,
              mergeSiteName: mainSite.join(','),
              certificateTypeName: item.certificate_type_name,
              certName: item.cert_file_list,
              refusedReason: null,
              subSite: subSite.join(',')
            }
    
            this.refusedList.push(data)
          }
          if (res.info.data.length == 200 && (res.info.meta.count > 200*this.currentPage)) {
            this.currentPage++
            await this.sleepSync(200)
            await this.getRefusedList()
          } else {
            await this.getAuditInfo()
          }
        } else if (res.code == 100004 || res.code == 20302) {
          this.$store.commit("setSheinAlertShow", true)
        }
      },
      async getAuditInfo() {
        let pqmsList = []
        this.refusedList.map(item => {
          pqmsList.push(item.pqmsCertificateSn)
        })

        let res = await sendGeiwohuoAPIMessage({
          url: `spmp-api-prefix/spmp/certificate/get_cert_audit_fail_reason`,
          method: 'POST',
          data: {
            pqms_certificate_sn_list: pqmsList
          }})
        if (res.code == '0') {
          res.info.data.map(item => {
            for (let i = 0; i < this.refusedList.length; i++) {
              if (this.refusedList[i].pqmsCertificateSn == item.certificate_sn) {
                this.refusedList[i].refusedReason = item.fail_reason
                break
              }
            }
          })
        } else if (res.code == 100004 || res.code == 20302) {
          this.$store.commit("setSheinAlertShow", true)
        }
      },
      sleepSync(milliseconds) {
        return new Promise(resolve => setTimeout(resolve, milliseconds));
      },
      exportWaitUploadToExcel() {
        // 假设你有一个表格数据的数组
        const data = [
          ["SPU", "商品标题", "SKC ID", "主规格", "证书类型", "管控地区", "管控子站点", "上传截止时间"]
        ]

        this.waitUploadList.map(item => {
          data.push([item.spu, item.productName, item.skc, item.mainAttrName, item.certificateTypeName, item.mergeSiteName, item.subSite, item.uploadEndTime])
        })
  
        // 将数据转换为工作表
        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);
      },
      exportRefusedToExcel() {
        // 假设你有一个表格数据的数组
        const data = [
          ["SPU", "商品标题", "SKC ID", "主规格", "证书类型","证书名称", "证书地址", "审核备注", "管控地区", "管控子站点"]
        ]

        this.refusedList.map(item => {
          let certName = [], certUrl = []
          item.certName.map(item1 => {
            certName.push(item1.certificate_url_name)
            certUrl.push(item1.certificate_url)
          })
          data.push([item.spu, item.productName, item.skc, item.mainAttrName, item.certificateTypeName, certName.join(','), certUrl.join(','), item.refusedReason, item.mergeSiteName, item.subSite])
        })
  
        // 将数据转换为工作表
        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>
