<template>
  <el-card shadow="never" class="aui-card--fill">
    <el-form v-if="pove" :model="dataForm" :rules="dataRule" ref="dataForm" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'" :disabled="pageDisabled">
      <el-form-item label="留言人"  label-width="100px">
        <el-input
            :rows="3"
            v-model="dataForm.boradName"
            style="width:50%">
        </el-input>
      </el-form-item>
      <el-form-item label="留言时间"  label-width="100px">
        <el-input
            :rows="3"
            v-model="dataForm.boradTime"
            style="width:50%">
        </el-input>
      </el-form-item>
      <el-form-item label="所属网格"  label-width="100px">
        <div>{{dataForm.dept}}</div>
      </el-form-item>
      <el-form-item label="留言内容" prop="content" label-width="100px">
        <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入会议内容，2000字以内"
            v-model="dataForm.boradContent"
            maxlength="2000"
            style="width:50%">
        </el-input>
      </el-form-item>
      <el-form-item label="留言图片" v-loading="loading"  label-width="100px">
        <el-upload
            ref="upload"
            :action="uploadUrl"
            :class="{hide:hideUpload}"
            list-type="picture-card"
            :file-list="dataForm.boradPicture"
            :limit=3
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :on-error="handelError"
            :before-upload="beforeAvatarUpload"
            style="width:480px">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <div><font color="gray">1~3张图</font></div>
      </el-form-item>
    </el-form>
    <el-form v-if="replyState" :model="dataForm" :rules="dataRule" ref="dataForm" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'" :disabled="pageDisabled">
      <el-form-item label="回复内容" prop="content" label-width="100px">
        <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入会议内容，2000字以内"
            v-model="dataForm.replyContent"
            maxlength="2000"
            style="width:50%">
        </el-input>
      </el-form-item>
      <el-form-item label="回复图片" v-loading="loading" prop="images" label-width="100px">
        <el-upload
            ref="upload"
            :action="uploadUrl"
            :class="{hide:hideUpload}"
            list-type="picture-card"
            :file-list="dataForm.replyPicture"
            :limit=3
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :on-error="handelError"
            :before-upload="beforeAvatarUpload"
            style="width:480px">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <div><font color="gray">1~3张图</font></div>
      </el-form-item>
      <el-form-item v-if="replyInfoState" label="回复人"  label-width="100px">
        <div>{{dataForm.replyName}}</div>
      </el-form-item>
      <el-form-item v-if="replyInfoState" label="回复时间"  label-width="100px">
        <div>{{dataForm.replyTime}}</div>
      </el-form-item>
    </el-form>

    <el-form>
      <el-form-item style="margin-left:35px;">
        <el-button type="primary" @click="backToUserRelationList">{{"返回"}}</el-button>
        <el-button v-if="!pageDisabled" type="primary" :disabled="isAble" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import debounce from 'lodash/debounce'
import Cookies from 'js-cookie'
export default {
  data () {
    return {
      visible: false,
      pove: false,
      dataForm: {
        id: '',
        userId: '',
        boradName: '',
        dept: '',
        deptId: '',
        boradContent: '',
        images: [],
        replyPicture: [],
        boradPicture: [],
        boradTime: '',
        replyContent: '',
        replyName: '',
        replyTime: '',
        state: '',
        boradId: '',
      },
      isAble: false,
      replyState: true,
      replyInfoState: false,
      meetTypeArr: [],
      dailyTypeArr: [],
      hideUpload: false,
      pageDisabled: false,
      // imgUrlArr: [],
      mapSelectVisible: false,
      uploadUrl: '',
      loading: false,
      dialogImageUrl: '',
      dialogVisible: false,
      options: []
    }
  },
  created: function () {
    this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/uploadImg?token=${Cookies.get('token')}`
  },
  computed: {
    dataRule () {
      return {
        content: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.pageDisabled = this.$route.query.disabled
    this.hideUpload = this.$route.query.disabled
    if (this.$route.query.id !== '' && this.$route.query.id != null) {
      this.dataForm.id = this.$route.query.id
      this.getInfo()
    } else {
      // 随手记下拉框赋值
      this.getInfo()
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/events/borad/details/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        let infoObj =  res.data.state ;
        if (infoObj == '0' &&  this.pageDisabled == true){ //表示是留言 查看详情状态 就显示留言内容
          this.pove = true;
          this.replyState = false
        }else if (infoObj == '0' &&  this.pageDisabled == false){  //表示是留言 回复状态 就显示回复框
          this.pove = false;
          this.replyState = true;
          this.dataForm.boradId = this.$route.query.id;
        }else if (infoObj == '1' &&  this.pageDisabled == true){ //表示留言已经回复 的 查看详情状态 显示全部信息
          this.pove = true;
          this.replyState = true;
          this.replyInfoState  = true;
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http['post']('/events/borad/reply/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
              this.backToUserRelationList();
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false }),

    handleAvatarSuccess (res, file) {
      this.loading = false
      this.isAble = false
      if (res === null || res.data === null || res.data.imgUrl === null) {
        this.$message.error('文件上传失败！')
        this.handleErrorRemove(file)
        return false
      }
      this.dataForm.replyPicture.push({ url: res.data.imgUrl, breviaryUrl: res.data.thumbnail, fileType: 1 })
      this.hideUpload = this.dataForm.replyPicture.length >= 3
    },
    handleErrorRemove (file) {
      // 实现缩略图模板时删除文件
      let fileList = this.$refs.upload.uploadFiles
      for (var i = 0; i < fileList.length; i++) {
        let item = fileList[i]
        if (item.url === file.url) {
          fileList.splice(i, 1)
        }
      }
    },
    handelError () {
      this.loading = false
      this.isAble = false
      this.$message.error('上传文件失败!')
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove (file, fileList) {
      for (var i = 0; i < this.dataForm.replyPicture.length; i++) {
        let item = this.dataForm.replyPicture[i]
        if (item.url === file.url) {
          this.dataForm.replyPicture.splice(i, 1)
        }
      }
      this.hideUpload = this.dataForm.replyPicture.length >= 3
    },
    beforeAvatarUpload (file) {
      if (this.dataForm.replyPicture.length === 3) {
        this.$message.error('最多上传3张图片!')
        return false
      }
      this.loading = true
      this.isAble = true
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      // const isLt1M = file.size / 1024 / 1024 < 1
      // 判断是否符合格式要求
      if (!isJPG && !isPNG) {
        this.$message.error('上传文件必须是jpg、png格式!')
        this.loading = false
        this.isAble = false
        return false
      }
    },
    // 返回按钮点击事件
    backToUserRelationList () {
      this.$emit('MessageBoradReply')
      this.$parent.selectComponent = 'MessageBoradReply'
      this.$router.push({ path: '/events-borad-boradReplyRoute' })
    },
  }
}
</script>

<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
