<template>
  <div class="create-container" v-loading="loading">
    <div class="title h1">创建项目</div>
    <div class="create-body">
      <el-form :model="project" :rules="rules" ref="project" label-width="12%" class="demo-project">
        <el-form-item label="项目名称" prop="name">
          <el-input size="small" v-model="project.name" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input size="small" v-model="project.contactName" placeholder="请输入联系人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="contactPhone">
          <el-input size="small" v-model="project.contactPhone" placeholder="请输入联系人电话"></el-input>
        </el-form-item>
        <el-form-item label="预算" prop="budget">
          <el-input size="small" type="number" v-model="project.budget" placeholder="请输入项目预算">
            <template slot="append">¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="计价标准" prop="valuationStandard">
          <el-input type="textarea" style="width: 400px" v-model="project.valuationStandard"
                    placeholder="请输入项目的计价标准（eg:1200/人天）"></el-input>
        </el-form-item>
        <el-form-item label="需求描述" prop="desc">
          <el-input type="textarea" style="width: 400px" v-model="project.desc"
                    placeholder="请输入对项目的描述"></el-input>
        </el-form-item>
        <!--<el-form-item label="价格" prop="price">-->
        <!--<el-input type="number" v-model="project.price">-->
        <!--<template slot="append">¥</template>-->
        <!--</el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="领域类型" prop="field">
          <el-radio-group v-model="project.field">
            <span v-for="(item,index) in fields" :key="index">
              <el-radio :label="item.code">{{ item.name }}&nbsp;&nbsp;&nbsp;&nbsp;</el-radio>
            </span>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="应用类型" prop="platform">
          <el-radio-group v-model="project.platform">
            <span v-for="(item,index) in platforms" :key="index">
              <el-radio :label="item.code">{{ item.name }}&nbsp;&nbsp;&nbsp;&nbsp;</el-radio>
            </span>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="测试类型" prop="type">
          <el-checkbox-group v-model="project.type">
            <span v-for="(item,index) in serviceType" :key="index">
              <el-checkbox :label="item.code" name="type">{{item.name}}&nbsp;&nbsp;&nbsp;&nbsp;</el-checkbox>
            </span>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="项目可见性" prop="resource">
          <el-tabs
            :tab-position="tabPosition"
            v-model="project.resource"
            style="max-height: 200px;"
          >
            <el-tab-pane :label="resourceType[0]" name="0">
              <el-radio-group v-model="project.institution" prop="institution">
                <el-radio :label="item" name="type" v-for="item,index in institutionArray" :key="index">{{item.name}}
                </el-radio>
              </el-radio-group>
            </el-tab-pane>
            <el-tab-pane :label="resourceType[1]" name="1">
              <provincecity
                ref="addFormProvince"
                @selectChange="locationChange"
                :provinceCode="project.location.provinceCode"
                :cityCode="project.location.cityCode"
              ></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="doc">
          <el-upload
            style="width: 400px"
            drag
            class="upload-demo"
            action=""
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :before-upload="beforeFileUpload"
            :http-request="uploadRequireDoc"
            :file-list="project.doc"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="安装包" prop="file">
          <el-upload
            drag
            style="width: 400px"
            class="upload-demo"
            action=""
            :on-remove="handleRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :before-upload="beforeApkUpload"
            :http-request="uploadApkFile"
            :file-list="project.file"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目截止时间" prop="datetime">
          <div class="block">
            <el-date-picker
              size="small"
              v-model="project.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" v-on:click="submitForm('project')">立即申请</div>
          <!--<div class="btn btn-medium" @click="resetForm('project')">重置</div>-->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

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

