<template>
  <div class="create-container">
    <div class="title h1">创建报告</div>
    <div class="create-body">
      <el-form :model="report" :rules="rules" ref="report" label-width="12%" class="demo-report">
        <el-form-item label="报告名称" prop="name">
          <el-input v-model="report.name"></el-input>
        </el-form-item>
        <el-form-item label="报告类型" prop="type">
          <el-radio-group 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>
        </el-form-item>
        <el-form-item label="测试对象" prop="name">
          <el-input style="width: 400px" type="textarea" v-model="report.target"></el-input>
        </el-form-item>
        <el-form-item label="测试内容" prop="name">
          <el-input style="width: 400px" type="textarea" v-model="report.content"></el-input>
        </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 type="textarea" v-model="report.target"></el-input>-->
        <!--</el-col>-->
        <!--</el-row>-->
        <!--<el-row :gutter="2">-->
        <!--<el-col :span="2">-->
        <!--<span>测试内容</span>-->
        <!--</el-col>-->
        <!--<el-col :span="10">-->
        <!--<el-input type="textarea" v-model="report.content"></el-input>-->
        <!--</el-col>-->
        <!--</el-row>-->
        <!--</div>-->
        <!--</el-form-item>-->
        <el-form-item prop="file" label="报告文件">
          <el-upload
            drag
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :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>
        </el-form-item>

        <el-form-item label="结论" prop="conclusion">
          <el-input style="width: 400px" type="textarea" v-model="report.conclusion"></el-input>
        </el-form-item>
        <el-form-item>
          <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: 'ReportCreate',
  components: {},
  data () {
    return {
      user: {},
      reportType: [],
      scope: 0,
      projectId: '',
      taskId: '',
      dependencyCode: '',
      report: {
        name: '',
        target: '',
        content: '',
        file: [],
        fileUrl: '',
        type: '',
        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'}
        // ],
        // file: [
        //   {required: true, message: '请上传报告文件', trigger: 'change'}
        // ],
        // conclusion: [
        //   {required: true, message: '请输入报告结论', trigger: 'blur'}
        // ]
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    init () {
      this.scope = this.$route.params.scope
      this.dependencyCode = this.$route.params.dependencyCode
      this.projectId = this.$route.params.projectId
      this.taskId = this.$route.params.taskId
      this.setUserInfo()
      this.setReportType()
    },
    submitForm (formName) {
      const newReport = {
        name: this.report.name,
        scope: this.scope,
        type: this.report.type,
        dependencyCode: this.dependencyCode,
        target: this.report.target,
        content: this.report.content,
        file: this.report.fileUrl,
        conclusion: this.report.conclusion
      }
      console.log(newReport)
      if (this.taskId == null) {
        Http.post(Apis.REPORT.CREATE_PROJECT_REPORT.replace('{projectId}', this.projectId), newReport).then((res) => {
          this.createReportSuccess(res.crowdReportVO.code)
        })
      } else {
        Http.post(Apis.REPORT.CREATE_TASK_REPORT.replace('{projectId}', this.projectId).replace('{taskId}', this.taskId), newReport).then((res) => {
          this.createReportSuccess(res.crowdReportVO.code)
        })
      }

      // this.$refs[formName].validate(valid => {
      //   if (valid) {
      //
      //     //提交 report
      //   } else {
      //     console.log('error submit!!')
      //     return false
      //   }
      // })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.report.name = ''
      this.report.abstract.target = ''
      this.report.abstract.content = ''
      this.report.file = []
      this.report.type = ''
      this.report.conclusion = ''
    },
    cancelCreate () {
      if (window.history.length <= 1) {
        this.$router.push({path: '/'})
        return false
      } else {
        this.$router.go(-1)
      }
    },
    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
    },
    loadData () {
    },
    uploadReportFile (param) {
      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)
      })
    },
    setReportType () {
      this.reportType = getAllReportTypes().then((res) => {
        this.reportType = res
      }).catch((error) => {
        notify('error', '获取报告类型列表失败')
      })
    },
    setUserInfo () {
      this.user = storageGet('user')
    },
    createReportSuccess (reportId) {
      this.$alert('报告创建成功', '创建成功', {
        confirmButtonText: '确定',
        callback: action => {
          this.$router.push({
            name: 'Report',
            params: {reportId: reportId, projectId: this.projectId, taskId: this.taskId}
          })
        }
      })
    },
  },
  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;
  }

  .el-input {
    width: 400px;
  }
</style>
