<template>
  <div class="app-container">
    <div class="box-container">
      <div class="contain-title">新内容发布</div>
    </div>
    <div class="content-container">
      <el-form :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm formWidth">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input placeholder="请填写内容标题" v-model="ruleForm2.title" class="input-with-select" maxlength=50>
                <el-select v-model="ruleForm2.catalog" slot="prepend" placeholder="栏目分类" @change="change" class="selectWidth">
                  <el-option label="平台新闻" value="1"></el-option>
                  <el-option label="采访专栏" value="2"></el-option>
                  <el-option label="政策法规" value="3"></el-option>
                  <el-option label="通知公告" value="4"></el-option>
                </el-select>
              </el-input>
            </el-form-item>
            <el-form-item label="作者/来源" prop="source">
              <el-input v-model.number="ruleForm2.source" placeholder="请填写作者/来源" maxlength=20></el-input>
            </el-form-item>
            <searchTemplate :relevant="relevantExperts" v-on:eventName="expert" ref="sear1"></searchTemplate>
            <searchTemplate :relevant="relevantInstitutions" v-on:eventName="institution" ref="sear2"></searchTemplate>
            <searchTemplate :relevant="relevantCompanies" v-on:eventName="company" ref="sear3"></searchTemplate>
          </el-col>
          <el-col :span="12" v-if="ruleForm2.catalog === '1' || ruleForm2.catalog === '2'">
            <el-form-item style="text-align:right" prop="imgUrl">
              <uploadFile :uploadImg=uploadImg v-on:uploadfun="uploadfun" :upImgsStr="upImgsStr"></uploadFile>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="文章正文" prop="cnt" class="editBox">
          <UE :id="artUe" :contentText="ruleForm2.cnt" ref="ueBox" v-if="UEflag"></UE>
        </el-form-item>
        <el-form-item class="traftButton">
          <el-button type="info" @click="draft">保存草稿</el-button>
        </el-form-item>
        <el-form-item class="traftButton" v-if="$route.query.id">
          最后修改时间：{{modifyTime}}
        </el-form-item>
        <el-form-item class="publishButton">
          <el-button type="primary" @click="submitForm('ruleForm2')">发布</el-button>
          <el-button type="danger" @click="deleteContent" v-if="$route.query.id">删除</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import searchTemplate from '@/components/searchBar'
  import uploadFile from '@/components/uploadFile'
  import UE from '@/components/editorUE'
  import { parseTime } from '@/utils/index'
  import { uploadPhotoUrl, publishUrl, draftFirstUrl, draftUrl, draftPublishUrl, deleteUrl, inquireContentUrl } from '@/api/content'
  import request from '@/utils/request'
  import { kexiuUrl } from '@/utils'
  export default {
    data() {
      var checkTitle = (rule, value, callback) => {
        if (!value) {
          if (this.draftFlag && this.ruleForm2.catalog === '') {
            return callback('请选择该内容所属栏目分类&&请填写标题')
          }
          return callback(new Error('请填写标题'))
        } else {
          if (this.draftFlag && this.ruleForm2.catalog === '') {
            callback('请选择该内容所属栏目分类')
          }
          callback()
        }
      }
      var checkAuthorSource = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请填写作者/来源'))
        } else {
          callback()
        }
      }
      var checkContent = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请填写内容'))
        } else {
          callback()
        }
      }
      return {
        UEflag: false,
        modifyTime: '',
        draftFlag: true,
        upImgsStr: '',
        id: '',
        artUe: 'artUeditorId',
        uploadImg: {
          url: uploadPhotoUrl,
          width: '340px',
          height: '200px'
        },
        relevantExperts: {
          url: '/ajax/platform/info/buttedProfessors',
          placeholder: '请选择关联专家',
          label: '相关专家',
          prop: 'professors'
        },
        relevantInstitutions: {
          url: '/ajax/platform/info/buttedOrgs',
          placeholder: '请选择关联机构',
          label: '相关机构',
          prop: 'orgs'
        },
        relevantCompanies: {
          url: '/ajax/company/name',
          placeholder: '请选择关联企业',
          label: '相关企业',
          prop: 'comps'
        },
        ruleForm2: {
          title: '',
          catalog: '',
          source: '',
          imgUrl: '',
          cnt: '',
          professors: [],
          orgs: [],
          comps: []
        },
        rules2: {
          title: [
            { validator: checkTitle, trigger: 'blur', required: true }
          ],
          source: [
            { validator: checkAuthorSource, trigger: 'blur', required: true }
          ],
          cnt: [
            { validator: checkContent, trigger: 'blur', required: true }
          ],
          imgUrl: []
        }
      }
    },
    created() {
      this.id = this.$route.query.id
      if (this.id) {
        this.$http.get(inquireContentUrl, { id: this.id }, (response) => {
          if (response.success && response.data) {
            const info = response.data
            this.ruleForm2 = {
              catalog: info.catalog || '',
              cnt: info.cnt,
              title: info.title,
              source: info.source,
              imgUrl: info.imgUrl
            }
            if (info.catalog === '1' || info.catalog === '2') {
              this.rules2.imgUrl.push({ message: '请上传封面图片', required: true, trigger: 'blur' })
            } else {
              this.rules2.imgUrl = []
            }
            this.UEflag = true
            if (info.professor) {
              this.ruleForm2.professors = [info.professor]
              request.get(kexiuUrl + '/ajax/professor/baseInfo/' + info.professor, {}, (res) => {
                if (res.success && res.data) {
                  const response = res.data
                  let title = response.title || response.office || ''
                  const job = response.orgName || ''
                  if (title) {
                    if (job) {
                      title = title + '，' + job
                    }
                  } else {
                    if (job) {
                      title = job
                    }
                  }
                  this.$refs.sear1.optionsList = [{ value: response.professor, label: response.name, title: title }]
                  this.$refs.sear1.input = response.professor
                }
              })
            }
            if (info.org) {
              this.ruleForm2.orgs = [info.org]
              request.get(kexiuUrl + '/ajax/org/' + info.org, {}, (res) => {
                if (res.success && res.data) {
                  const response = res.data
                  this.$refs.sear2.optionsList = [{ value: response.id, label: response.name }]
                  this.$refs.sear2.input = response.id
                }
              })
            }
            if (info.comp) {
              this.ruleForm2.comps = [info.comp]
              this.$http.get('/ajax/company/qo', { id: info.comp }, (res) => {
                if (response.success && response.data) {
                  const response = res.data
                  this.$refs.sear3.optionsList = [{ value: response.id, label: response.name }]
                  this.$refs.sear3.input = response.id
                }
              })
            }
            this.upImgsStr = info.imgUrl
            if (this.id) {
              this.modifyTime = parseTime(info.modifyTime).substr(0, 19)
            }
          }
        })
      } else {
        this.UEflag = true
      }
    },
    components: {
      searchTemplate,
      uploadFile,
      UE
    },
    methods: {
      uploadfun(value) {
        this.ruleForm2.imgUrl = value
      },
      institution(value) {
        this.ruleForm2.orgs = [value]
      },
      company(value) {
        this.ruleForm2.comps = [value]
      },
      expert(value) {
        this.ruleForm2.professors = [value]
      },
      change(value) {
        if (!value) {
          this.$refs.ruleForm2.validateField('title')
          return
        }
        if (this.ruleForm2.title) {
          this.$refs.ruleForm2.validateField('title')
        }
        if (value === '1' || value === '2') {
          this.rules2.imgUrl.push({ message: '请上传封面图片', required: true, trigger: 'blur' })
        } else {
          this.rules2.imgUrl = []
        }
        this.ruleForm2.catalog = value
      },
      deleteContent() {
        this.$confirm('该内容是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.$http.get(deleteUrl, { id: this.id }, response => {
            if (response.success) {
              if (response.data) {
                this.$router.push('/draftList')
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
              } else {
                this.$http.get(inquireContentUrl, { id: this.id }, (response) => {
                  if (response.success && response.data) {
                    const info = response.data
                    if (!info.actived) {
                      this.$message({
                        message: '该内容已被删除',
                        type: 'warning'
                      })
                    }
                  }
                })
              }
            }
          })
        }).catch(() => {

        })
      },
      draft() {
        this.draftFlag = false
        this.$refs.ruleForm2.validateField('title')
        this.ruleForm2.cnt = this.$refs.ueBox.getUEContent()
        if (this.ruleForm2.title) {
          if (this.id) {
            this.ruleForm2.id = this.id
          }
          this.$confirm('该内容是否保存草稿箱？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
            this.$http.post((this.id) ? draftUrl : draftFirstUrl, this.ruleForm2, response => {
              this.draftFlag = true
              if (response.success && response.data) {
                const info = response.data
                if (!this.id) {
                  this.id = info
                }
              } else {
                if (this.id) {
                  this.$http.get(inquireContentUrl, { id: this.id }, (response) => {
                    if (response.success && response.data) {
                      const info = response.data
                      if (info.published) {
                        this.$message({
                          message: '该内容草稿已被发布',
                          type: 'warning'
                        })
                      } else {
                        if (info.actived) {
                          this.$message({
                            message: '该内容草稿已被删除',
                            type: 'warning'
                          })
                        }
                      }
                    }
                  })
                }
              }
            })
          }).catch(() => {
          })
        }
      },
      submitForm(formName) {
        this.change()
        this.ruleForm2.cnt = this.$refs.ueBox.getUEContent()
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.id) {
              this.ruleForm2.id = this.id
            }
            this.$confirm('该内容是否发布？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              center: true
            }).then(() => {
              this.$http.post((this.id) ? draftPublishUrl : publishUrl, this.ruleForm2, (response) => {
                if (response.success && response.data) {
                  this.$router.push('publist')
                } else {
                  if (this.id) {
                    this.$http.get(inquireContentUrl, { id: this.id }, (response) => {
                      if (response.success && response.data) {
                        const info = response.data
                        if (info.published) {
                          this.$message({
                            message: '该内容已被发布',
                            type: 'warning'
                          })
                        } else {
                          if (info.actived) {
                            this.$message({
                              message: '该内容已被删除',
                              type: 'warning'
                            })
                          }
                        }
                      }
                    })
                  }
                }
              })
            }).catch(() => {
            })
          } else {
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .formWidth {
    width: 960px
  }

  .selectWidth {
    width: 103px;
  }

  .teimg {
    color: #606266;
    font-size: 12px;
    text-align: center;
    line-height: 10px;
  }

  .tetype {
    color: #909399;
    font-size: 14px;
    text-align: center;
    line-height: 10px
  }

  .editBox .el-form-item__content {
    line-height: 0px;
  }

  .publishButton {
    text-align: center;
  }

  .traftButton {
    text-align: right;
  }

  .avatar-uploader {
    line-height: 1.15;
  }
</style>