<template>
  <a-modal
    centered
    class="importGuide-modal"
    :footer="null"
    :maskClosable="false"
    destroyOnClose
    title="导入产品"
    v-model="isShow"
    :closable="false"
    :width="850">
    <div class="importGuide-con">
      <div class="explain-con" v-show="step==0">
        <div class="explain-item">
          <div class="explain-tit">
            <span>1</span>准备导入
          </div>
          <ul>
            <li>1) 导入的Excel文件中必须包含名为“产品编码”、“数量”的列，且名称必须相同</li>
            <li>2) 除了“产品编码”、“数量”两列，其他列可自定义，不影响数据导入</li>
            <li>3) 如果导入的产品已经存在，则不会导入该行</li>
          </ul>
          <a-button
            id="importGuide-download"
            type="link"
            icon="download"
            style="padding: 0 0 0 23px;"
            :loading="spinning"
            @click="handleExport">下载导入模板</a-button>
        </div>
        <div class="explain-item">
          <div class="explain-tit">
            <span>2</span>上传数据文件
          </div>
          <p>目前支持的文件类型*.xls，*.xlsx.</p>
          <div style="overflow: hidden;padding-left: 23px;">
            <Upload
              id="importGuide-attachList"
              ref="importUpload"
              :maxNums="1"
              fileType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
              uploadType="import"
              :action="attachAction"
              :uploadParams="uploadParams"
              upText="添加文件"
              @change="changeImport"></Upload>
          </div>
        </div>
      </div>
      <!-- 第二步 -->
      <div v-show="step==1">
        <!-- 可导入数据 -->
        <p class="blue">可导入数据<span>{{ loadData.length }}</span>条</p>
        <a-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.no"
          :columns="nowColumns"
          :dataSource="loadData"
          :loading="spinning"
          :scroll="{ y: 200 }"
          :pagination="false"
          bordered>
        </a-table>
        <!-- 不可导入数据 -->
        <p class="red">不可导入数据<span>{{ unLoadData.length }}</span>条</p>
        <a-table
          class="unTable"
          ref="unTable"
          size="small"
          :rowKey="(record) => record.no"
          :columns="nowUnColumns"
          :dataSource="unLoadData"
          :loading="spinning"
          :scroll="{ y: 200 }"
          :pagination="false"
          bordered>
        </a-table>
      </div>
      <!-- 按钮 -->
      <div class="btn-con">
        <a-button
          id="importGuide-cancel"
          size="large"
          class="button-cancel"
          @click="handleCancel"
          :disabled="spinning"
          style="padding: 0 40px;margin-left: 15px;">取消</a-button>
        <a-button
          type="primary"
          id="importGuide-nextStep"
          size="large"
          class="button-primary"
          @click="handlerNextStep"
          v-if="step==0"
          :disabled="spinning"
          style="padding: 0 40px;margin-left: 15px;">下一步</a-button>
        <a-button
          type="default"
          id="importGuide-prevStep"
          size="large"
          v-if="step==1"
          class="button-primary"
          @click="handlerPrevStep"
          :disabled="spinning"
          style="padding: 0 40px;margin-left: 15px;">上一步</a-button>
        <a-button
          type="primary"
          id="chooseImport-submit"
          v-if="step==1"
          size="large"
          class="button-primary"
          @click="handleSubmit"
          :disabled="spinning"
          style="padding: 0 40px;margin-left: 15px;">确认导入</a-button>
        <a-button
          type="primary"
          id="chooseImport-error"
          v-if="step==1"
          size="large"
          class="button-error"
          :disabled="spinning"
          @click="handleError"
          style="padding: 0 40px;margin-left: 15px;">导出错误项</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
