<template>
  <div class="create-container" v-loading="loading">
    <div class="title h1" v-if="!isModifyMode">任务</div>
    <div class="create-body">
      <div class="title h2" v-if="!isModifyMode">基本信息</div>
      <el-form :model="task" :rules="rules" ref="task" label-width="120px" class="demo-task"
               style="margin:0 100px;">
        <el-form-item label="任务名称" prop="title" style="width: 700px;">
          <el-input size="small" v-if="isModifyMode" v-model="task.title"></el-input>
          <span v-if="!isModifyMode">{{task.title}}</span>
          <el-tag v-if="!isModifyMode" :type="task.statusVO&&task.statusVO.style">{{task.statusVO ?
            task.statusVO.text:''}}
          </el-tag>
        </el-form-item>
        <el-form-item label="任务描述" prop="desc" style="width: 700px;">
          <el-input autosize v-if="isModifyMode" type="textarea" v-model="task.description"></el-input>
          <span v-if="!isModifyMode">{{task.description ? task.description : '暂无'}}</span>
        </el-form-item>
        <el-form-item label="任务报价" prop="quotePrice" style="width: 700px;">
          <el-input size="small" type="number" v-if="isModifyMode" v-model="task.quotePrice">
            <template slot="append">¥</template>
          </el-input>
          <span v-if="!isModifyMode">{{task.quotePrice}}￥</span>
        </el-form-item>
        <!--<el-form-item type="number" label="任务定价" prop="fixedPrice">-->
        <!--<el-input v-if="isModifyMode" v-model="task.fixedPrice">-->
        <!--<template slot="append">¥</template>-->
        <!--</el-input>-->
        <!--<span v-if="!isModifyMode">{{task.fixedPrice}}</span>-->
        <!--</el-form-item>-->
        <el-form-item label="测试类型" prop="serviceType">
          <el-radio-group v-if="isModifyMode" v-model="task.serviceType" @change="handleTestTypeChange">
            <span v-for="(item,index) in serviceType" :key="index">
              <el-radio :label="item.code" name="serviceType">{{item.name}}</el-radio>
            </span>
          </el-radio-group>
          <span class="badge" v-if="!isModifyMode">{{serviceName}}</span>
        </el-form-item>

        <el-form-item label="服务序列号" prop="endPoint" style="width: 700px;"
                      v-if="showBD&&task.endPoint&&currType.type===1"
                      >
          <el-input v-if="isModifyMode" v-model="task.endPoint.serverCode" label="examId"></el-input>
          <span v-if="!isModifyMode&&showBD">{{task.endPoint.serverCode}}</span>
        </el-form-item>

        <el-form-item label="任务可见性" prop="resource" style="width: 700px;">
          <div v-if="!isModifyMode">
            <!--<div v-if="task.resource=='1'">{{updateLocation(task.location)}}</div>-->
            <div v-if="task.resource==0">定向</div>
            <div v-if="task.resource==2">{{resourceType[task.resource]}}</div>
          </div>
          <el-tabs
            :tab-position="tabPosition"
            v-model="task.resource"
            style="max-height: 200px;"
            v-if="isModifyMode"
          >
            <el-tab-pane :label="resourceType[0]" name="0">
              <el-radio-group v-model="task.institution" @change="handleTestTypeChange">
                <el-radio
                  :label="item"
                  name="type"
                  v-for="item,index in institutionArray"
                  :key="index"
                >{{item.evaluationAgencyName}}
                </el-radio>
              </el-radio-group>
            </el-tab-pane>
            <!--<el-tab-pane :label="resourceType[1]" name="1">-->
            <!--<provincecity-->
            <!--ref="addFormProvince"-->
            <!--@selectChange="locationChange"-->
            <!--:provinceCode="task.location == null ||task.location.provinceCode==null?'3200':task.location.provinceCode"-->
            <!--:cityCode="task.location == null ||task.location.cityCode==null?'3201':task.location.cityCode"-->
            <!--&gt;</provincecity>-->
            <!--</el-tab-pane>-->
            <el-tab-pane :label="resourceType[2]" name="2"></el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item label="领取人数" prop="contactPhone" v-if="isModifyMode&&task.resource !== '0' && currType.type===0">
          <el-input-number v-model="task.participantCount" :min="1" :max="1000" label="领取人数"></el-input-number>
        </el-form-item>
        <el-form-item label="领取人数" prop="contactPhone" v-if="isModifyMode&&task.resource !== '0' && currType.type===1">
          <el-input-number v-model="task.participantCount" :min="2" :max="1000" label="领取人数"></el-input-number>
        </el-form-item>
        <el-form-item label="领取人数" prop="quotePrice" v-if="!isModifyMode">
          {{task.acceptedCount }}/{{ task.participantCount}}
        </el-form-item>
        <el-form-item label="需求文档" prop="doc">
          <el-upload
            style="width: 400px"
            v-if="isModifyMode"
            drag
            class="upload-demo"
            action=""
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"

            :http-request="uploadRequireDoc"
            :file-list="task.doc"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
          </el-upload>
          <span>
              <span v-if="task.requireDocUrl == null || task.requireDocUrl == ''">
                <i class="el-icon-document"></i>暂无文件
              </span>
              <span v-if="task.requireDocUrl != null && task.requireDocUrl != ''">
                <a :href="task.requireDocUrl"><el-link :underline="false" type="primary"><i
                  class="el-icon-document"></i>下载文档</el-link></a>
              </span>
            </span>
        </el-form-item>

        <el-form-item label="任务截止时间" prop="datetime">
          <div class="block" v-if="isModifyMode">
            <el-date-picker
              size="small"
              v-model="task.datetime"
              type="datetime"
              placeholder="选择截止时间"
              align="right"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </div>
          <span v-if="!isModifyMode">{{dateFormat(new Date(task.datetime),'yyyy-MM-dd HH:mm:ss')}}</span>
        </el-form-item>
        <el-form-item v-if="isModifyMode">
          <div class="btn btn-small btn-info" @click="updateTask()">确认修改</div>
          <!--<div class="btn btn-small" @click="resetForm()">重置</div>-->
          <div class="btn btn-small" @click="cancelMode()">取消</div>
        </el-form-item>
        <el-form-item v-if="!isModifyMode">
          <el-button size="mini" @click="toProject()">项目详情</el-button>
          <el-popover
            placement="top-start"
            title="确认结束？"
            width="200"
            trigger="hover"
            content="测评机构已提交结束申请，请确认是否结束该任务">
            <el-button v-if="taskOperationControl.confirmFinish" type="success" size="mini" slot="reference"
                       @click="endTask()">确认结束
            </el-button>
          </el-popover>

          <el-popover
            placement="top-start"
            title="确认提交？"
            width="200"
            trigger="hover"
            content="提交任务后不可更改，等待区域管理员验收">
            <el-button v-if="taskOperationControl.finish" type="primary" size="mini" slot="reference"
                       @click="submitTaskRequest()">提交任务
            </el-button>
          </el-popover>

          <el-popover
            placement="top-start"
            title="确认拒绝？"
            width="200"
            trigger="hover"
            content="拒绝后不可再接收此任务，且该任务对您不可见">
            <el-button v-if="taskOperationControl.reject" type="danger" size="mini" slot="reference"
                       @click="rejectTask()">拒绝任务
            </el-button>
          </el-popover>

          <el-popover
            placement="top-start"
            title="确认接收？"
            width="200"
            trigger="hover"
            content="接收任务后请认真完成！">
            <el-button v-if="taskOperationControl.receive" type="primary" size="mini" slot="reference"
                       @click="receiveTask()">接收任务
            </el-button>
          </el-popover>

          <el-button v-if="taskOperationControl.writeReport" type="primary" size="mini" @click="gotoWriteReport()">填写报告
          </el-button>

          <el-button v-if="taskOperationControl.update" type="primary" size="mini" @click="modifyForm()">修改任务
          </el-button>
          <el-button v-if="taskOperationControl.uploadReport" type="primary" size="mini" @click="toCreateReport()">
            上传报告
          </el-button>
          <!--<div class="btn btn-small btn-info"-->
          <!--v-if="taskOperationControl.confirmFinish"-->
          <!--@click="endTask()">确认结束-->
          <!--</div>-->
          <!--<div class="btn btn-small btn-info" v-if="!taskOperationControl.finish" @click="submitTaskRequest()">提交任务-->
          <!--</div>-->
          <!--<div class="btn btn-small btn-info" v-if="!taskOperationControl.receive" @click="receiveTask()">接收任务</div>-->
          <!--<div class="btn btn-small btn-danger" v-if="!taskOperationControl.reject" @click="rejectTask()">拒绝任务</div>-->
          <!--<div class="btn btn-small btn-info" v-if="taskOperationControl.update" @click="modifyForm()">修改任务</div>-->
          <!--<div class="btn btn-small btn-info" v-if="!taskOperationControl.uploadReport" @click="toCreateReport()">上传报告-->
          <!--</div>-->

        </el-form-item>
      </el-form>
    </div>
    <div class="create-body" v-if="!isModifyMode">
      <div class="title h2">用户报告列表</div>
      <el-collapse accordion style="margin: 0 30px">
        <el-collapse-item v-for="(item,index) in acceptedUserList" :key="item.id">
          <template slot="title">
            <el-row style="width: 100%;font-size: 16px">
              <el-col :span="6">{{item.userVO.userName}}</el-col>
              <el-col :span="6">{{item.userVO.email}}</el-col>
              <el-col :span="6">
                <el-tag type="success" v-if="item.crowdReportVOS">已提交报告</el-tag>
                <el-tag type="info" v-if="!item.crowdReportVOS">未提交报告</el-tag>
              </el-col>
              <el-col :span="6">
                <el-tag type="success" v-if="item.isCommitted">已提交任务</el-tag>
                <el-tag type="info" v-if="!item.isCommitted">未提交任务</el-tag>
              </el-col>
            </el-row>
          </template>
          <report-list v-bind:reports="item.crowdReportVOS" v-bind:taskId="taskId" v-bind:projectId="projectId"/>
        </el-collapse-item>
      </el-collapse>
      <!--      <report-list v-if="isAgency" v-bind:reports="reportList" v-bind:taskId="taskId" v-bind:projectId="projectId"/>-->
      <!--      <report-list v-bind:reports="reportList" v-bind:taskId="taskId" v-bind:projectId="projectId"/>-->
    </div>
  </div>
