<template>
  <div class="app-container">
    <div class="box-container">
      <div class="contain-title">需求内容浏览</div>
    </div>
    <div class="content-container">
      <el-form :model="ruleFormDem" :rules="readonlyShow?{}:rules" ref="ruleFormDem" class="form-main" label-width="100px" :label-position="readonlyShow?'left':''" v-loading="formLoading">
        <div class="content-tit">{{stateShow}}
          <small v-if="ruleFormDem.state===1 && curTime > ruleFormDem.invalidDay">过期时间：{{TimeTr(ruleFormDem.invalidDay)}}</small>
          <small v-if="ruleFormDem.state===2">完成时间：{{TimeTr(ruleFormDem.overTime)}}</small>
          <small v-if="ruleFormDem.state===3">关闭时间：{{TimeTr(ruleFormDem.closeTime)}}</small>
        </div>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item v-if="ruleFormDem.state===3" label="关闭理由">
              <span>{{demandCloseReason}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="需求主题" prop="title">
              <span v-if="readonlyShow">{{ruleFormDem.title}}</span>
              <el-input v-else v-model="ruleFormDem.title" maxlength="50" placeholder="请用一句话概括您的需求"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求方名称" prop="linkOrg">
              <span v-if="readonlyShow">{{ruleFormDem.linkOrg}}</span>
              <el-input v-else v-model="ruleFormDem.linkOrg" placeholder="请填写需求方企业名称" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在城市" prop="city">
              <span v-if="readonlyShow">{{cityStr}}</span>
              <cityPicker v-else @paren="toshow" @parenStr="toshowStr" :addrCode="ruleFormDem.city"></cityPicker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需求有效期" prop="invalidDay">
              <span v-if="readonlyShow">{{TimeTr(ruleFormDem.invalidDay)}}</span>
              <el-date-picker v-else
                v-model="ruleFormDem.invalidDay"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyyMMdd"
                :editable="false"
                placeholder="请选择截止日期"
                :picker-options="pickerOptions0">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计合作周期" prop="duration">
              <span v-if="readonlyShow">{{ruleFormDem.durationStr}}</span>
              <el-select v-else v-model="ruleFormDem.duration" placeholder="请选择预计合作周期" @change="changeDuration">
                <el-option
                  v-for="item in longTime"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用预算" prop="cost">
              <span v-if="readonlyShow">{{ruleFormDem.costStr}}</span>
              <el-select v-else v-model="ruleFormDem.cost" placeholder="请选择预算范围" @change="changeCost">
                <el-option
                  v-for="item in costRange"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="linkPhone">
              <span v-if="readonlyShow">{{ruleFormDem.linkPhone}}</span>
              <el-input v-else v-model="ruleFormDem.linkPhone" placeholder="请输入您的联系电话" maxlength="50"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布用户名">
              <span>{{ownerIn.account}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名">
              <span>{{ownerIn.name}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="需求内容" prop="descp">
              <span v-if="readonlyShow" v-html="ruleFormDem.descp"></span>
              <el-input v-else type="textarea" :rows="4" v-model="ruleFormDem.descp" maxlength="1000" placeholder="请描述您的需求背景、具体问题、对专家的要求等等"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="ruleFormDem.state===2"><div class="form-line"></div></el-col>
          <el-col :span="24" v-if="ruleFormDem.state===2">
            <el-form-item label="意见建议">
              <span v-html="feedback"></span>
            </el-form-item>
          </el-col>
          <el-col :span="24" ><el-form-item style="height:20px"></el-form-item></el-col>
          <el-col :span="24">
            <el-form-item align="center" style="margin-left:-100px">
              <el-button type="primary" @click="submitForm('ruleFormDem')" style="padding: 12px 50px">确定</el-button><br/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
  import { qoDemand, editDemand, pqDemandReason, feedbackReason } from '@/api/demand'
  import queryBase from '@/utils/queryBase'
  import queryDict from '@/utils/queryDict'
  import cityPicker from '@/components/CityPicker'
  import { urlParse, TimeTr } from '@/utils'

  export default {
    data() {
      var delayValidate = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择截止日期'))
        } else {
          const curDate = (new Date()).toISOString().substring(0, 10).replace(/-/g, '')
          if (curDate > value) {
            callback(new Error('已过期，请重新选择'))
          } else {
            callback()
          }
        }
      }
      return {
        pickerOptions0: {
          disabledDate(time) {
            return time.getTime() < Date.now()
          }
        },
        curTime: (new Date()).toISOString().substring(0, 10).replace(/-/g, ''),
        TimeTr: TimeTr,
        demandId: '',
        formLoading: false,
        longTime: [],
        costRange: [],
        cityRange: [],
        demandButtExperts: '',
        cooperateExperts: '',
        buttCount: 0,
        demandCloseReason: '',
        ownerIn: {},
        feedback: '',
        cityStr: '',
        ruleFormDem: {
          title: '',
          descp: '',
          city: '',
          invalidDay: '',
          linkPhone: '',
          linkOrg: '',
          cost: '',
          duration: '',
          costStr: '',
          durationStr: ''
        },
        rules: {
          title: [
            { required: true, message: '请填写需求主题', trigger: 'blur' }
          ],
          descp: [
            { required: true, message: '请填写需求内容', trigger: 'blur' },
            { max: 1000, message: '不得超过1000个字', trigger: 'blur' }
          ],
          city: [
            { required: true, message: '请选择所在城市', trigger: 'blur' }
          ],
          invalidDay: [
            { required: true, validator: delayValidate, trigger: 'blur' }
          ],
          linkOrg: [
            { required: true, message: '请填写您所在的企业名称', trigger: 'blur' },
            { max: 50, message: '不得超过50个字', trigger: 'blur' }
          ],
          linkPhone: [
            { required: true, message: '请填写您的联系电话', trigger: 'blur' }
          ]
        }
      }
    },
    components: {
      cityPicker
    },
    watch: {
      readonlyShow(val) {
        this.readonlyShow = val
      },
      ruleFormDem(val) {
        this.ruleFormDem = val
      }
    },
    created() {
      this.getDictoryData()
      if (urlParse('id')) {
        this.demandId = urlParse('id')
        this.formLoading = true
        this.getDemandInfo()
        this.getDemandReason()
      }
    },
    computed: {
      readonlyShow() {
        return !urlParse('flag')
      },
      stateShow() {
        const state = this.ruleFormDem.state
        const curTime = this.curTime
        let msg = '发布中'
        if (state === 1) {
          msg = '发布中'
          if (curTime > this.ruleFormDem.invalidDay) {
            msg = '已过期'
          }
        } else if (state === 2) {
          msg = '已完成'
        } else if (state === 3) {
          msg = '已关闭'
        }
        return msg
      }
    },
    methods: {
      getDictoryData() {
        const that = this
        queryDict.applyDict('FYYS', function(dictData) {
          dictData.map(item => {
            that.costRange.push({ value: item.code, label: item.caption })
          })
        }) // 费用预算
        queryDict.applyDict('HZZQ', function(dictData) {
          dictData.map(item => {
            that.longTime.push({ value: item.code, label: item.caption })
          })
        }) // 合作周期
      },
      getDemandInfo() {
        var that = this
        that.$http.get(qoDemand, {
          id: that.demandId
        }, function(res) {
          if (res.success) {
            const obj = res.data
            if (obj.cost) {
              const costMM = that.costRange.find((item) => {
                return item.value === obj.cost
              })
              obj.costStr = costMM.label
            }
            if (obj.duration) {
              const durationMM = that.longTime.find((item) => {
                return item.value === obj.duration
              })
              obj.durationStr = durationMM.label
            }
            that.turnOutUserName(obj.creator)
            that.cityTurn(obj.city)
            that.formLoading = false
            that.ruleFormDem = obj
            if (obj.state === 2) {
              that.getFeedBack(obj.creator)
            }
          }
        })
      },
      cityTurn(code) {
        const that = this
        queryDict.applyDict('XZQH', function(dictData) {
          for (let i = 0; i < dictData.length; ++i) {
            if (dictData[i].code === code) {
              that.cityStr = dictData[i].caption
              break
            }
          }
        })
      },
      turnOutUserName(id) {
        var that = this
        queryBase.getNormalOne(id, function(sc, value) {
          if (sc) {
            that.ownerIn = value
          }
        })
      },
      getFeedBack(id) {
        var that = this
        this.$http.get(feedbackReason, {
          target: that.demandId,
          type: 1,
          creator: id
        }, function(res) {
          if (res.success && res.data) {
            that.feedback = res.data.cnt
          }
        })
      },
      getDemandReason() {
        var that = this
        this.$http.get(pqDemandReason, {
          id: that.demandId
        }, function(res) {
          if (res.success && res.data) {
            var arr = []
            for (let i = 0; i < res.data.length; ++i) {
              arr.push(res.data[i].descp)
            }
            that.demandCloseReason = arr.join('，')
          }
        })
      },
      submitForm(formName) {
        var that = this
        if (that.readonlyShow) {
          that.$router.back(-1)
          return
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var obj = this.ruleFormDem
            const paramsData = {
              id: that.demandId,
              title: obj.title,
              descp: obj.descp,
              city: obj.city,
              invalidDay: obj.invalidDay,
              linkPhone: obj.linkPhone,
              linkOrg: obj.linkOrg,
              cost: obj.cost,
              duration: obj.duration,
              cityStr: that.cityStr,
              costStr: obj.costStr,
              durationStr: obj.durationStr
            }
            that.$confirm('确定修改该需求信息并重新发布？', '修改需求', {
              type: 'warning'
            }).then(() => {
              that.$http.put(editDemand, paramsData, function(res) {
                if (res.success) {
                  that.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  setTimeout(function() {
                    that.$router.replace({ name: 'publishedList' })
                  }, 0)
                }
              })
            }).catch(() => {})
          } else {
            return false
          }
        })
      },
      changeDuration(val) {
        let obj = {}
        obj = this.longTime.find((item) => {
          return item.value === val
        })
        this.ruleFormDem.durationStr = obj.label
      },
      changeCost(val) {
        let obj = {}
        obj = this.costRange.find((item) => {
          return item.value === val
        })
        this.ruleFormDem.costStr = obj.label
      },
      toshow(value) {
        this.ruleFormDem.city = value
      },
      toshowStr(value) {
        this.cityStr = value
      }
    }
  }
</script>

<style>
  .form-main{
    max-width:1000px;
    margin: auto;
    padding: 10px 40px;
  }
  .content-tit{
    text-align: center;
    margin: 20px;
    font-size: 18px;
  }
  .content-tit small{
    margin-left: 20px;
  }
  .form-line{
    border-top:1px dashed #ccc;
    margin-bottom:20px;
  }
</style>
