<template>
  <a-modal
    :title="modalTitle"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item
        label="上传文件"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-upload :fileList="fileList" :multiple="true" @change="handleChange" :remove="handleRemove" :beforeUpload="beforeUpload">
          <a-button> <a-icon type="upload" />选择上传文件</a-button>
        </a-upload>
      </a-form-item>
    </a-form>
    <title-divider title="导入结果" width="90px"></title-divider>
    <a-table
      :data-source="data"
      :columns="columns"
      bordered
      tableLayout="auto"
      rowKey="id">
    </a-table>
    <p style="color: red">注意事项：<br/>
      1：请确保文件中对应设备新号已经设置<br/>
      2：请确保保养对应的设备部位、指定的人员员均已在系统中设置<br/>
      3：导入如出现问题，请及时联系<br/>
    </p>
    <template slot="footer">
      <a-button :loading="confirmLoading" v-show="data.length===0" type="primary" @click="save()">确定</a-button>
      <a-button type="primary" @click="handleCancel">关闭</a-button>
    </template>
  </a-modal>
</template>

<script>
import { importCheckStandard, importCheckStandardOldVersion, importCheckStandardByUpdate } from '@/api/check/checkstandard'

export default {
  name: 'SbModelBomImportForm',
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      type: null,
      fileList: [],
      // 表头
      columns: [
        {
          title: '编号',
          dataIndex: 'id'
        },
        {
          title: '文件名',
          dataIndex: 'name'
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: '100px'
        },
        {
          title: '原因',
          dataIndex: 'reason'
        }
      ],
      data: []
    }
  },
  methods: {
    base (type) {
      this.visible = true
      this.modalTitle = '维护标准导入'
      this.type = type
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload (file) {
      const reg = /\.(xls|xlsx)(\?.*)?$/
      return new Promise((resolve, reject) => {
        if (reg.test(file.name)) {
          this.fileList = [...this.fileList, file]
          return false
        } else {
          this.$message.error(`请上传正确的excel文件`)
          reject(new Error('请上传正确的excel文件'))
          return false
        }
      })
    },
    handleChange (info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} file uploaded successfully`)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        const formData = new FormData()
        // 循环添加到formData中
        this.fileList.forEach(function (file) {
          formData.append('files', file, file.name)
        })
        if (this.type === 0) {
          importCheckStandard(formData)
            .then((res) => {
              // 循环添加到formData中
              const resultArr = res.data.split(';')
              const result = []
              for (let i = 0; i < resultArr.length; i++) {
                const r = resultArr[i]
                if (r.indexOf('成功') === 0) {
                  result.push({ id: i, name: r, status: '成功' })
                } else if (r.indexOf('失败') === 0) {
                  result.push({ id: i, name: r, status: '失败', reason: r.split(':')[2] })
                }
              }
              this.$message.success('导入结束，请查看结果表格')
              this.data = result
              // this.handleCancel(values)
              this.BaseTool.ListForm.clearOneList(this)
              this.fileList = []
              this.BaseTool.ListForm.pushOneListAddMore(this, res.data)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else if (this.type === 1) {
          importCheckStandardOldVersion(formData)
            .then((res) => {
              // 循环添加到formData中
              const resultArr = res.data.split(';')
              const result = []
              for (let i = 0; i < resultArr.length; i++) {
                const r = resultArr[i]
                if (r.indexOf('成功') === 0) {
                  result.push({ id: i, name: r, status: '成功' })
                } else if (r.indexOf('失败') === 0) {
                  result.push({ id: i, name: r, status: '失败', reason: r.split(':')[2] })
                }
              }
              this.$message.success('导入结束，请查看结果表格')
              this.data = result
              // this.handleCancel(values)
              this.BaseTool.ListForm.clearOneList(this)
              this.fileList = []
              this.BaseTool.ListForm.pushOneListAddMore(this, res.data)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          importCheckStandardByUpdate(formData)
            .then((res) => {
              // 循环添加到formData中
              const resultArr = res.data.split(';')
              const result = []
              for (let i = 0; i < resultArr.length; i++) {
                const r = resultArr[i]
                if (r.indexOf('成功') === 0) {
                  result.push({ id: i, name: r, status: '成功' })
                } else if (r.indexOf('失败') === 0) {
                  result.push({ id: i, name: r, status: '失败', reason: r.split(':')[2] })
                }
              }
              this.$message.success('导入结束，请查看结果表格')
              this.data = result
              // this.handleCancel(values)
              this.BaseTool.ListForm.clearOneList(this)
              this.fileList = []
              this.BaseTool.ListForm.pushOneListAddMore(this, res.data)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.fileList = []
      this.data = []
      this.form.resetFields()
      this.storeId = null
      this.$emit('ok', values)
    }

  }
}
</script>
