<template>
  <el-dialog :visible.sync="visible"
             title="查看"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             @close="visible= false">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <el-form-item label="所属机构:">
        <el-form-item>
          {{dataForm.allDeptNames}}
      </el-form-item>
      </el-form-item>
      <el-form-item label="类别"
                    prop="newsCateroryId">
        <el-form-item>
          {{dataForm.newsProperty}}
      </el-form-item>
      </el-form-item>
      <el-form-item label="新闻标题"
                    prop="newsTitle">
        <el-form-item>
          {{dataForm.newsTitle}}
        </el-form-item>
      </el-form-item>
      <el-form-item prop="newsContent"
                    label="正文编辑">
        <!-- 富文本编辑器, 容器 -->
        <!-- <div id="J_quillEditor"></div> -->
        <!-- 自定义上传图片功能 (使用element upload组件) -->
        <!-- <el-upload :action="uploadUrl"
                   :show-file-list="false"
                   :before-upload="uploadBeforeUploadHandle"
                   :on-success="uploadSuccessHandle"
                   style="display: none;">
          <el-button ref="uploadBtn"
                     type="primary"
                     size="small">{{ $t('upload.button') }}</el-button>
        </el-upload> -->
        <tinymce-editor v-model="dataForm.newsContent"></tinymce-editor>
      </el-form-item>
      <el-form-item label="新闻首图"
                    v-loading="loading"
                    prop="newsImageUrl">
        <el-upload class="avatar-uploader"
                    disabled="true"
                   :action="uploadUrl"
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.newsImageUrl"
               :src="dataForm.newsImageUrl"
               class="avatar">
          <i v-else
             class="el-icon-plus avatar-uploader-icon"></i>
          <div slot="tip"
               class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="显示时长"
                    prop="newsReleaseStartTime">
        <el-date-picker @change='setRegistTime'
                        v-model="time"
                        readonly="true"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie'
import debounce from 'lodash/debounce'
import mixinViewModule from '@/mixins/view-module'
import AddOrUpdate from './news-add-or-update'
import TinymceEditor from '@/components/tinymce-editor'
export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/news/news/page',
        getDataListIsPage: true,
        deleteURL: '/news/news',
        deleteIsBatch: true
      },
      dataForm: {
        id: '',
        streetId: null,
        street: null,
        communityId: null,
        community: null,
        gridId: null,
        grid: null,
        newsCateroryId: '',
        newsProperty: '',
        newsTitle: '',
        newsReleaseStartTime: '',
        newsReleaseEndTime: '',
        newsContent: '',
        newsImageUrl: '',
        allDeptIdsShow: []
      },
      time: [],
      streetList: [],
      communityList: [],
      gridList: [],
      options: [],
      categorys: [],
      loading: false,
      uploadUrl: '',
      // 富文本end
      fileList: [],
      visible: false
    }
  },
  created () {
    this.$http
      .get(`/sys/user/deptOptions/getByLoginUser`)
      .then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.options = res.data.options
      })
      .catch(() => { })
    this.getDeptInfoList('street', localStorage.getItem('street') === null ? '1169154711480528897' : localStorage.getItem('street'))
    this.getListCategory()
    this.visible = true
    this.$nextTick(() => {
      this.dataForm.communityId = this.dataForm.streetId = this.dataForm.gridId = null
      // 富文本
      this.hideUpload = false
      this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get('token')}`
    })
  },
  computed: {
    dataRule () {
      return {
        streetId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsTitle: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsReleaseStartTime: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsImageUrl: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsCateroryId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        newsContent: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/news/news/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = { ...this.dataForm, ...res.data }
        this.resetRegistTime()
        if (this.dataForm.streetId) {
          if (this.dataForm.communityId === 0) {
            this.dataForm.communityId = this.dataForm.gridId = null
          }
          this.getDeptInfoList('community', this.dataForm.streetId)
        }
        if (this.dataForm.communityId) {
          if (this.dataForm.gridId === 0) {
            this.dataForm.gridId = null
          }
          this.getDeptInfoList('grid', this.dataForm.communityId)
        }
      }).catch(() => { })
    },
    // 获取部门列表
    getDeptInfoList (dataReceiver, faDeptId) {
      if (!faDeptId) {
        return
      }
      this.$http.get(`/sys/dept/sublist/` + faDeptId).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (dataReceiver === 'street') {
          let all = [{ id: '1', name: '全部' }]
          this.streetList = all.concat(res.data)
        } else if (dataReceiver === 'community') {
          this.communityList = res.data
        } else if (dataReceiver === 'grid') {
          this.gridList = res.data
        }
      }).catch(() => { })
    },
    changeStreet (event) {
      let choosenItem = this.streetList.filter(item => item.id === this.dataForm.streetId)[0]
      this.dataForm.street = choosenItem.name
      this.dataForm.communityId = this.dataForm.gridId = this.dataForm.community = this.dataForm.grid = null
      this.communityList = this.gridList = []
      this.getDeptInfoList('community', event)
    },
    changeCommunity (event) {
      let choosenItem = this.communityList.filter(item => item.id === this.dataForm.communityId)[0]
      this.dataForm.community = choosenItem.name
      this.dataForm.gridId = this.dataForm.grid = null
      this.gridList = []
      this.getDeptInfoList('grid', event)
    },
    changeGrid (event) {
      let choosenItem = this.gridList.filter(item => item.id === this.dataForm.gridId)[0]
      this.dataForm.grid = choosenItem.name
    },
    changeCaterory () {
      // 给新闻类别变量赋值
      let choosenItem = this.categorys.filter(item => item.id === this.dataForm.newsCateroryId)[0]
      this.dataForm.newsProperty = choosenItem.name
    },
    getListCategory () {
      this.$http.get(`/news/newscategory/category`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.categorys = res.data
      }).catch(() => { })
    },
    // 上传图片
    handleAvatarSuccess (res, file) {
      this.loading = false
      this.dataForm.newsImageUrl = res.data.url
    },
    beforeAvatarUpload (file) {
      this.loading = true
    },
    setRegistTime () {
      this.dataForm.newsReleaseStartTime = this.time[0]
      this.dataForm.newsReleaseEndTime = this.time[1]
    },
    resetRegistTime () {
      this.time = [this.dataForm.newsReleaseStartTime.substr(0, 10), this.dataForm.newsReleaseEndTime.substr(0, 10)]
    },
    // 上传图片end
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      /*if ((this.dataForm.newsContent).length > 10000) {
        return this.$message.error('您输入的的内容已超过字数不能提交')
      }*/
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http['put']('/news/news/', 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.dataForm = {}
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  },
  components: {
    AddOrUpdate,
    TinymceEditor
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
