<template>
  <div class="app-content" style="max-height:75vh;overflow:auto;">
    <a-spin :spinning="loading" style="width:100%;height:100%;">
      <a-form-model ref="from" :model="formData" :rules="rules" style="border-top: 0px" class="from-table font-line-space">
        <a-row>
          <a-col :span="24" style="border-top: 0px;">
            <div class="tb-title">
              <span>基础信息</span>
            </div>
          </a-col>
        </a-row>
        <a-row type="flex">
          <a-col :span="4" class="bg-gray">
            <div class="special-middle">
              <div>项目合同编号</div>
            </div>
          </a-col>
          <a-col :span="20">
            <a-form-model-item prop="projNo">
              {{formData.projNo}}
              <!-- <a-input placeholder="项目合同编号" v-model="formData.projNo" :maxLength="50" style="width: 80%" /> -->
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row type="flex">
          <a-col :span="4" class="bg-gray">
            <div class="special-middle">
              <div>项目名称</div>
            </div>
          </a-col>
          <a-col :span="20">
            <a-form-model-item prop="projName">
              {{formData.projName}}
              <!-- <a-input placeholder="项目名称" v-model="formData.projName" :maxLength="100" style="width: 80%" /> -->
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row type="flex">
          <a-col :span="4" class="bg-gray">
            <div class="special-middle">
              <div>项目负责人</div>
            </div>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="personName">
              {{formData.appPersonName}}
              <!-- <a-input placeholder="项目负责人" v-model="formData.personName" :maxLength="50" style="width: 80%" /> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="4" class="bg-gray">
            <div class="special-middle">
              <div>联系电话</div>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="special-middle">
              <a-form-model-item prop="telephone">
                {{formData.telephone}}
                <!-- <a-input placeholder="联系电话" v-model="formData.telephone" :maxLength="50" style="width: 80%" /> -->
              </a-form-model-item>
            </div>
          </a-col>
        </a-row>
        <a-row type="flex">
          <a-col :span="4" class="bg-gray">
            <div class="special-middle">
              <div>项目承担单位</div>
            </div>
          </a-col>
          <a-col :span="20">
            <a-form-model-item prop="unitName">
              {{formData.appUnitName}}
              <!-- <a-input placeholder="承担单位" v-model="formData.appUnitName" :maxLength="50" style="width: 80%" /> -->
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24" style="border-top: 0px;">
            <div class="tb-title">
              <span>论文发表情况（省级以上刊物）</span>
            </div>
          </a-col>
        </a-row>
        <a-row type="flex" class="row_center">
          <a-col :span="6" class="bg-gray">
            <div class="special-middle">
              <div class="required">论文名称</div>
            </div>
          </a-col>
          <a-col :span="3" class="bg-gray">
            <div class="special-middle">
              <div class="required">作者姓名</div>
            </div>
          </a-col>
          <a-col :span="3" class="bg-gray">
            <div class="special-middle">
              <div class="required">发表年月</div>
            </div>
          </a-col>
          <a-col :span="3" class="bg-gray">
            <div class="special-middle">
              <div class="required">发表在何种刊物</div>
            </div>
          </a-col>
          <a-col :span="3" class="bg-gray">
            <div class="special-middle">
              <div class="required">国内外反映应用情况</div>
            </div>
          </a-col>
          <a-col :span="5" class="bg-gray">
            <div class="special-middle">
              <div class="required">论文上传</div>
            </div>
          </a-col>
          <a-col :span="1" class="bg-gray">
            <div class="special-middle">
              <div>操作</div>
            </div>
          </a-col>
        </a-row>
        <a-row v-for="(thesis, index) in formData.thesisList" :key="'thesisList'+index" type="flex" class="row_center">
          <a-col :span="6">
            <a-form-model-item :prop="'thesisList.' + index + '.name'" :rules="{ required: true, message: '*', trigger: 'blur',}">
              <a-input v-model="thesis.name" :maxLength="50" placeholder="论文名称" style="width:85%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="3">
            <a-form-model-item :prop="'thesisList.' + index + '.author'" :rules="{ required: true, message: '*', trigger: 'blur',}">
              <a-input v-model="thesis.author" :maxLength="25" placeholder="作者姓名" style="width:85%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="3">
            <a-form-model-item :prop="'thesisList.' + index + '.publishDate'" :rules="{ required: true, message: '*', trigger: 'change',}">
              <a-month-picker format="YYYY-MM" valueFormat="YYYY-MM" v-model="thesis.publishDate" style="width:85%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="3">
            <a-form-model-item :prop="'thesisList.' + index + '.publication'" :rules="{ required: true, message: '*', trigger: 'blur',}">
              <a-input v-model="thesis.publication" :maxLength="100" placeholder="发表在何种刊物" style="width:85%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="3">
            <a-form-model-item :prop="'thesisList.' + index + '.application'" :rules="{ required: true, message: '*', trigger: 'blur',}">
              <a-input v-model="thesis.application" :maxLength="100" placeholder="国内外反映应用情况" style="width:85%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <div class="special-middle" style="text-align: left;">
              <div v-if="thesis.downloadUrl">
                <a-icon type="paper-clip" style="margin:0 6px" />
                <a class="hover-pointer" style="margin-right:8px " @click="downloadfile(thesis)">{{thesis.fileName}}</a>
                <a-popconfirm title="确定要删除吗？" ok-text="确定" cancel-text="取消" @confirm="deletefile(thesis, index)">
                  <a-icon type="close" class="hover-pointer d-icon" />
                </a-popconfirm>
              </div>
              <div v-else>
                <a-form-model-item :prop="'thesisList.' + index + '.downloadUrl'" :rules="{required: true, message: '请上传附件',trigger: 'blur',}">
                  <input type="file" :ref="'thesisfileElem' + index" class="visually-hidden" @change="handleFiles('thesisfileElem',thesis, index)" />
                  <a-button @click="fileSelect('thesisfileElem',thesis, index)"><a-icon type="upload" />选择文件</a-button>
                </a-form-model-item>
              </div>
            </div>
          </a-col>
          <a-col :span="1">
            <div class="special-middle">
              <a-popconfirm title="确定要删除吗？" ok-text="确定" cancel-text="取消" @confirm="deleteListItem(thesis,1)">
                <a-button type="link" size="small">删除</a-button>
              </a-popconfirm>
            </div>
          </a-col>
        </a-row>
        <a-row type="flex">
          <a-col :span="24" style="text-align: center">
            <div class="special-middle">
              <a-button type="dashed" style="width: 20%" @click="addListItem(1)">
                <a-icon type="plus" /> 添加 <span style="color:red;margin-left:10px"></span>
              </a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </div>
