<template>
  <a-card size="small" :bordered="false" class="bulkImportList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <div ref="tableSearch" class="table-page-search-wrapper">
        <Upload
          id="bulkImportList-attachList"
          ref="importUpload"
          :maxNums="1"
          fileType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
          uploadType="attach"
          :action="attachAction"
          :uploadParams="uploadParams"
          upText="选择导入文件"
          @remove="resetSearchForm"
          @change="changeImport"></Upload>
        <a :href="filePath" style="margin: 5px 0 0 15px;display: block;float: left;">
          <a-icon type="download" style="padding-right: 5px;" />下载导入模板
        </a>
      </div>
      <div class="importGuide-con">
        <div class="explain-con">
          <div class="explain-item">
            <div class="explain-tit">导入文件说明</div>
            <ul>
              <li>1) 导入的EXCEL文件中必须包含名为"产品编码"、"仓库"、"仓位"、"入库数量"、"成本价"；列顺序可忽略、行顺序可忽略。以产品编码,仓库,仓位，成本价作为导入的是否有效判断依据。</li>
              <li>2) 红色底白字为错误项，错误项忽略不能导入，正确项可直接导入。</li>
              <li>3) 入库数量必须大于0，且为正整数,为了保证数据的正确性,请检查上传文件数据无误后再上传操作。</li>
              <li>4) 成本价为必填项，必须填写大于等于零的数字。</li>
              <li>5) 支持上传文件格式：.xls、.xlsx。</li>
            </ul>
          </div>
        </div>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowClassName="(record, index) => record.isError==1 ? 'redBg-row':''"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
      </s-table>
      <div class="btn-con" v-if="uploadData && uploadData.stockImportSn">
        <a-button
          id="productInfoList-batchAudit"
          type="primary"
          class="button-warning"
          @click="handleConfirm"
          style="margin: 0 15px;">确认导入</a-button>
        <a-button
          id="productInfoList-batchLaunch"
          type="primary"
          class="button-primary"
          @click="handleCancel"
          style="margin: 0 15px;">取消导入</a-button>
        <a-button
          id="productInfoList-batchDownline"
          type="primary"
          class="button-grey"
          @click="handleExportError"
          style="margin: 0 15px;">导出错误项</a-button>
      </div>
    </a-spin>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, Upload } from '@/components'
import { stockImportList, stockImportFinish, stockImportCancel, stockImportKCExportError } from '@/api/stockImport'
import { downloadExcel } from '@/libs/JGPrint.js'
export default {
  name: 'StockImportList',
  components: { STable, Upload },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      exportLoading: false, // 导出loading
      tableHeight: 0,
      queryParam: {}, // 查询参数
      isAllError: false, // 是否全部错误
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '25%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '仓库', dataIndex: 'warehouseName', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '入库数量', dataIndex: 'putQty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '成本价', dataIndex: 'cost', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '错误原因', dataIndex: 'errorMsg', width: '20%', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        return stockImportList(Object.assign(parameter, { stockImportSn: this.uploadData && this.uploadData.stockImportSn })).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
            const ret = data.list.filter(item => item.isError == 1)
            this.isAllError = ret.length == data.count
          }
          this.spinning = false
          return data
        })
      },
      attachAction: process.env.VUE_APP_API_BASE_URL + '/stockImport/importForStock',
      uploadParams: {
        savePathType: 'local'
      },
      uploadData: null,
      filePath: 'https://jianguan-images.oss-cn-beijing.aliyuncs.com/template/StockImports.xlsx'
    }
  },
  methods: {
    // 上传文件  change
    changeImport (file) {
      if (file && JSON.parse(file).length > 0) {
        this.uploadData = JSON.parse(file)[0] || null
        if (this.uploadData && this.uploadData.stockImportSn) {
          this.$refs.table.refresh(true)
        }
      } else {
        this.uploadData = null
      }
    },
    resetSearchForm () {
      this.$refs.table.clearTable() //  清空列表数据
      this.$refs.importUpload.setFileList() //  清空导入文件
      this.uploadData = null //  清空上传数据
    },
    // 确认导入
    handleConfirm () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '您是否确认导入库存？',
        centered: true,
        onOk () {
          _this.spinning = true
          stockImportFinish({ stockImportSn: _this.uploadData && _this.uploadData.stockImportSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.resetSearchForm()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 取消导入
    handleCancel () {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '您确认取消导入库存？',
        centered: true,
        onOk () {
          _this.spinning = true
          stockImportCancel({ stockImportSn: _this.uploadData && _this.uploadData.stockImportSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.resetSearchForm()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 导出错误项
    handleExportError () {
      const _this = this
      _this.spinning = true
      stockImportKCExportError({ stockImportSn: _this.uploadData && _this.uploadData.stockImportSn }).then(res => {
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          downloadExcel(res, '库存导入错误项')
        }
      })
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 400
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less">
  .bulkImportList-wrap{
    .table-page-search-wrapper{
      overflow: hidden;
      .upload-file{
        height: auto;
        margin-bottom: 10px;
        .ant-btn{
          background-color: #f30;
          border-color: #f30;
          margin: 0 5px;
          font-size: 12px;
          color: #fff;
        }
      }
    }
    .importGuide-con{
      .explain-con{
        .explain-item{
          margin-bottom: 10px;
          .explain-tit{
            font-weight: bold;
            span{
              display: inline-block;
              width: 18px;
              height: 18px;
              line-height: 16px;
              text-align: center;
              margin-right: 5px;
              border-radius: 50%;
              border: 1px solid rgba(0, 0, 0, 0.3);
            }
          }
          p{
            margin: 8px 0;
            padding-left: 23px;
          }
          ul{
            list-style: none;
            padding: 0;
            padding-left: 23px;
            margin: 0;
            li{
              line-height: 26px;
              font-size: 12px;
            }
          }
        }
      }
    }
    .redBg-row{
      background-color: #F39494;
    }
    .btn-con{
      text-align: center;
    }
  }
</style>
