<template>
  <div class="create-container" v-loading="loading">
    <div class="title h1">创建任务</div>
    <div class="create-body">
      <el-form :model="task" :rules="rules" ref="task" label-width="120px" class="demo-task" style="margin:0 100px">
        <el-form-item label="任务名称" prop="name" style="width:700px;">
          <el-input size="small" v-model="task.name"></el-input>
        </el-form-item>
        <el-form-item label="任务描述" prop="desc" style="width:700px;">
          <el-input autosize type="textarea" style="width: 400px" v-model="task.desc"></el-input>
        </el-form-item>
        <el-form-item label="任务报价" prop="quotePrice" style="width:700px;">
          <el-input size="small" type="number" v-model="task.quotePrice">
            <template slot="append">¥</template>
          </el-input>
        </el-form-item>
        <!--<el-form-item type="number" label="任务定价" prop="fixedPrice">-->
        <!--<el-input v-model="task.fixedPrice">-->
        <!--<template slot="append">¥</template>-->
        <!--</el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="测试类型" prop="type">
          <el-radio-group v-model="task.type" @change="handleTestTypeChange">
            <span v-for="(item,index) in serviceType" :key="index">
              <el-radio :label="item.code" name="type">{{item.name}}</el-radio>
            </span>
          </el-radio-group>
        </el-form-item>


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


        <el-form-item label="任务可见性" prop="resource" style="width:700px;" v-if="currType.type==0">
          <el-tabs :tab-position="tabPosition" v-model="task.resource" style="width: 800px">
            <el-tab-pane :label="resourceType[0]" name="0">
