<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>是否在售：</label>
              <el-select clearable v-model="reqData.skcSiteStatus" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="search-item">
              <label>站点：</label>
              <el-select v-model="reqData.bindSiteId" placeholder="请选择" size="small">
                <el-option
                  v-for="item in siteList"
                  :key="item.siteId"
                  :label="item.siteName"
                  :value="item.siteId">
                </el-option>
              </el-select>
            </div>
            <div class="search-item">
              <label>合规下架风险：</label>
              <el-select v-model="reqData.certPunishTypes" multiple placeholder="请选择" size="small">
                <el-option
                  v-for="item in certPunishTypes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="search-item">
              <label>资质上传状态：</label>
              <el-select v-model="reqData.productCertAuditStatuses" multiple placeholder="请选择" size="small">
                <el-option
                  v-for="item in productCertAuditStatusList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="search-item">
              <label>商品名称：</label>
              <el-input clearable size="small" placeholder="请输入商品名称" v-model="reqData.productName"></el-input>
            </div>
            <div class="search-item">
              <label>库存起始值：</label>
              <el-input size="small"  placeholder="请输入库存起始值" type="number" v-model="reqData.jitStockQuantitySection.leftValue"></el-input>
            </div>
            <div class="search-item">
              <label>库存结束值：</label>
              <el-input size="small"  placeholder="请输入库存结束值" type="number" v-model="reqData.jitStockQuantitySection.rightValue"></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>
              <json-excel
                  :data="tableData"
                  :fields="jsonFields"
                  name="商品列表.xls"
                  worksheet="商品列表">
                  <el-button type="primary" :disabled="tableData.length == 0">下载数据</el-button>
                </json-excel>
          </template>
          <ai-table
            :isShowPagination="false"
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="tableData.length"
            height="500"
            style="margin-top: 8px;"
            @getList="() => {}">

            <el-table-column slot="productName" width="200px" :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 {timestampToTime} from '@/utils/date'