</template>

<script>
const Thesis = { name: null, author: null, publishDate: null, publication: null, application: null, downloadId: null, fileName: null, downloadUrl: null }

import { isEmptyParams } from "@/views/utils/common"
import axios from 'axios'

export default {
  name: "thesisEdit",
  components: {

  },
  props: {
    value: {
      type: String,
      default: () => {
        return null;
      },
    },
  },
  data () {
    return {
      formData: {
        projNo: null,
        projName: null,
        appPersonName: null,
        appUnitName: null,
        telephone: null,
        thesisList: [],
      },
      rules: {},
      loading: true,
    };
  },
  created () {
    this.getConclusionByProjId()
  },
  computed: {},
  methods: {
    getConclusionByProjId () {
      let pars = { id: this.value }
      if (!!this.value) {
        this.$api.conclusion.getConclusionByProjId(pars).then(({ data = {} }) => {
          if (data) {
            this.formData = data
            this.loading = false
          } else {
            this.$emit('close', 'error')
          }
        }).catch(() => {
          this.$message.error('500 Internal Server Error！');
          this.$emit('close', 'error')
        })
      }
    },
    addListItem (type) {
      switch (type) {
        case 1:
          this.formData.thesisList.push({ ...Thesis })
          break
      }
    },
    deleteListItem (obj, type) {
      switch (type) {
        case 1:
          if (this.formData.thesisList.length == 1) {
            this.$message.error('至少填写一篇论文信息！')
          }
          else {
            let i = this.formData.thesisList.indexOf(obj)
            if (i !== -1) {
              this.formData.thesisList.splice(i, 1)
            }
          }
          break
      }
    },
    fileSelect (Fname, item, index) {
      let fileElem = this.$refs[Fname + index][0]
      if (fileElem) {
        fileElem.click()
      }
    },
    handleFiles (Fname, item, index) {
      let fileElem = this.$refs[Fname + index][0]
      let files = fileElem.files
      if (files.length <= 0) {
        this.$message.error('未选中文件，请尝试重新选择')
        return
      }
      //判断是否小于1M
      let isLtSize = files[0].size < 1024 * 1024 * 20;
      if (!isLtSize) {
        this.$message.error('所选文件超过20M，已自动过滤，请检查~');
        return
      }
      var fileNames = files[0].name.split('.')
      var fileType = fileNames[fileNames.length - 1].toLocaleLowerCase()
      var extList = ['doc', 'docx', 'pdf']
      if (!extList.find((item) => item == fileType)) {
        this.$message.error('文件格式错误！')
        return
      }
      this.$api.base.asyncUpload(this.uploadHandle(files[0], files[0].name)).then(({ data = {} }) => {

        item.downloadId = data.id
        item.fileName = files[0].name
        item.downloadUrl = data.downloadUrl

      }).catch(() => {
        this.$message.error('上传失败')
      })
    },
    uploadHandle (file, fileName) {
      let formData = new FormData()
      formData.append('file', file)
      formData.append('fileName', fileName)
      return formData
    },
    downloadfile (item) {
      axios({
        url: item.downloadUrl,
        method: 'GET',
        responseType: 'blob' // 告诉axios返回的数据类型为Blob
      }).then(response => {
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', item.fileName)  // 下载文件的名称
        document.body.appendChild(link)
        link.click()
      })
    },
    deletefile (item, index) {
      this.$api.base.deletefile({ id: item.downloadId }).then(({ data = {} }) => {
        if (data) {
          item.fileName = ''
          item.downloadUrl = ''
          item.downloadId = ''
        }
      }).catch(() => {
        this.$message.error('删除失败')
      })
    },
    submit () {
      this.$refs.from.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.formData.state != 30)
            this.formData.state = 10
          let pars = isEmptyParams(this.formData)
          let par = { ...pars }
          this.$api.conclusion.saveThesis(par).then(({ data = {} }) => {
            if (data) {
              this.formData.id = data
              this.$emit('close', 'edit')
            }
          }).catch(() => { this.loading = false })
        } else {
          this.$message.error('信息未填写完全，请检查！')
          return false
        }
      })
    },
  },
};
</script>
<style scoped lang="less">
.file-description {
  display: block;
  width: 100%;
  line-height: 22px;
  padding: 3px 3px 3px 3px;
  color: red;
  white-space: normal;
  word-wrap: break-word;
  //   text-indent: 1em;
}
.inner_from {
  .ant-row-flex:last-child .ant-col {
    border-bottom: 0;
  }
  .ant-row-flex .ant-col:first-child {
    border-left: 0;
  }
  .ant-row-flex {
    border-right: 0;
  }
}
.special-middle {
  .font_s {
    margin: 0 6px;
  }
}
</style>