import { Upload } from '@/components'
// 接口
import { allocateBillDownload, allocateBillParseProducts, allocateBillFailExcel, allocateBillBatchInsert } from '@/api/allocateBill'
export default {
  name: 'TransferOutImportGuideModal',
  mixins: [commonMixin],
  components: { Upload },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    params: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      attachAction: process.env.VUE_APP_API_BASE_URL + '/upload', // 上传文件路径
      paramsData: null, // 上传参数
      uploadParams: { // 上传参数
        savePathType: 'local'
      },
      spinning: false, // 导出按钮加载状态
      step: 0,
      nowColumns: [ //  正品
        { title: '序号', dataIndex: 'no', width: 70, align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '数量', dataIndex: 'qtyText', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '库存', dataIndex: 'currentStockQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'productUnit', width: 60, align: 'center', customRender: function (text) { return text || '--' } }
      ],
      nowUnColumns: [ //  促销品
        { title: '序号', dataIndex: 'no', width: 70, align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '数量', dataIndex: 'qtyText', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '库存', dataIndex: 'currentStockQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'productUnit', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备注', dataIndex: 'errorDesc', width: 180, align: 'center', customRender: function (text) { return text || '--' } }
      ],
      loadData: [], // 可导入数据
      unLoadData: [] // 错误数据
    }
  },
  methods: {
    // 上传文件  change
    changeImport (file) {
      if (file) {
        this.paramsData = {
          allocateSn: this.params.allocateSn || '',
          path: file
        }
        this.loadData = []
        this.unLoadData = []
        this.handlerNextStep()
      } else {
        this.paramsData = null
      }
    },
    // 下一步
    handlerNextStep () {
      if (this.paramsData) {
        if (this.loadData.length == 0 && this.unLoadData.length == 0) {
          this.getData()
        }
        this.step = 1
      } else {
        this.$message.warning('添加文件后再进行下一步操作！')
      }
    },
    // 上一步
    handlerPrevStep () {
      const _this = this
      if (this.loadData.length) {
        this.$confirm({
          title: '提示',
          content: '当前页面数据未导入，是否返回上页？',
          centered: true,
          cancelText: '返回上页',
          okText: '继续导入',
          onOk () {
            _this.step = 1
          },
          onCancel () {
            _this.step = 0
          }
        })
      } else {
        _this.step = 0
      }
    },
    // 取消或关闭
    handleCancel () {
      const _this = this
      if (_this.loadData.length) {
        this.$confirm({
          title: '提示',
          content: '当前页面数据未导入，是否取消导入操作？',
          centered: true,
          cancelText: '确认取消',
          okText: '继续导入',
          onOk () {
            _this.step = 1
          },
          onCancel () {
            _this.isShow = false
          }
        })
      } else {
        _this.isShow = false
      }
    },
    // 获取表格数据
    getData () {
      const _this = this
      this.spinning = true
      // 获取列表数据  无分页
      allocateBillParseProducts(this.paramsData).then(res => {
        this.spinning = false
        if (res.status == 200) {
          if (res.data.okList && res.data.okList.length > 0) {
            res.data.okList.map((item, index) => {
              item.no = index + 1
            })
          }
          if (res.data.failList && res.data.failList.length > 0) {
            res.data.failList.map((item, index) => {
              item.no = index + 1
            })
          }
          _this.loadData = res.data.okList || []
          _this.unLoadData = res.data.failList || []
        }
      })
    },
    // 确认导入
    handleSubmit () {
      if (this.loadData.length == 0) {
        this.$message.warning('无可导入产品！')
      } else {
        this.spinning = true
        allocateBillBatchInsert(this.loadData).then(res => {
          if (res.status == 200) {
            this.$emit('ok')
            this.isShow = false
          }
          this.spinning = false
        })
      }
    },
    // 导出
    handleError () {
      const _this = this
      if (_this.unLoadData.length < 1) {
        _this.$message.info('暂无可导出错误项~')
        return
      }
      _this.spinning = true
      hdExportExcel(allocateBillFailExcel, _this.unLoadData, '产品导入错误项', function () {
        _this.spinning = false
      })
    },
    // 下载模板
    handleExport () {
      const _this = this
      _this.spinning = true
      allocateBillDownload({}).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 {
          this.download(res)
        }
      })
    },
    // 下载模板
    download (data) {
      if (!data) { return }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const fname = '调拨单产品导入模板'
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
      } else {
        this.paramsData = null
        if (this.$refs.importUpload) {
          this.$refs.importUpload.setFileList('')
        }
        this.loadData = []
        this.unLoadData = []
        this.step = 0
        this.spinning = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .importGuide-modal{
    .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;
            }
          }
        }
        #importGuide-attachList{
          width: 100%;
        }
      }
      .blue{
        span{
          color: #1890ff;
          margin: 0 5px;
        }
        margin: 10px 0;
      }
      .red{
        span{
          color: #f5222d;
          margin: 0 5px;
        }
        margin: 10px 0;
      }
      .btn-con{
        margin: 30px 0 20px;
        text-align: center;
      }
    }
  }
</style>