<!--              <el-radio-group v-model="task.institution">-->
<!--                <el-radio-->
<!--                  :label="item"-->
<!--                  name="type"-->
<!--                  v-for="item,index in institutionArray"-->
<!--                  :key="index"-->
<!--                >{{item.evaluationAgencyName}}-->
<!--                </el-radio>-->
<!--              </el-radio-group>-->
              <el-select v-model="task.institution" filterable placeholder="请选择">
                <el-option
                  v-for="item in institutionArray"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
              <br/>
             <el-button  type="primary" size="mini" @click="instituationEvaluate()">
                  机构评估
              </el-button>
              <el-button  type="primary" size="mini" @click="peopleEvaluate()">
                人员评估
              </el-button>
            </el-tab-pane>

            <!--<el-tab-pane :label="resourceType[1]" name="1">-->
            <!--<provincecity-->
            <!--ref="addFormProvince"-->
            <!--@selectChange="locationChange"-->
            <!--:provinceCode="task.location.provinceCode"-->
            <!--:cityCode="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="resource" style="width:700px;"
                      v-if="currType.type ==1"
                      required>
          <el-tabs :tab-position="tabPosition" v-model="task.resource" value='2' style="width: 800px">
            <el-tab-pane :label="resourceType[2]" name="2"></el-tab-pane>
          </el-tabs>
        </el-form-item>

        <el-form-item label="领取人数" prop="contactPhone" v-if="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="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="Go平台" prop="goPlatform">
          <el-radio-group v-model="task.goPlatform">
            <el-radio :label="0">不使用</el-radio>
            <el-radio :label="1">使用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="需求文档" prop="doc">
          <el-upload
            drag
            style="width: 400px"
            class="upload-demo"
            action=""
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :before-upload="beforeFileUpload"
            :http-request="uploadRequireDoc"
            :file-list="task.doc"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item size="small" label="任务截止时间" prop="datetime">
          <div class="block">
            <el-date-picker
              v-model="task.datetime"
              type="datetime"
              placeholder="选择截止时间"
              align="right"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="btn btn-medium btn-info" @click="submitForm('task')">立即创建</div>
          <!--<div class="btn btn-medium" @click="resetForm('task')">重置</div>-->
          <div class="btn btn-medium" @click="cancelCreate('task')">取消</div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import provincecity from '@/components/commons/ProvinceCity'
  import provinceCityJSON from '@/constants/provinceCity.json'
  import Http from '@/js/http.js'
  import Apis from '@/js/api.js'
  import ResourceType from '@/constants/enum/resource-type.js'
  import {notify} from '@/constants/index'
  import {getAllInstitutions, getAllServiceTypes, getProvinceNameByProvinceCode, storageGet} from '@/js/index'

  export default {
    name: 'Task',
    components: {
      provincecity
    },
    data() {
      return {
        currType: {},
        user: {},
        projectId: 0,
        institutionArray: [],
        tabPosition: 'top',
        resourceType: ResourceType,
        loading: false,
        serviceType: [],
        task: {
          name: '',
          desc: '',
          type: '',
          resource: '', //如果是广场不用管Location和institution ,定向看institution,区域看location
          // location: {provinceCode: '3200', cityCode: '3201'},
          institution: null,
          datetime: '',
          quotePrice: '',
          fixedPrice: '',
          doc: [],
          requireDocUrl: '',
          participantCount: 1,
          goPlatform: 0,
          endPoint: {
            serverCode: '',
          }
        },
        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: {
          name: [
            {required: true, message: '请输入任务名称', trigger: 'blur'},
            {min: 5, max: 50, message: '任务名称长度在 5 到 50 个字符', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '测试类型不可为空'},
          ],
          desc: [{required: true, message: '请填写描述', trigger: 'blur'}],
          //price: [{required: true, message: '请填写价格', trigger: 'blur'}],
          quotePrice: [
            {required: true, message: '预算不可为空', trigger: 'blur'},
            {
              validator: (rule, value, callback) => {
                if (parseInt(value) < 0) {
                  callback(new Error('请输入不小于0的数'))
                } else {
                  callback()
                }
              }, trigger: 'blur'
            },
          ],
          resource: [
            {required: true},
            {
              validator: (rule, value, callback) => {
                if (value == 0 && !this.task.institution) {
                  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'}],
        }
      }
    },
    watch: {
      serviceType(val) {
        this.serviceType = val
      },
      institution(val) {
        this.institution = 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: {
      instituationEvaluate(){
        let turl ='http://8.134.39.104:8088/#/enter/';
        window.open(turl,'_blank');
      },
      peopleEvaluate(){
        let turl ='http://8.134.39.104:7477/#/evaluate/evaevaall';
        window.open(turl,'_blank');
      },
      handleTestTypeChange(val) {
        let type = this.serviceType.filter((item) => {
          return item.code === val;
        });
        this.currType = type[0] ? type[0] : {};
        if (this.currType.type === 0) {
          this.$refs.task.clearValidate('endPoint');
        }else{
          this.task.resource = '2'
        }
      },
      init() {
        this.projectId = this.$route.params.projectId
        this.setServiceType()
        this.setInstitutions()
        this.setUserInfo()
      },
      updateLocation(location) {
        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 provinceName + ' / ' + cityName
      },
      submitForm(formName) {
        this.$refs['task'].validate(valid => {
          if (valid) {
            this.showLoading()
            const newTask = {
              name: this.task.name,
              desc: this.task.desc,
              type: this.task.type,
              resource: this.task.resource,
              // location: this.task.resource == '0' ? getProvinceNameByProvinceCode(this.task.location.provinceCode, this.task.location.cityCode):null,
              institution: this.task.resource === '0' ? this.task.institution : null,
              datetime: this.task.datetime,
              quotePrice: this.task.quotePrice,
              fixedPrice: this.task.fixedPrice,
              requirementFile: this.task.requireDocUrl,
              participantCount: this.task.participantCount,
              goPlatform: this.task.goPlatform,
              endPoint: this.task.endPoint
            }
            Http.post(Apis.TASK.CREATE_TASK.replace('{projectId}', this.projectId), newTask).then((res) => {
              console.log(res)
              this.hideLoading()
              this.createTaskSuccess(res.crowdTaskVO.id)
            }).catch((error) => {
              console.log(error)
              this.hideLoading()
              notify('error', error.data)
            })
          } else {
            notify('error', '表单填写有误！')
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs.addFormProvince.resetProviceCity()
        this.$refs[formName].resetFields()
        this.task.name = ''
        this.task.desc = ''
        this.task.type = ''
        this.task.resource = '广场'; //如果是广场不用管Location和institution ,定向看institution,区域看location
        this.task.location = {provinceCode: '', cityCode: ''}
        this.task.institution = null
        this.task.datetime = ''
        this.task.participantCount = 1
        this.task.goPlatform = 0
      },
      locationChange(provinceId, cityId) {
        if (provinceId || cityId) {
          this.task.location = {provinceCode: provinceId, cityCode: cityId}
        }
      },
      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}？`)
      },
      // RAR文件获取不到ContentType
      beforeFileUpload(file) {
        const isPDF = file.type === 'application/pdf'
        const isDOC = file.type === 'application/msword'
        const isDOCX = 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'
        const isZIP = file.type === 'application/x-zip-compressed'
        //console.log(file)
        if (!(isDOC || isDOCX || isEXCEL || isPDF || isTXT || isXLS || isXLSX || isZIP)) {
          this.$message.error('上传文件只能是 PDF、DOC、DOCX、XLS、TXT、XLSX、ZIP!')
        }
        return isDOC || isEXCEL || isPDF || isTXT || isXLS || isXLSX || isZIP
      },
      uploadRequireDoc(param) {
        this.showLoading()
        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) => {
          this.hideLoading()
          notify('success', '上传成功')
          this.task.requireDocUrl = res.data
          console.log(res.data)
        }).catch((error) => {
          this.hideLoading()
          notify('error', '上传失败:' + error.data)
        })
      },
      setServiceType() {
        getAllServiceTypes().then((res) => {
          this.serviceType = res
        })
      },
      setInstitutions() {
        getAllInstitutions().then((res) => {
          this.institutionArray = res
        }).catch((error) => {
          notify('error', '测评机构加载失败')
        })
      },
      setUserInfo() {
        this.user = storageGet('user')
      },
      createTaskSuccess(taskId) {
        this.$alert('任务创建成功', '创建成功', {
          confirmButtonText: '确定',
          callback: action => {
            this.$router.push({
              name: 'Task',
              params: {projectId: this.projectId, taskId: taskId}
            })
          }
        })
      },
      showLoading() {
        this.loading = true
      },
      hideLoading() {
        this.loading = false
      }
    }
  }
</script>

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

  .el-input {
    width: 400px;
  }

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