import JsonExcel from 'vue-json-excel'

  export default {
    name: 'MyNormalOrder',

    data () {
      return {
        form: {
          mallId: ''
        },
        startPage: 1,
        endPage: 10,
        reqData: {
          productName: '',
          page: 1,
          pageSize: 100,
          skcSiteStatus: '',
          bindSiteId: '',
          certPunishTypes: [],
          productCertAuditStatuses: [],
          jitStockQuantitySection: {
            leftValue: '',
            rightValue: ''
          }
        },
        options: [
          {label: '是', value: 1},
          {label: '否', value: 0}
        ],
        colConfigs: [
          { slot: 'productName', label: '商品名称', width: '180px', align: 'left', fixed: 'left' },
          { prop: 'category', label: '分类', width: '140px', align: 'left', fixed: 'left' },
          { prop: 'productId', label: 'SPU ID', width: '120px', align: 'left' },
          { prop: 'productSkcId', label: 'SKC ID', width: '120px', align: 'left' },
          { prop: 'productSkuId', label: 'SKU ID', width: '120px', align: 'left' },
          { prop: 'skcSiteStatus', label: '是否在售', width: '120px', align: 'left' },
          { prop: 'extCode', label: 'SKC货号', width: '100px', align: 'left' },
          { prop: 'skuExtCode', label: 'SKU货号', width: '160px', align: 'left' },
          { prop: 'specName', label: 'SKU属性', width: '100px', align: 'left' },
          { prop: 'skuStockQuantity', label: '库存', width: '100px', align: 'left' },
          { prop: 'productCertAuditStatus', label: '资质上传状态', width: '120px', align: 'left' },
          { prop: 'certPunishType', label: '合规下架风险', width: '120px', align: 'left' },
          { prop: 'supplierPrice', label: '申报价格(CNY)', width: '180px', align: 'left' },
          { prop: 'todaySalesVolume', label: '今日销量', width: '100px', align: 'left' },
          { prop: 'createdAt', label: '上架时间', width: '160px', align: 'left' }
        ],
        isLoading: false,
        tableData: [],
        jsonFields: {
          "商品名称": "productName",
          "图片": "mainImageUrl",
          "分类": "category",
          "SPU ID": "productId",
          "SKC ID": "productSkcId",
          "SKU ID": "productSkuId",
          "是否在售": "skcSiteStatus",
          "SKC货号": "extCode",
          "SKU货号": "skuExtCode",
          "SKU属性": "specName",
          "库存": "skuStockQuantity",
          "资质上传状态": "productCertAuditStatus",
          "合规下架风险": "certPunishType",
          "申报价格(CNY)": "supplierPrice",
          "今日销量": "todaySalesVolume",
          "上架时间": "createdAt"
        },
        certPunishTypes: [
          {id: 1, name: '已经处罚'},
          {id: 2, name: '即将下架'},
          {id: 3, name: '下架风险预警'},
        ],
        productCertAuditStatusList: [
          {id: 1, name: '待上传'},
          {id: 2, name: '上传中'},
          {id: 3, name: '上传失败'},
          {id: 4, name: '上传成功'},
        ],
        currentIndex: 0,
        siteList: []
      }
    },
    components: {
      JsonExcel
    },
    created () {
      this.getSiteList()
    },
    methods: {
      async getSiteList() {
        let res = await sendChromeAPIMessage({
          url: 'bg-visage-mms/config/common/site/query',
          needMallId: true,
          mallId: this.$store.state.mallList[0].mallId,
          data: {}})
        if (res.success && res.errorCode == 1000000) {
          this.siteList = res.result.siteBaseList.filter(item => {
            return item.matchSemiManaged
          })
        }
      },
      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
        }
        this.reqData.page = this.startPage
        this.tableData = []
        this.currentIndex = 0
        this.isLoading = true
        this.load()
      },
      load() {
        sendChromeAPIMessage({
          url: 'bg-visage-mms/product/skc/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.mainImageUrl
                data.productId = item.productId
                data.productSkcId = item.productSkcId
                data.skcSiteStatus = item.skcSiteStatus == '1'? '在售': ''
                data.createdAt = timestampToTime(item.createdAt) 
                data.extCode = item.extCode
                data.productCertAuditStatus = '-'
                if (item.productCertAuditStatus == 1) {
                  data.productCertAuditStatus = '待上传'
                } else if (item.productCertAuditStatus == 2) {
                  data.productCertAuditStatus = '上传中'
                } else if (item.productCertAuditStatus == 3) {
                  data.productCertAuditStatus = '上传失败'
                } else if (item.productCertAuditStatus == 4) {
                  data.productCertAuditStatus = '上传成功'
                }
                data.certPunishType = '-'
                if (item.productCertPunish?.certPunishType == 1) {
                  data.certPunishType = '已经处罚'
                } else if (item.productCertPunish?.certPunishType == 2) {
                  data.certPunishType = '即将下架'
                } else if (item.productCertPunish?.certPunishType == 3) {
                  data.certPunishType = '下架风险预警'
                }

                data.category = ''
                for (let i = 1; i < 11; i++) {
                  if (item.categories['cat'+i].catName) {
                    data.category += '->' + item.categories['cat'+i].catName
                  } else {
                    break
                  }
                }
                data.category = data.category.substring(2)

                for(let k = 0; k < item.productSkuSummaries.length; k++) {
                  let temp = item.productSkuSummaries[k].productSkuSpecList.map(item2 => {
                    return item2.parentSpecName + "：" + item2.specName
                  })
                  let skuStockQuantity = '-'
                  if (item.productSkuSummaries[k].productSkuSemiManagedStock) {
                    skuStockQuantity = item.productSkuSummaries[k].productSkuSemiManagedStock.skuStockQuantity
                  }
                  data = {...data,
                    productSkuId: item.productSkuSummaries[k].productSkuId,
                    skuExtCode: item.productSkuSummaries[k].extCode,
                    supplierPrice: item.productSkuSummaries[k].supplierPrice / 100,
                    specName: temp.join("，"),
                    skuStockQuantity,
                    todaySalesVolume: item.productSkuSummaries[k].todaySalesVolume
                  }

                    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
              }
            }
          })
      }
    }
  }
</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>