<template>
  <div class="create-container">
    <div class="create-body" v-loading="loading">
      <el-form :model="report" :rules="rules" ref="report" label-width="12%" class="demo-report">
        <el-form-item label="报告名称" prop="name">
          <el-input v-if="isModifyMode" v-model="report.name"></el-input>
          <span v-if="!isModifyMode">{{report.name}}</span>
        </el-form-item>
        <el-form-item label="报告类型" prop="type">
          <el-radio-group v-if="isModifyMode" v-model="report.type">
            <span v-for="(item,index) in reportType" :key="index">
              <el-radio :label="item" name="type">{{item}}</el-radio>
            </span>
          </el-radio-group>
          <span v-if="!isModifyMode" class="badge">{{report.type}}</span>
        </el-form-item>
        <el-form-item label="摘要" prop="abstract">
          <div>
            <el-row :gutter="2">
              <el-col :span="2">
                <span>测试对象</span>
              </el-col>
              <el-col :span="10">
                <el-input v-if="isModifyMode" type="textarea" v-model="report.target"></el-input>
                <span v-if="!isModifyMode">{{report.target}}</span>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="2">
                <span>测试内容</span>
              </el-col>
              <el-col :span="10">
                <el-input v-if="isModifyMode" type="textarea" v-model="report.content"></el-input>
                <span v-if="!isModifyMode">{{report.content}}</span>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item prop="file" label="报告文件">
          <el-upload
            v-if="isModifyMode"
            drag
            class="upload-demo"
            action=""
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            :before-upload="beforeFileUpload"
            :file-list="report.file"
            :http-request="uploadReportFile"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">请上传报告文件</div>
          </el-upload>
          <div v-if="!isModifyMode">
            <span v-if="report.fileUrl==null">暂无文件</span>
            <a :href="report.fileUrl" v-if="report.fileUrl!=null">
              <el-link :underline="false" type="primary"><i class="el-icon-document"></i>下载文档</el-link>
            </a>
          </div>
        </el-form-item>

        <el-form-item label="结论" prop="conclusion">
          <el-input v-if="isModifyMode" type="textarea" v-model="report.conclusion"></el-input>
          <span v-if="!isModifyMode">{{report.conclusion}}</span>
        </el-form-item>
        <el-form-item v-if="!isModifyMode">
          <div class="btn btn-medium btn-info" @click="modifyForm()">修改</div>
          <div class="btn btn-medium" @click="back()">返回</div>
        </el-form-item>
        <el-form-item v-if="isModifyMode">
          <div class="btn btn-primary btn-info" @click="submitForm('report')">确认修改</div>
          <div class="btn btn-primary" @click="resetForm('report')">重置</div>
          <div class="btn btn-primary" @click="cancelCreate('report')">取消</div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Http from '@/js/http.js'
import Apis from '@/js/api.js'
import {notify} from '@/constants/index'
import {getAllReportTypes, storageGet} from '@/js/index'

