<template>
  <div class="create-container">
    <div class="create-body" v-loading="loading">
      <div class="title">创建项目</div>
      <el-tabs tabPosition="top" type="card">
        <el-tab-pane label="单个创建项目">
          <el-form :model="project" :rules="rules" ref="project" label-width="12%" class="demo-report">
            <el-form-item label="项目名称" prop="name">
              <el-input v-if="isModifyMode" v-model="project.name"></el-input>
              <!--<span v-if="!isModifyMode">{{project.name}}</span>-->
            </el-form-item>
            <el-form-item label="项目描述" prop="name">
              <el-input v-if="isModifyMode" v-model="project.description"></el-input>
              <!--<span v-if="!isModifyMode">{{project.description}}</span>-->
            </el-form-item>
            <el-form-item label="联系人姓名" prop="name">
              <el-input v-if="isModifyMode" v-model="project.contactName"></el-input>
              <!--<span v-if="!isModifyMode">{{project.contactName}}</span>-->
            </el-form-item>
            <el-form-item label="联系人电话" prop="name">
              <el-input v-if="isModifyMode" v-model="project.contactPhone"></el-input>
              <!--<span v-if="!isModifyMode">{{project.contactPhone}}</span>-->
            </el-form-item>
            <el-form-item label="项目定价" prop="name">
              <el-input v-if="isModifyMode" v-model="project.price"></el-input>
              <!--<span v-if="!isModifyMode">{{project.price}}</span>-->
            </el-form-item>
            <el-form-item label="平台" prop="platform">
              <el-checkbox-group v-if="isModifyMode" v-model="project.platform">
                <span v-for="(item,index) in platforms" :key="index">
              <el-checkbox :label="item">{{ item }}&nbsp;&nbsp;&nbsp;&nbsp;</el-checkbox>
            </span>
              </el-checkbox-group>
              <!--<span-->
              <!--v-if="!isModifyMode"-->
              <!--class="badge"-->
              <!--v-for="item in project.platform"-->
              <!--&gt;{{platformType[item]}}</span>-->
            </el-form-item>
            <el-form-item label="服务类型" prop="type">
              <el-checkbox-group v-if="isModifyMode" v-model="project.type">
            <span v-for="(item,index) in serviceType" :key="index">
              <el-checkbox :label="item" name="type">{{item}}&nbsp;&nbsp;&nbsp;&nbsp;</el-checkbox>
            </span>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item prop="file" label="项目需求文档">
              <el-upload
                v-if="isModifyMode"
                drag
                style="width: 400px"
                class="upload-demo"
                action=""
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :before-upload="beforeFileUpload"
                :http-request="uploadRequireDoc"
                :file-list="project.requireDoc"
              >
                <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="project.file==null || project.file.length === 0">暂无文件</span>-->
              <!--<a :href="project.file[0]" v-if="project.file!=null && project.file.length > 0"><i-->
              <!--class="fa fa-file-text-o"></i>-->
              <!--{{project.file[0]}}</a>-->
              <!--</div>-->
            </el-form-item>
            <el-form-item prop="file" label="项目待测文件">
              <el-upload
                style="width: 400px"
                v-if="isModifyMode"
                drag
                class="upload-demo"
                action=""
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :http-request="uploadApkFile"
                :before-upload="beforeFileUpload"
                :file-list="project.file"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
              </el-upload>
              <!--<div v-if="!isModifyMode">-->
              <!--<span v-if="project.file==null || project.file.length === 0">暂无文件</span>-->
              <!--<a :href="project.file[0]" v-if="project.file!=null && project.file.length > 0"><i-->
              <!--class="fa fa-file-text-o"></i>-->
              <!--{{project.file[0]}}</a>-->
              <!--</div>-->
            </el-form-item>
            <el-form-item label="项目截止时间" prop="datetime">
              <div class="block" v-if="isModifyMode">
                <el-date-picker
                  v-model="project.datetime"
                  type="datetime"
                  placeholder="选择截止时间"
                  align="right"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </div>
              <span v-if="!isModifyMode">{{new Date(project.datetime)}}</span>
            </el-form-item>
            <!--<el-form-item v-if="!isModifyMode">-->
            <!--<div class="btn btn-medium btn-info" @click="modifyInfo()">修改</div>-->
            <!--<div class="btn btn-medium" @click="cancelModify()">返回</div>-->
            <!--</el-form-item>-->
            <el-form-item v-if="isModifyMode">
              <div class="btn btn-primary btn-info" @click="submitInfo()">确认提交</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="批量创建项目">
          <el-form :model="project" :rules="rules" ref="project" label-width="12%" class="demo-report">
            <el-form-item prop="file" label="Excel模板文件">
              <a :href="downloadFile">
                <el-link :underline="false" type="primary"><i
                  class="el-icon-document"></i>下载文档
                </el-link>
              </a>
            </el-form-item>
            <el-form-item type="file" prop="file" label="Excel文件">
              <el-upload
                v-if="isModifyMode"
                drag
                class="upload-demo"
                action=""
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :limit="1"
                :on-exceed="handleExceed"
                :before-upload="beforeFileUpload"
                :http-request="uploadProjectCreateExcelFile"
                :file-list="project.excelFile"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
                </div>
              </el-upload>
              <!--<div v-if="!isModifyMode">-->
              <!--<span v-if="project.file==null">暂无文件</span>-->
              <!--<a :href="project.file" v-if="project.file!=null"><i class="fa fa-file-text-o"></i>-->
              <!--{{project.file}}</a>-->
              <!--</div>-->
            </el-form-item>
            <el-form-item v-if="isModifyMode">
              <div class="btn btn-primary btn-info" @click="ensureSubmitExcel()">确认提交</div>
            </el-form-item>
          </el-form>
          <el-dialog
            title="您添加的项目"
            :visible.sync="dialogVisible"
            width="80%"
            :before-close="handleDialogClose"
            center>
        <span>
          <el-table
            :data="projectList"
            style="width: auto">
            <el-table-column prop="name" label="项目名称">
              <template slot-scope="scope">
                <span>{{scope.row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="platform" label="领域类型">
              <template slot-scope="scope">
                <span>{{scope.row.fieldType}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="应用类型">
              <template slot-scope="scope">
                <span>{{scope.row.applicationType}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="platform" label="测试类型">
              <template slot-scope="scope">
                <span>{{scope.row.type}}</span>
              </template>
            </el-table-column>
             <el-table-column prop="platform" label="委托单位">
              <template slot-scope="scope">
                <span>{{scope.row.entrustUnit}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="linkMan" label="项目联系人">
              <template slot-scope="scope">
                <span>{{scope.row.linkMan}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="linkManMobile" label="联系方式">
              <template slot-scope="scope">
                <span>{{scope.row.linkManMobile}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="项目需求描述">
              <template slot-scope="scope">
                <span>{{scope.row.description}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="计价标准">
              <template slot-scope="scope">
                <span>{{scope.row.valuationStandard}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="测试报告内容">
              <template slot-scope="scope">
                <span>{{scope.row.crowdTestReportForProject.content}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="测试报告结论">
              <template slot-scope="scope">
                <span>{{scope.row.crowdTestReportForProject.conclusion}}</span>
              </template>
            </el-table-column>
    </el-table>
        </span>
            <span slot="footer" class="dialog-footer">
    <el-button @click="handleDialogClose">取消</el-button>
    <el-button type="primary" @click="hindDialog">确认</el-button>
  </span>
          </el-dialog>
        </el-tab-pane>

      </el-tabs>

    </div>
  </div>
</template>

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

    export default {
        name: 'ProjectAdd',
        data() {
            return {
                userId: 0,
                user: {},
                loading: false,
                dialogVisible: false,
                isModifyMode: true,
                serviceType: [],
                platforms: [],
                isFormSubmit: true,
                downloadFile: '',
                project: {
                    name: '',
                    description: '',
                    contactName: '',
                    contactPhone: '',
                    platform: [],
                    type: [],
                    requireDoc: [],
                    requireDocUrl: '',
                    file: [],
                    fileUrl: '',
                    excelFile: [],
                    excelFileUrl: '',
                    price: '',
                    datetime: ''
                },
                projectList: [{
                    "id": null,
                    "name": "广东省农产品商贸交易服务平台",
                    "code": "PROJ-2020070820055",
                    "userId": 20473,
                    "regionalManagerId": 99222,
                    "projectDistributionTypeId": 1,
                    "fieldType": "KJFW",
                    "applicationType": "WEB",
                    "type": "GNCS",
                    "linkMan": "张三",
                    "linkManMobile": "13512345678",
                    "description": "本平台提供农产品网上供求信息的发布、在线交易服务等功能，帮助用户快速捕获商机，具备开设网上交易会和网上农博会，为用户提供更广阔的宣传平台。",
                    "projectFile": "",
                    "requirementFile": "",
                    "distributionProvince": "江苏",
                    "distributionCity": "南京",
                    "valuationStandard": "1200元/(人天）",
                    "quotedPrice": 30000.0,
                    "fixedPrice": 30000.0,
                    "restPrice": null,
                    "entrustUnit": "广东省农村信息中心",
                    "status": 4,
                    "deadTime": "2020-07-08T12:16:34.695+0000",
                    "endTime": "2020-07-08T12:16:34.695+0000",
                    "isDeleted": 0,
                    "joinCount": 1,
                    "createTime": null,
                    "crowdTestTaskList": [{
                        "id": null,
                        "name": "广东省农产品商贸交易服务平台-GNCS",
                        "code": "TASK-GNCS-2020070820008",
                        "crowdTestProjectCode": "PROJ-2020070820055",
                        "evaluationAgencyId": 1,
                        "type": "GNCS",
                        "description": "本平台提供农产品网上供求信息的发布、在线交易服务等功能，帮助用户快速捕获商机，具备开设网上交易会和网上农博会，为用户提供更广阔的宣传平台。",
                        "requirementFile": "",
                        "distributionType": 0,
                        "distributionProvince": null,
                        "distributionCity": null,
                        "quotedPrice": 30000.0,
                        "fixedPrice": 30000.0,
                        "status": 4,
                        "fullStatus": 0,
                        "deadTime": "2020-07-08T12:16:34.695+0000",
                        "endTime": "2020-07-08T12:16:34.695+0000",
                        "isDeleted": 0,
                        "createTime": null,
                        "participantCount": 1,
                        "acceptedCount": 1,
                        "participantHasCommittedCount": 1,
                        "acceptedUserList": [{
                            "id": null,
                            "taskCode": "TASK-GNCS-2020070820008",
                            "userId": 20473,
                            "quotedPrice": 0.0,
                            "hasReport": 1,
                            "distributionType": 1,
                            "isAccepted": 1,
                            "acceptTime": null,
                            "isCommitted": 1,
                            "user": null,
                            "commitTaskTime": "2020-07-08T12:16:34.695+0000",
                            "commitReportTime": "2020-07-08T12:16:34.695+0000",
                            "crowdTestReportList": [{
                                "id": null,
                                "name": "广东省农产品商贸交易服务平台-GNCS测试报告",
                                "code": "REPORT-2020070820089",
                                "userId": 20473,
                                "dependencyCode": "TASK-GNCS-2020070820008",
                                "type": "测试报告",
                                "scope": 1,
                                "testObject": null,
                                "description": null,
                                "content": "对平台的供求信息发布、在线交易、网上上交易会等模块进行了功能性测试，所有测试项均符合项目需求规格说明书的要求",
                                "file": null,
                                "conclusion": "通过",
                                "isDeleted": 0,
                                "createTime": null
                            }]
                        }]
                    }],
                    "crowdTestReportForProject": {
                        "id": null,
                        "name": "广东省农产品商贸交易服务平台测试报告",
                        "code": "REPORT-2020070820090",
                        "userId": null,
                        "dependencyCode": "PROJ-2020070820055",
                        "type": "GNCS",
                        "scope": 0,
                        "testObject": "广东省农产品商贸交易服务平台",
                        "description": "本平台提供农产品网上供求信息的发布、在线交易服务等功能，帮助用户快速捕获商机，具备开设网上交易会和网上农博会，为用户提供更广阔的宣传平台。",
                        "content": "对平台的供求信息发布、在线交易、网上上交易会等模块进行了功能性测试，所有测试项均符合项目需求规格说明书的要求",
                        "file": null,
                        "conclusion": "通过",
                        "isDeleted": 0,
                        "createTime": null
                    }
                }],
                excelFile: {},
                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'}
                    // ]
                },
                pickerOptions: {
                    shortcuts: [
                        {
                            text: '今天',
                            onClick(picker) {
                                picker.$emit('pick', new Date())
                            }
                        },
                        {
                            text: '昨天',
                            onClick(picker) {
                                const date = new Date()
                                date.setTime(date.getTime() - 3600 * 1000 * 24)
                                picker.$emit('pick', date)
                            }
                        },
                        {
                            text: '一周前',
                            onClick(picker) {
                                const date = new Date()
                                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
                                picker.$emit('pick', date)
                            }
                        }
                    ]
                },
                tableData: [{
                    date: '2016-05-02',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1518 弄'
                }, {
                    date: '2016-05-04',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1517 弄'
                }, {
                    date: '2016-05-01',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1519 弄'
                }, {
                    date: '2016-05-03',
                    name: '王小虎',
                    address: '上海市普陀区金沙江路 1516 弄'
                }]
            }
        },
        mounted() {
            this.$nextTick(() => {
                this.init()
            })
        },
        methods: {
            init() {
                this.setServiceType()
                this.setPlatformType()
                this.setUserInfo()
                this.setTemplateExcel()
            },
            //加载数据
            loadData: function () {
            },
            modifyInfo() {
                this.isModifyMode = true
            },
            submitInfo() {
                //this.isModifyMode = false
                this.showLoading()
                const newProject = {
                    userId: this.user.userVO.id,
                    name: this.project.name,
                    description: this.project.description,
                    contactName: this.project.contactName,
                    contactPhone: this.project.contactPhone,
                    platform: this.project.platform,
                    type: this.project.type,
                    doc: this.project.requireDocUrl,
                    file: this.project.fileUrl,
                    price: this.project.price,
                    datetime: this.project.datetime
                }
                Http.post(Apis.PROJECT.ADD_PROJECT, newProject).then((res) => {
                    this.hideLoading()
                    this.createProjectByFormSuccessConfirm()
                    console.log(res)
                }).catch(error => {
                    this.hideLoading()
                    notify('error', error.data)
                })
            },
            // cancelModify () {
            //   this.isModifyMode = false
            // },
            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() {

            },
            uploadProjectCreateExcelFile(param) {
                this.showLoading()
                const formData = new FormData()
                let config = {
                    //添加请求头
                    headers: {'Content-Type': 'multipart/form-data'},
                }
                formData.append('file', param.file)
                Http.upload(Apis.PROJECT.ADD_PROJECT_BY_EXCEL_PRE.replace('{userId}', this.user.userVO.id), formData, config).then((res) => {
                    console.log(res)
                    this.projectList = res.data
                    this.hideLoading()
                    this.showDialog()
                    //notify('success', '项目添加成功')
                }).catch(error => {
                    console.log("打印错误信息！！！");
                    console.log(error);
                    console.log(error.data);
                    notify('error', error)
                    this.hideLoading()
                })
            },
            uploadRequireDoc(param) {
                const formData = new FormData()
                let config = {
                    //添加请求头
                    headers: {'Content-Type': 'multipart/form-data'},
                }
                formData.append('file', param.file)
                Http.upload(Apis.FILE.REQUIREMENT_FILE.replace('{userId}', this.user.userVO.id), formData, config).then((res) => {
                    console.log('上传成功')
                    this.project.requireDocUrl = res.data
                    console.log(res.data)
                    notify('success', '上传成功')
                }).catch(error => {
                    notify('error', error.data)
                })
            },
            uploadApkFile(param) {
                const formData = new FormData()
                let config = {
                    //添加请求头
                    headers: {'Content-Type': 'multipart/form-data'},
                }
                formData.append('file', param.file)
                Http.upload(Apis.FILE.APK.replace('{userId}', this.user.userVO.id), formData, config).then((res) => {
                    console.log('上传成功')
                    this.project.fileUrl = res.data
                    console.log(res)
                    notify('success', '上传成功')
                }).catch(error => {
                    notify('error', error.data)
                })
            },
            handleDialogClose(done) {
                this.hideDialog()
                this.project.excelFile = []
                // this.$confirm('确认退出？退出前请记录下登录账号和密码，否则无法找回！！！')
                //   .then(_ => {
                //     //done()
                //     this.hideDialog()
                //   })
                //   .catch(_ => {
                //   })
            },
            hindDialog(){
                this.hideDialog()
            },
            ensureSubmitExcel() {
                this.hideDialog()
                this.showLoading()
                this.project.excelFile = []
                Http.post(Apis.PROJECT.ADD_PROJECT_BY_EXCEL, this.projectList).then((res) => {
                    notify('success', '添加成功')
                    this.hideLoading()
                }).catch((error) => {
                    notify('error', error.data)
                    this.hideLoading()
                })
            },
            showDialog() {
                this.dialogVisible = true
            },
            hideDialog() {
                this.dialogVisible = false
                //this.resetForm()
            },
            setServiceType() {
                getAllServiceTypes().then((res) => {
                    this.serviceType = res
                }).catch((error) => {
                    notify('error', '获取服务类型出错')
                })
            },
            setPlatformType() {
                this.platforms = getAllPlatformTypes()
            },
            createProjectByFormSuccessConfirm() {
                this.$confirm('项目创建成功，是否跳转至主页?', '提示', {
                    confirmButtonText: '跳转至主页',
                    cancelButtonText: '继续创建项目',
                    type: 'success'
                }).then(() => {
                    this.$router.push({
                        name: 'Home',
                        // params: {projectId: projectId, taskId: taskId}
                    })
                    // this.$message({
                    //   type: 'success',
                    //   message: '删除成功!'
                    // });
                }).catch(() => {
                    this.resetForm()
                    // this.$message({
                    //   type: 'info',
                    //   message: '已取消删除'
                    // });
                })
            },
            resetForm() {
                this.project = {
                    name: '',
                    description: '',
                    contactName: '',
                    contactPhone: '',
                    platform: [],
                    type: [],
                    requireDoc: [],
                    requireDocUrl: '',
                    file: [],
                    fileUrl: '',
                    excelFile: [],
                    excelFileUrl: '',
                    price: '',
                    datetime: ''
                }
            },
            setUserInfo() {
                this.user = storageGet('user')
            },
            setTemplateExcel() {
                this.showLoading()
                getGreenChannelAddProjectExcelTemplateFile(this.setTemplateExcelSuccess, this.setTemplateExcelFail)
            },
            setTemplateExcelSuccess(res) {
                this.hideLoading()
                this.downloadFile = res.fileUrl
            },
            setTemplateExcelFail(error) {
                this.hideLoading()
                notify('error', '加载模板文件失败：' + error.data)
            },
            showLoading() {
                this.loading = true
            },
            hideLoading() {
                this.loading = false
            }
        },
        watch: {
            serviceType(val) {
                this.serviceType = val
            }
        },
        created: function () {
        }
    }
</script>

<style 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>
