<template>
  <!-- 新增 -->
  <div id="addWrap">
    <h2 class="title">{{ title }}</h2>

    <a-form-model
      ref="ruleForm"
      :model="form"
      v-bind="formItemLayout"
      :rules="rules"
    >
      <a-form-model-item
        label="文件名称："
        ref="form.fileName"
        prop="fileName">
        <a-input
          v-model="form.fileName"
          placeholder="请输入文件名称"
          :onkeyup="form.fileName = form.fileName.replace(/\s+/g,'')"
        />
      </a-form-model-item>

      <a-form-model-item
        v-if="this.uploading === true"
        label="上传文件"
        extra="请上传PDF格式文件"
      >
        <span style="color: #000">
          {{ form.fileUploadName }}
        </span>
      </a-form-model-item>

      <a-form-model-item
        label="上传文件"
        ref="form.fileList"
        prop="fileList"
        extra="请上传PDF格式文件"
        v-if="this.uploading === false"
      >
        <a-upload
          name="file"
          prop="form.fileList"
          :multiple="false"
          :file-list="form.fileList"
          :accept="pdffileFormat"
          :action="uploadFileUrl"
          :headers="headers"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <a-button v-if="form.fileList.length === 0 && this.form.fileUploadName ===''">
            <a-icon type="upload" />上传文件
          </a-button>
        </a-upload>
      </a-form-model-item>

      <a-form-model-item label="标准类型：" ref="fileType" prop="fileType" v-model="form.fileType">
        <a-select
          prop="fileType"
          v-model="form.fileType"
          placeholder="请选择标准类型"
        >
          <a-select-option v-for="(item, index) in standardTypes" :key="index" :value="item" >
            {{ item }}
          </a-select-option>

        </a-select>
      </a-form-model-item>
      <a-form-model-item label="文件描述：">
        <a-input type="textarea" v-model="form.fileDesc" placeholder="请输入文件描述"/>
      </a-form-model-item>

      <a-form-model-item :wrapper-col="{ span: 12, offset: 6 }">
        <a-button class="submitBtn" type="primary" @click="onSubmit()">
          提交
        </a-button>
        <a-button class="closeBtn" type="default" @click="onClose">
          取消
        </a-button>
      </a-form-model-item>
    </a-form-model>

  </div>

</template>

<script type="text/ecmascript-6">
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { addFile, updateFile } from '@/api/standard/standardFile'

export default {
  data: () => ({
    formItemLayout: {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    },
    form: {
      fileName: '',
      fileType: '',
      fileDesc: '',
      fileList: [],
      fileUploadName: '', // 实际名称
      pdfRoute: '' // 路径
    },
    title: '',
    pdffileFormat: '.pdf',
    standardTypes: ['国家标准', '行业标准', '地方标准', '企业标准', '其他'],
    showState: true,
    uploadFileUrl: process.env.VUE_APP_BASE_API + '/common/upload',
    headers: {
      Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN)
    },
    rules: {
      fileName: [
        { required: true, message: '请输入文件名称', trigger: 'change' }
      ],
      fileList: [
        { required: true, message: '请上传文件', trigger: 'change' }
      ],
      fileType: [
        { required: true, message: '请选择标准类型', trigger: 'blur' }
      ]
    },

    uploading: false
  }),
  props: {
    selectedRows: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  mounted() {
    this.form = Object.assign(this.form, this.selectedRows)
    // console.log('this.form  : ', this.form)
    if (Object.keys(this.selectedRows).length !== 0) {
      this.title = '修改标准'
      this.uploading = true
      console.log(this.form)
    } else {
      this.title = '新增标准'
    }
  },
  created() {

  },
  methods: {
    // 文件移除
    handleRemove(file) {
      const index = this.form.fileList.indexOf(file)
      const newFileList = this.form.fileList.slice()
      newFileList.splice(index, 1)
      this.form.fileList = newFileList
    },

    // 上传PDF
    beforeUpload(file) {
      const filetypeDataList = ['pdf']
      const filetype = file.name.substring(file.name.lastIndexOf('.') + 1, file.name.length)

      // if (!filetypeDataList.includes(filetype)) {
      //   this.$message.error('请上传格式为pdf的文件!')
      // }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        console.log(file)
        this.$message.error('文件在10M以下!')
      } else {
        return filetypeDataList.includes(filetype) && isLt2M
      }
    },

    handleChange(info) {
      if (info.file.status === 'done' && (info.file.response && info.file.response.code === 200)) {
        this.$message.success(`${info.file.name} 上传成功`)

        this.form.fileUrl = info.file.response.fileName
        this.form.fileUploadName = info.file.name
      } else if (info.file.status === 'error' || (info.file.response && info.file.response.code === 500)) {
        // this.$message.error(`${info.file.name} 上传失败`)
        this.rules.fileList[0].message = `${info.file.name} 上传失败`
        this.form.fileUrl = ''
        this.form.fileUploadName = ''
        info.fileList = []
      }

      let fileList = [...info.fileList]
      fileList = fileList.slice(-1)
      fileList = fileList.map((file) => {
        if (file.response) {
          file.url = file.response.url
        }
        return file
      })

      this.form.fileList = fileList
      console.log('uploading this.fileList : ', this.fileList)
    },
    typeChange() {
      switch (this.form.fileType) {
        case '国家标准':
          this.form.fileType = '0'
        break
        case '行业标准':
          this.form.fileType = '1'
        break
        case '地方标准':
          this.form.fileType = '2'
        break
        case '企业标准':
          this.form.fileType = '3'
          break
        case '其他':
          this.form.fileType = '4'
        break
      }
      switch (this.form.status) {
          case '启用': // 0
            this.form.status = '0'
          break
          case '停用':// 1
            this.form.status = '1'
          break
      }
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
       console.log('valid', valid)
        if (valid) {
          if (!this.form.hasOwnProperty('id')) {
            this.typeChange()
            addFile(this.form).then(res => {
              if (res.code === 200) {
                this.showState = false
                this.$emit('getShowState', this.showState)
                // console.log('上传 this.form=========', this.form)
              }
            })
          }
          if (this.form.hasOwnProperty('id')) {
            this.typeChange()
            updateFile(this.form).then(res => {
            if (res.code === 200) {
              this.showState = false
              this.$emit('getShowState', this.showState)
              // console.log('修改文件: ', this.form)
            }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    onClose() {
      this.showState = false
      this.$emit('getShowState', this.showState)
    }

  }
}
</script>

<style lang="less">
#addWrap {
  width: 520px;
  height: 460px;
  background: #ffffff;
  border-radius: 12px;
  box-sizing: border-box;
  padding: 25px 30px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
  position: absolute;
  z-index: 10;
  top: 200px;
  left: calc(50% - 260px);

  .title{
    font-size: 22px;
    color: #000;
    margin-bottom: 30px;
  }
  .submitBtn, .closeBtn{
    margin: 0 20px;
  }
}
</style>