</template>

<script>
  import ResourceType from '@/constants/enum/resource-type.js'
  import provincecity from '@/components/commons/ProvinceCity'
  import ReportList from '@/components/report/ReportList'
  import Http from '@/js/http.js'
  import Apis from '@/js/api.js'
  import {notify} from '@/constants/index'
  import {
    ensureEndTask,
    getAllAgencies,
    getAllServiceTypes,
    getFormalTimeFromDate,
    getProvinceCodeByProvinceName,
    getProvinceNameByProvinceCode,
    getTask,
    receiveTaskRequest,
    rejectTask,
    storageGet,
    submitTaskRequest,
    updateTask
  } from '@/js/index'

  export default {
    name: 'Task',
    components: {
      provincecity,
      ReportList
    },
    data() {
      return {
        currType: {},
        user: {},
        serviceName:'',
        showBD: true,
        rolesPermissions: {},
        loading: false,
        isModifyMode: false,
        institutionArray: [],
        tabPosition: 'top',
        resourceType: ResourceType,
        serviceType: [],
        taskId: '',
        projectId: '',
        taskOperationControl: {
          confirmFinish: false,
          finish: false,
          receive: false,
          update: false,
          uploadReport: false
        },
        crowdReportUrl: '',
        task: {
          agencyId: '',
          status: '',
          name: '',
          desc: '',
          serviceType: '',
          resource: '',
          location: {},
          institution: {},
          datetime: '',
          quotePrice: '',
          fixedPrice: '',
          doc: [],
          requireDocUrl: '',
          participantCount: 1,
          title: '',
          description: '',
          endPoint: {
            serverCode: '',
          }
        },
        reportList: [],
        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)
              }
            }
          ]
        },
        rules: {
          title: [
            {required: true, message: '请输入任务名称', trigger: 'blur'},
            {min: 5, max: 50, message: '任务名称长度在 5 到 50 个字符', trigger: 'blur'}
          ],
          serviceType: [
            {required: true, message: '测试类型不可为空', trigger: 'change'},
          ],
          desc: [{required: false, message: '请填写描述', trigger: 'blur'}],
          //price: [{required: true, message: '请填写价格', trigger: 'blur'}],
          quotePrice: [
            {required: true, message: '预算不可为空', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (value < 0) {
                  callback(new Error('请输入不小于0的数'))
                } else {
                  callback()
                }
              }, trigger: 'blur'
            },
          ],
          resource: [
            {required: true},
            {
              validator: (rule, value, callback) => {
                if (value == 0 && this.task.institution.id == null) {
                  callback(new Error('定向发布至少要选择一个测评机构'))
                } else {
                  callback()
                }
              }, trigger: 'change'
            },
          ],
          endPoint: [
            {
              validator: (rule, value, callback) => {
                if (this.currType.type === 1 && this.task.endPoint.serverCode === '') {
                  callback(new Error('请填写对应得服务序列号'))
                } else {
                  callback()
                }
              }, trigger: ['change','blur']
            },
          ],
          datetime: [{required: true, message: '截止时间不可为空', trigger: 'blur'}],
        },
        acceptedUserList: [],
      }
    },
    watch: {
      institutionArray(val) {
        this.institutionArray = val
      },
      serviceType(val) {
        this.serviceType = val
      },
      // 'task.institution' () {
      //   if (this.task.institution) {
      //     //this.$refs.addFormProvince.resetProviceCity()
      //     this.task.location = {provinceCode: '', cityCode: ''}
      //   }
      // },
      // 'task.location' () {
      //   if (this.task.location.provinceCode || this.task.location.cityCode) {
      //     this.task.institution = ''
      //   }
      // },
      // 'task.resource' () {
      //   if (this.task.resource == '广场') {
      //     this.$refs.addFormProvince.resetProviceCity()
      //     this.task.institution = ''
      //     this.task.location = {provinceCode: '', cityCode: ''}
      //   }
      // },
      deep: true
    },
    mounted() {
      this.$nextTick(() => {
        this.init()
      })
    },
    methods: {
      getServiceByCode(code){
        let serviceName = this.serviceType.filter((item) => {
          return item.code === code;
        });
        return serviceName&&serviceName[0]&&serviceName[0]['name']
      },

      handleTestTypeChange(val) {
        let type = this.serviceType.filter((item) => {
          return item.code === val;
        });
        this.currType = type[0] ? type[0] : {};
        if (this.currType.type === 0) {
          this.task.participantCount = 1
          this.$refs.task.clearValidate('endPoint');
        }
      },
      init() {
        this.taskId = this.$route.params.taskId
        this.projectId = this.$route.params.projectId
        this.setUserInfo()
        this.setServiceType()
        //this.loadData(this.projectId, this.taskId)
        this.getTaskDetail()
        this.setInstitutions()
      },

      //北斗测试报告填写跳转
      gotoWriteReport() {
        window.open(this.crowdReportUrl, '_blank');
      },

      //跳转至项目详情页面
      toProject() {
        this.$router.push({
          name: 'Project',
          params: {projectId: this.projectId}
        })
      },

      //切换至可编辑页面
      modifyForm() {
        // this.task.serviceType = ''
        this.isModifyMode = true
      },
      //切换至不可编辑页面
      cancelMode() {
        this.isModifyMode = false
      },
      //重置表单
      resetForm() {
        this.task.name = ''
        this.task.desc = ''
        this.task.quotePrice = ''
        this.task.fixedPrice = ''
        this.task.type = ''
        this.task.resource = '2' //如果是广场不用管Location和institution ,定向看institution,区域看location
        this.task.location = {provinceCode: '', cityCode: ''}
        this.task.institution = ''
        this.task.datetime = ''
        this.task.participantCount = 1
        // this.task.endPointVO.caseId = ''
        // this.task.endPointVO.examId = ''
      },
      //显示页面加载画面
      showLoading() {
        this.loading = true
      },
      //隐藏页面加载画面
      hideLoading() {
        this.loading = false
      },
      //加载用户信息
      setUserInfo() {
        this.user = storageGet('user')
        this.rolesPermissions = storageGet('rolesPermissions')
        if (storageGet('rolesPermissions').isRegionManager || storageGet('rolesPermissions').isSystemAdministrator) {
          this.showBD = true;
        } else {
          this.showBD = false;
        }
      },
      //加载任务的测试类型
      setServiceType() {
        getAllServiceTypes().then((res) => {
          this.serviceType = res
        }).catch((error) => {
          notify('error', '加载测试类型失败')
        })
      },
      //加载所有的测评机构
      setInstitutions() {
        getAllAgencies().then((res) => {
          this.institutionArray = res
        }).catch((error) => {
          notify('error', '获取机构列表失败')
        })
      },
      //获取任务详情
      getTaskDetail() {
        this.showLoading()
        getTask(this.projectId, this.taskId, this.getTaskDetailSuccess, this.getTaskDetailFail)
      },
      //获取任务详情成功时回调函数
      getTaskDetailSuccess(res) {
        this.hideLoading()
        this.taskId = res.crowdTaskVO.id
        this.projectId = res.crowdTaskVO.projectId
        this.task.title = res.crowdTaskVO.title
        this.task.description = res.crowdTaskVO.description
        this.task.serviceType = res.crowdTaskVO.serviceType
        this.task.resource = res.crowdTaskVO.resource.toString()
        this.task.location = getProvinceCodeByProvinceName(res.crowdTaskVO.location.provinceCode, res.crowdTaskVO.location.cityCode)
        this.task.institution = res.crowdTaskVO.institution
        this.task.datetime = new Date(res.crowdTaskVO.datetime)
        this.task.quotePrice = res.crowdTaskVO.quotePrice
        this.task.acceptedCount = res.crowdTaskVO.acceptedCount
        this.task.participantCount = res.crowdTaskVO.participantCount
        this.task.fixedPrice = res.crowdTaskVO.fixedPrice
        this.task.doc = []
        this.task.requireDocUrl = res.crowdTaskVO.requirementFile
        this.task.agencyId = res.crowdTaskVO.agencyId
        this.task.status = res.crowdTaskVO.status
        this.task.statusVO = res.crowdTaskVO.statusVO
        this.task.endPoint = res.crowdTaskVO.endPointVO ? res.crowdTaskVO.endPointVO : {
          serverCode: '',
        }
        this.taskOperationControl = res.taskOperationControl
        this.acceptedUserList = res.acceptedUserList;
        this.crowdReportUrl = res.crowdTaskVO.writeReportUrl;
        this.handleFormatReport(this.acceptedUserList);
        this.handleTestTypeChange(res.crowdTaskVO.serviceType);
        this.serviceName = this.getServiceByCode(res.crowdTaskVO.serviceType);
      },
      //获取任务详情失败时回调函数
      getTaskDetailFail(error) {
        this.hideLoading()
        // notify('error', '获取任务详情失败:' + error.data)
      },

      //处理显示报告
      handleFormatReport(acceptedUserList) {
        acceptedUserList.map((user) => {
          user.crowdReportVOS && user.crowdReportVOS.map((report) => {
            report.userName = user.userVO.userName;
            this.reportList.push(report);
          })
        })
      },

      dateFormat(date, format) {
        date = new Date(date)
        let o = {
          'M+': date.getMonth() + 1, //month
          'd+': date.getDate(), //day
          'H+': date.getHours(), //hour+8小时
          'm+': date.getMinutes(), //minute
          's+': date.getSeconds(), //second
          'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
          'S': date.getMilliseconds() //millisecond
        }
        if (/(y+)/.test(format)) {
          format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        }

        for (let k in o)
          if (new RegExp('(' + k + ')').test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));

        return format;
      },

      //更新任务信息
      updateTask() {
        this.$refs['task'].validate(valid => {
          if (valid) {
            this.showLoading()
            const newTask = {
              name: this.task.title,
              desc: this.task.description,
              type: this.task.serviceType,
              resource: this.task.resource,
              location: this.task.location == null ? {} : getProvinceNameByProvinceCode(this.task.location.provinceCode, this.task.location.cityCode),
              institution: this.task.institution ? this.task.institution.id : null,
              datetime: this.task.datetime,
              quotePrice: this.task.quotePrice,
              fixedPrice: this.task.fixedPrice,
              requirementFile: this.task.requireDocUrl,
              participantCount: this.task.participantCount,
              endPoint: this.task.endPoint
            }
            //console.log(newTask)
            updateTask(this.projectId, this.taskId, newTask, this.updateTaskSuccess, this.updateTaskFail)
          } else {
            notify('error', '表单填写有误！')
            return false
          }
        })
      },
      //更新任务信息成功时回调函数
      updateTaskSuccess(res) {
        this.cancelMode()
        this.taskId = res.crowdTaskVO.id
        this.projectId = res.crowdTaskVO.projectId
        this.task.title = res.crowdTaskVO.title
        this.task.description = res.crowdTaskVO.description
        this.task.serviceType = res.crowdTaskVO.serviceType
        this.task.resource = res.crowdTaskVO.resource
        this.task.location = res.crowdTaskVO.location == null ? {
          provinceCode: 3200,
          cityCode: 3201
        } : getProvinceCodeByProvinceName(res.crowdTaskVO.location.provinceCode, res.crowdTaskVO.location.cityCode)
        this.task.institution = res.crowdTaskVO.institution
        this.task.datetime = new Date(res.crowdTaskVO.datetime)
        this.task.quotePrice = res.crowdTaskVO.quotePrice
        this.task.fixedPrice = res.crowdTaskVO.fixedPrice
        // this.task.endPointVO = res.crowdTaskVO.endPointVO
        this.task.doc = []
        this.task.requireDocUrl = res.crowdTaskVO.requirementFile,
          this.task.participantCount = res.crowdTaskVO.participantCount
          this.task.endPoint = res.crowdTaskVO.endPointVO ? res.crowdTaskVO.endPointVO : {
            serverCode: '',
          }
        this.reportList = res.crowdReportVOList
        this.acceptedUserList = res.acceptedUserList
        this.handleTestTypeChange(res.crowdTaskVO.serviceType);
        this.serviceName = this.getServiceByCode(res.crowdTaskVO.serviceType);
        this.hideLoading()
        notify('success', '修改成功')
      },
      //更新任务信息失败时回调函数
      updateTaskFail(error) {
        notify('error', '修改失败:' + error.data)
        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) => {
          notify('success', '上传成功')
          this.uploadRequireDocSuccess(res)
        }).catch((error) => {
          notify('error', '上传失败:' + error.data)
          this.uploadRequireDocFail(error)
        })
      },
      //上传任务需求文档成功时回调函数
      uploadRequireDocSuccess(res) {
        this.hideLoading()
        console.log('上传成功')
        this.task.requireDocUrl = res.data
        console.log(res.data)
      },
      //上传任务需求文档失败时回调函数
      uploadRequireDocFail(error) {
        this.hideLoading()
        notify('error', '任务需求文档上传失败：' + error.data)
      },
      //文档上传前响应函数

      //移除文档前的响应函数
      beforeRemove(file, fileList) {
        //return this.$confirm(`确定移除 ${file.name}？`)
      },
      //移除文档时的响应函数
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      //需求文档添加进来时的响应函数
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 1 个文件，本次选择了 ${
            files.length
            } 个文件，共选择了 ${files.length + fileList.length} 个文件`
        )
      },
      //接收任务
      receiveTask() {
        this.$confirm('确认接收任务？', '提示', {
          confirmButtonText: '确认接收',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          this.showLoading()
          receiveTaskRequest(this.projectId, this.taskId, this.user.userVO.id, this.receiveTaskSuccess, this.receiveTaskFail)
        }).catch(() => {
        })
      },
      //接收任务成功时的回调函数
      receiveTaskSuccess(res) {
        this.hideLoading()
        this.getTaskDetail();
        notify('success', '接收任务成功')
        // console.log(res)
        this.taskOperationControl = res.taskOperationControl
        this.task.status = res.crowdTaskVO.status
        this.task.institution = res.crowdTaskVO.institution
      },
      //接收任务失败时的回调函数
      receiveTaskFail(error) {
        this.hideLoading()
        notify('error', '接收任务失败：' + error.data)
      },
      //拒绝任务
      rejectTask() {
        this.$confirm('确认拒绝任务？拒绝后将不能再接收该任务', '提示', {
          confirmButtonText: '确认拒绝',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          this.showLoading()
          rejectTask(this.projectId, this.taskId, this.rejectTaskSuccess, this.rejectTaskFail)
        }).catch(() => {

        })
      },
      //拒绝任务成功时的回调函数
      rejectTaskSuccess(res) {
        this.hideLoading()
        this.$router.push({
          name: 'Mine'
        })
        notify('success', '拒绝任务成功，已为您自动跳转到个人中心')
      },
      //拒绝任务失败时的回调函数
      rejectTaskFail(error) {
        this.hideLoading()
        notify('error', '拒绝任务失败：' + error.data)
      },
      //提交结束任务申请
      submitTaskRequest() {
        this.$confirm('确认提交任务？提交后将不能再修改', '提示', {
          confirmButtonText: '确认提交',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          this.showLoading()
          submitTaskRequest(this.projectId, this.taskId, this.submitTaskRequestSuccess, this.submitTaskRequestFail)

        }).catch(() => {

        })
      },
      //提交结束任务申请成功时的回调函数
      submitTaskRequestSuccess(res) {
        this.hideLoading()
        console.log(res)
        this.taskOperationControl = res.taskOperationControl
        this.task.status = res.crowdTaskVO.status
        this.task.institution = res.crowdTaskVO.institution
        notify('success', '提交任务成功，等待区域管理员审核')
        this.getTaskDetail();
      },
      //提交结束任务申请失败时的回调函数
      submitTaskRequestFail(error) {
        this.hideLoading()
        notify('error', '提交任务失败：' + error.data)
      },
      //结束任务
      endTask() {
        this.$confirm('确认结束任务？', '提示', {
          confirmButtonText: '确认结束',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          this.getTaskDetail()
          this.showLoading()
          ensureEndTask(this.projectId, this.taskId, this.endTaskSuccess, this.endTaskFail)
        }).catch(() => {

        })
      },
      //结束任务成功时的回调函数
      endTaskSuccess(res) {
        this.hideLoading()
        this.taskOperationControl = res.taskOperationControl
        this.task.status = res.crowdTaskVO.status
        this.task.institution = res.crowdTaskVO.institution
        notify('success', '结束任务成功！')
        this.getTaskDetail();
      },
      //结束任务失败时的回调函数
      endTaskFail(error) {
        this.hideLoading()
        notify('error', '结束任务失败：' + error.data)
      },
      //跳转到创建项目报告页面
      toCreateReport() {
        this.$router.push({
          name: 'TaskReportCreate',
          params: {
            scope: 1,
            dependencyCode: this.taskId,
            projectId: this.projectId,
            taskId: this.taskId,
          }
        })
      },
      reformDate(date) {
        return getFormalTimeFromDate(date)
      }
    },
  }
  //回收站
  //
  // updateLocation (location) {
  //   console.log(location)
  //   const loactionName = getProvinceNameByProvinceCode(location.provinceCode, location.cityCode)
  //   // var provinceName = ''
  //   // var cityName = ''
  //   // for (var item of provinceCityJSON.provinces) {
  //   //   if (item.code === location.provinceCode) {
  //   //     provinceName = item.name
  //   //     for (var city of item.cities) {
  //   //       if (city.code === location.cityCode) {
  //   //         cityName = city.name
  //   //         break
  //   //       }
  //   //     }
  //   //   }
  //   // }
  //   return loactionName.provinceCode + ' / ' + loactionName.cityCode
  // },
  //
  // locationChange (provinceId, cityId) {
  //   if (provinceId || cityId) {
  //     this.task.location = {provinceCode: provinceId, cityCode: cityId}
  //   }
  // },
  // submitForm (formName) {
  // this.$refs[formName].validate(valid => {
  //   if (valid) {
  //     this.isModifyMode = false
  //
  //   } else {
  //     console.log('error submit!!')
  //     return false
  //   }
  // })
  // },
</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-collapse-item__content {
    padding-bottom: 0 !important;
  }
</style>
