<template>
  <div class="create-container">
    <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 v-model="project.name"></el-input>
        </el-form-item>
        <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="platform">
          <el-checkbox-group v-model="project.platform">
            <el-checkbox label="0">IOS</el-checkbox>
            <el-checkbox label="1">ANDROID</el-checkbox>
            <el-checkbox label="2">WEB</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="需求描述" prop="desc">
          <el-input type="textarea" v-model="project.desc"></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="type">
          <el-checkbox-group v-model="project.type">
            <el-checkbox label="0" name="0">接口测试</el-checkbox>
            <el-checkbox label="1" name="1">安全漏洞扫描</el-checkbox>
            <el-checkbox label="2" name="2">风险评估服务</el-checkbox>
            <el-checkbox label="3" name="3">源代码安全审计服务</el-checkbox>
            <el-checkbox label="4" name="4">功能测试服务</el-checkbox>
            <el-checkbox label="5" name="5">性能测试</el-checkbox>
            <el-checkbox label="6" name="6">功能和易用性测试</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="用途" prop="usage">
          <el-input v-model="project.usage"></el-input>
        </el-form-item>
        <el-form-item label="预算" prop="budget">
          <el-input type="number" v-model="project.budget">
            <template slot="append">¥</template>
          </el-input>
        </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">
                <el-radio
                  :label="item"
                  name="type"
                  v-for="item,index in institutionArray"
                  :key="index"
                ></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
            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>
            <div class="el-upload__tip" slot="tip">请上传需求文档</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="安装包" prop="file">
          <el-upload
            drag
            class="upload-demo"
            action=""
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :before-upload="beforeFileUpload"
            :http-request="uploadApkFile"
            :file-list="project.file"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">只能上传Android或IOS安装包文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目截止时间" prop="datetime">
          <div class="block">
            <el-date-picker
              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 Enum from '@/constants/enum/index'
import PlatformType from '@/constants/enum/platform-type'
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 ServiceType from '@/constants/enum/service-type'
import ResourceType from '@/constants/enum/resource-type'

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 {
      tabPosition: 'top',
      institutionArray: Enum.institution,
      platformType: [],
      serviceType: ServiceType,
      resourceType: ResourceType,
      project: {
        userId: 3,
        name: '',
        contactName: '',
        contactPhone: '',
        type: [],
        platform: [],
        desc: '',
        doc: '123',
        file: '123',
        resource: '0',
        location: {provinceCode: '3200', cityCode: '3201'},
        institution: '',
        datetime: '',
        price: '',
        usage: '',
        budget: ''
      },
      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: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        type: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一种服务类型',
            trigger: 'change'
          }
        ],
        platform: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个平台',
            trigger: 'change'
          }
        ],
        desc: [{required: true, message: '请填写活动形式', trigger: 'blur'}],
        contact: [{validator: validatePass, trigger: 'blur'}],
        resource: [
          {
            required: true,
            message: '请选择项目可见性',
            trigger: 'change'
          }
        ]
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  watch: {
    '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.project.platform.map(item => {
        this.platformType.push(PlatformType[item])
      })
    },
    submitForm (formName) {
      Http.post(Apis.PROJECT.CREATE_PROJECT, this.project).then((res) => {
        console.log(res.status)
        if (window.history.length <= 1) {
          this.$router.push({path: '/'})
          return false
        } else {
          this.$router.go(-1)
        }
      })
      // this.$refs[formName].validate(valid => {
      //   if (valid) {
      //     Http.post(Apis.PROJECT.CREATE_PROJECT, this.project).then((res) => {
      //       console.log(res.status)
      //     })
      //     //提交 project
      //   } else {
      //     console.log('error submit!!')
      //     return false
      //   }
      // })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.project.name = ''
      this.project.type = []
      this.project.platform = []
      this.project.desc = ''
      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 = ''
    },
    beforeFileUpload (file) {
      // const isAPK = file.type === 'application/vnd.android.package-archive'
      // const isDMG = file.type === 'application/octet-stream'
      //
      // if (!isAPK && !isDMG) {
      //   this.$message.error('上传安装包只能是 APK 或 DMG 格式!')
      // }
      // return isAPK && isDMG
    },
    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) {
      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}', 3), formData, config).then((res) => {
        console.log('上传成功')
        this.project.requireDocUrl = res.data
        console.log(res.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}', 3), formData, config).then((res) => {
        console.log('上传成功')
        this.project.fileUrl = res.data
        console.log(res)
      })
    }
  }
}
</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;
  }
</style>