export default {
  name: 'TaskReport',
  components: {},
  data () {
    return {
      user: {},
      loading: false,
      reportId: 0,
      projectId: '',
      taskId: '',
      isModifyMode: false,
      reportType: [],
      report: {
        name: '',
        type: '',
        description: '',
        target: '',
        content: '',
        file: [],
        fileUrl: '',
        conclusion: ''
      },
      rules: {
        // name: [
        //   {required: true, message: '请输入报告名称', trigger: 'blur'}
        //   // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        // ],
        // abstract: [
        //   {
        //     required: true,
        //     message: '请输入摘要信息',
        //     trigger: 'change'
        //   }
        // ],
        // type: [
        //   {required: true, message: '请选择报告类型', trigger: 'change'}
        // ],
        // conclusion: [
        //   {required: true, message: '请输入报告结论', trigger: 'blur'}
        // ]
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    init () {
      this.reportId = this.$route.params.reportId
      this.projectId = this.$route.params.projectId
      this.taskId = this.$route.params.taskId
      this.setReportType()
      this.setUserInfo()
      this.loadData()
    },
    modifyForm () {
      this.isModifyMode = true
    },
    submitForm (formName) {
      this.showLoading()
      const newReport = {
        name: this.report.name,
        scope: this.taskId == null ? 0 : 1,
        type: this.report.type,
        dependencyCode: this.taskId == null ? this.projectId : this.taskId,
        target: this.report.target,
        content: this.report.content,
        file: '123.pdf',
        conclusion: this.report.conclusion
      }
      console.log(newReport)
      Http.put(Apis.REPORT.UPDATE_TASK_REPORT.replace('{projectId}', this.projectId).replace('{taskId}', this.taskId).replace('{reportId}', this.reportId), newReport).then((res) => {
        console.log(res)
        this.hideLoading()
        this.isModifyMode = false
      }).catch((error) => {
        this.hideLoading()
        notify('error', error.data)
      })
      // this.$refs[formName].validate(valid => {
      //   if (valid) {
      //     this.isModifyMode = false
      //
      //     //提交 report
      //   } else {
      //     console.log('error submit!!')
      //     return false
      //   }
      // })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.report.name = ''
      this.report.target = ''
      this.report.content = ''
      this.report.file = ''
      this.report.type = ''
      this.report.conclusion = ''
    },
    cancelCreate () {
      this.isModifyMode = false
      //请求 report
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handleExceed (files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
          } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    beforeRemove (file, fileList) {
      //return this.$confirm(`确定移除 ${file.name}？`)
    },
    beforeFileUpload (file) {
      console.log(file)
      const isPDF = file.type === 'application/pdf'
      const isDOC = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      const isEXCEL = file.type === 'application/vnd.ms-excel'
      const isXLS = file.type === 'application/x-xls'
      const isTXT = file.type === 'text/plain'
      const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      //console.log(file)
      if (!(isDOC || isEXCEL || isPDF || isTXT || isXLS || isXLSX)) {
        this.$message.error('上传文件只能是 PDF 、 DOC 、DOCX 、XLS、TXT、XLSX 格式!')
      }
      return isDOC || isEXCEL || isPDF || isTXT || isXLS || isXLSX
    },
    back () {
      if (window.history.length <= 1) {
        this.$router.push({path: '/'})
        return false
      } else {
        this.$router.go(-1)
      }
    },
    loadData () {
      //pro1564487183259
      //pro1564487183259_task1564487274060
      //pro1564487183259pro1564487183259_task1564487274060_rep1564488510500
      this.showLoading()
      Http.get(Apis.REPORT.GET_TASK_REPORT.replace('{projectId}', this.projectId).replace('{taskId}', this.taskId).replace('{reportId}', this.reportId)).then((res) => {
        console.log(res)
        this.report.name = res.crowdReportVO.name
        this.report.crowdTestTaskId = res.crowdReportVO.crowdTestTaskId
        this.report.scope = res.crowdReportVO.scope
        this.report.type = res.crowdReportVO.type
        this.report.description = res.crowdReportVO.description
        this.report.content = res.crowdReportVO.content
        this.report.fileUrl = res.crowdReportVO.file
        this.report.conclusion = res.crowdReportVO.conclusion
        this.report.target = res.crowdReportVO.target
        this.hideLoading()
      }).catch((error) => {
        this.hideLoading()
        notify('error', '打开报告失败:' + error.data)
      })
    },
    uploadReportFile (param) {
      this.showLoading()
      const formData = new FormData()
      let config = {
        //添加请求头
        headers: {'Content-Type': 'multipart/form-data'},
      }
      formData.append('file', param.file)
      Http.upload(Apis.FILE.UPLOAD_REPORT_FILE.replace('{userId}', this.user.userVO.id), formData, config).then((res) => {
        console.log('上传成功')
        this.report.fileUrl = res.data
        console.log(res)
        this.hideLoading()
      }).catch((error) => {
        this.hideLoading()
        notify('error', '文件上传失败:' + error.data)
      })
    },
    setReportType () {
      getAllReportTypes().then((res) => {
        this.reportType = res
      }).catch((error) => {
        notify('error', '加载报告类型失败')
      })
    },
    setUserInfo () {
      this.user = storageGet('user')
    },
    updateReportSuccess () {

    },
    showLoading () {
      this.loading = true
    },
    hideLoading () {
      this.loading = false
    }
  },
  watch: {
    reportType (val) {
      this.reportType = val
    }
  }
}
</script>

<style lang="less" scoped>
  .el-radio {
    margin: 10px 20px 10px 0;
  }

  .el-form-item /deep/ .el-tabs__content {
    max-height: 120px !important;
    overflow: auto;
  }

  .el-row {
    margin-bottom: 10px;
  }
</style>