export default {
  name: 'ProjectCreate',
  components: {
    provincecity
  },
  data () {
    var validatePass = (rule, value, callback) => {
      var reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (this.contactPhone) {
        if (!reg.test(this.contactPhone)) {
          callback(new Error('请检查手机号码'))
        } else {
          callback()
        }
      }
    }
    return {
      user: {},
      loading: false,
      tabPosition: 'top',
      institutionArray: [],
      fields:[{code: '', name: ''}],
      platforms:[{code: '', name: ''}],
      // platforms: [],
      serviceType: [{code: '', name: ''}],
      resourceType: ResourceType,
      project: {
        userId: 0,
        name: '',
        contactName: '',
        contactPhone: '',
        type: [],
        platform: '',
        valuationStandard:'',
        field: '',
        desc: '',
        doc: [],
        file: [],
        requireDocUrl: '',
        fileUrl: '',
        resource: '0',
        location: {provinceCode: '3200', cityCode: '3201'},
        institution: {},
        datetime: '',
        price: '',
        usage: '',
        budget: ''
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now();
        },
        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'}
        ],
        contactName: [
          {required: true, message: '请输入联系人姓名', trigger: 'blur'}
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        contactPhone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (!this.checkPhoneNumber(value)) {
                callback(new Error('手机号输入有误'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          },
        ],
        type: [
          {
            required: true,
            message: '请至少选择一种测试类型',
            trigger: 'change'
          }
        ],
        platform: [
          {
            required: true,
            message: '请至少选择一个应用类型',
            trigger: 'change'
          }
        ],
        field: [
          {
            required: true,
            message: '请至少选择一个领域类型',
            trigger: 'change'
          }
        ],
        desc: [{required: false, message: '请填写描述', trigger: 'blur'}],
        //price: [{required: true, message: '请填写价格', trigger: 'blur'}],
        budget: [
          {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.project.institution.id == null) {
                callback(new Error('定向发布至少要选择一个区域管理员'))
              } else {
                callback()
              }
            }, trigger: 'change'
          },
        ],
        datetime:[{required: true, message: '截止时间不可为空', trigger: 'blur'}],
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  watch: {
    serviceType (val) {
      this.serviceType = val
    },
    institutionArray (val) {
      this.institutionArray = val
    },
    // 'project.institution' () {
    //   if (this.project.institution) {
    //     this.$refs.addFormProvince.resetProviceCity()
    //     this.project.location = {provinceCode: '', cityCode: ''}
    //   }
    // },
    // 'project.location' () {
    //   if (this.project.location.provinceCode || this.project.location.cityCode) {
    //     this.project.institution = ''
    //   }
    // },
    // 'project.resource' () {
    //   if (this.project.resource == '2') {
    //     this.$refs.addFormProvince.resetProviceCity()
    //     this.project.institution = ''
    //     this.project.location = {provinceCode: '', cityCode: ''}
    //   }
    // },
    deep: true
  },
  methods: {
    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
    },
    locationChange (provinceId, cityId) {
      if (provinceId || cityId) {
        this.project.location = {provinceCode: provinceId, cityCode: cityId}
      }
    },
    init () {
      this.setServiceType()
      this.setFields()
      this.setPlatforms()
      this.setInstitution()
      this.setUserInfo()
      // this.project.platform.map(item => {
      //   this.platformType.push(PlatformType[item])
      // })
    },
    submitForm () {
      this.$refs['project'].validate(valid => {
        if (valid) {
          //console.log(this.project)
          this.showLoading()
          const newLocation = getProvinceNameByProvinceCode(this.project.location.provinceCode, this.project.location.cityCode)
          const newProject = {
            userId: this.user.userVO.id,
            name: this.project.name,
            type: this.project.type,
            platform: this.project.platform,
            field: this.project.field,
            desc: this.project.desc,
            valuationStandard: this.project.valuationStandard,
            resource: this.project.resource,
            location: newLocation,
            institution: this.project.institution.id,
            contactName: this.project.contactName,
            contactPhone: this.project.contactPhone,
            doc: this.project.requireDocUrl,
            file: this.project.fileUrl,
            budget: this.project.budget,
            datetime: this.project.datetime,
            usage: this.project.usage,
            price: this.project.price
          }
          console.log(newProject)
          Http.post(Apis.PROJECT.CREATE_PROJECT, newProject).then((res) => {
            //notify('success', '创建成功')
            this.hideLoading()
            this.createProjectSuccess(res.projectDetails.id)
            // if (window.history.length <= 1) {
            //   this.$router.push({path: '/'})
            //   return false
            // } else {
            //   this.$router.go(-1)
            // }
          }).catch(error => {
            //console.log(error)
            this.hideLoading()
            notify('error', error.data)

          })
        } else {
          console.log(valid)
          this.hideLoading()
          notify('error','表单填写错误！')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.project.name = ''
      this.project.type = []
      this.project.platform = ''
      this.project.field = ''
      this.project.desc = ''
      this.project.valuationStandard = ''
      this.project.file = ''
      this.project.doc = ''
      this.project.contactName = ''
      this.project.contactPhone = ''

      this.project.resource = '非定向'
      this.project.institution = ''
      this.project.datetime = ''
      this.project.price = ''
      this.project.usage = ''
      this.project.budget = ''
    },
    beforeApkUpload (file) {
      return true;
      //const fileType = ['exe', 'apk', 'dmg']
      //return checkFileType(file, fileType, this.beforeApkUploadError)
    },
    beforeApkUploadError () {
      this.$message.error('上传文件只能是exe,dmg,apk格式!')
    },
    beforeFileUpload (file) {
      return true;
      //const fileTypeList = ['pdf', 'xls', 'xlsx', 'doc', 'docx', 'txt']
      //return checkFileType(file, fileTypeList, this.beforeFileUploadError)
    },
    beforeFileUploadError () {
      this.$message.error('上传文件只能是 PDF 、 DOC 、DOCX 、XLS、TXT、XLSX 格式!')
    },
    loadData () {
      Http.get(Apis.PAGE.PROJECT_DETAIL_PAGE).then((res) => {
        this.project = res.project
      })
    },
    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}？`)
    },
    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) => {
        //console.log('上传成功')
        this.hideLoading()
        notify('success', '需求文档上传成功')
        this.project.requireDocUrl = res.data
        //console.log(this.project.doc)
        //console.log(res.data)
      }).catch((error) => {
        this.hideLoading()
        this.project.doc = []
        notify('error', '需求文档上传失败:' + error.data)
      })

    },
    uploadApkFile (param) {
      this.showLoading()
      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) => {
        this.hideLoading()
        notify('success', '文件上传成功')
        this.project.fileUrl = res.data
        console.log(res)
      }).catch((error) => {
        this.hideLoading()
        this.project.file = []
        notify('error', '文件上传失败：' + error.data)
      })
    },
    setServiceType () {
        getAllServiceTypes().then((res) => {
            this.serviceType = res
        })
    },
    setFields(){
        getAllFields().then((res) => {
            this.fields = res
        })
    },
    setPlatforms () {
        getAllPlatformTypes().then((res) => {
            this.platforms = res
        })
    },
    setInstitution () {
      getAllInstitutions().then((res) => {
        this.institutionArray = res
      })
    },
    setUserInfo () {
      this.user = storageGet('user')
    },
    createProjectSuccess (projectId) {
      this.$alert('项目创建成功', '创建成功', {
        confirmButtonText: '确定',
        callback: action => {
          this.$router.push({
            name: 'Project',
            params: {projectId: projectId}
          })
        }
      })
    },
    checkPhoneNumber(phoneNumber){
      return /^1[3456789]\d{9}$/.test(phoneNumber)
    },
    showLoading () {
      this.loading = true
    },
    hideLoading () {
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped>
  .el-col {
    padding: 0 !important;
  }

  .el-row {
    margin-bottom: 10px;
  }

  .el-radio {
    margin: 10px 20px 10px 0;
  }

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

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

<!--<el-form-item label="联系方式" prop="contact">-->
<!--<div>-->
<!--<el-row :gutter="2">-->
<!--<el-col :span="2">-->
<!--<span>联系人</span>-->
<!--</el-col>-->
<!--<el-col :span="10">-->
<!--<el-input v-model="project.contactName" placeholder="请输入联系人姓名"></el-input>-->
<!--</el-col>-->
<!--</el-row>-->
<!--<el-row :gutter="2">-->
<!--<el-col :span="2">-->
<!--<span>联系人电话</span>-->
<!--</el-col>-->
<!--<el-col :span="10">-->
<!--<el-input v-model="project.contactPhone" placeholder="请输入联系人电话"></el-input>-->
<!--</el-col>-->
<!--</el-row>-->
<!--</div>-->
<!--</el-form-item>-->


<!--<el-form-item label="用途" prop="usage">-->
<!--<el-input v-model="project.usage"></el-input>-->
<!--</el-form-item>-->
