<template>
  <el-dialog :visible.sync="visible"
             title="查看"
             :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
      <el-form-item label="所属机构"
                    prop="allDeptIdsShow">
        <el-form-item>
          {{dataForm.allDeptNames}}
      </el-form-item>
      </el-form-item>
      <el-form-item label="通知标题"
                    prop="noticeTitle">
        <el-form-item>
          {{dataForm.noticeTitle}}
      </el-form-item>
      </el-form-item>
      <el-form-item prop="noticeContent"
                    label="通知内容">
        <el-row style="height: 550px;">
          <!-- 富文本编辑器, 容器 -->
          <div id="J_quillEditor"
               style="height: 500px;"></div>
        </el-row>
        <!-- 自定义上传图片功能 (使用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>
      </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 'quill/dist/quill.snow.css'
import Quill from 'quill'
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        id: '',
        streetId: null,
        street: null,
        communityId: null,
        community: null,
        gridId: null,
        grid: null,
        noticeTitle: '',
        noticeContent: '',
        allDeptIdsShow: []
      },
      value: '',
      // 富文本
      quillEditor: null,
      quillEditorToolbarOptions: [
        ['bold', 'italic', 'underline', 'strike'],
        ['image'],
        [{ 'header': 1 }, { 'header': 2 }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'script': 'sub' }, { 'script': 'super' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        ['clean']
      ],
      uploadUrl: '',
      // 富文本end
      streetList: [],
      communityList: [],
      gridList: [],
      options: []
    }
  },
  computed: {
    dataRule () {
      return {
        streetId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        allDeptIdsShow: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        noticeTitle: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        noticeContent: [
          { required: true, message: this.$t(' ') }
        ]
      }
    }
  },
  created () {
    this.$http
      .get(`/sys/user/deptOptions/getAllByLoginUser`)
      .then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.options = res.data.options
      })
      .catch(() => { })
    // 1169154711480528897 为市北区部门ID
    this.getDeptInfoList('street', localStorage.getItem('street') === null ? '1169154711480528897' : localStorage.getItem('street'))
  },
  methods: {
    // 富文本编辑器
    quillEditorHandle () {
      this.quillEditor = new Quill('#J_quillEditor', {
        modules: {
          toolbar: this.quillEditorToolbarOptions
        },
        readOnly: true,
        theme: 'snow'
      })
      // // 自定义上传图片功能 (使用element upload组件)
      this.quillEditor.getModule('toolbar').addHandler('image', () => {
        this.$refs.uploadBtn.$el.click()
      })
      // 监听内容变化，动态赋值
      this.quillEditor.on('text-change', () => {
        this.dataForm.noticeContent = this.quillEditor.root.innerHTML
        if ((this.dataForm.noticeContent).length > 10000) {
          return this.$message.error('您输入的的内容已超过字数不能提交')
        }
      })
    },
    // 上传图片之前 (富文本)
    uploadBeforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
        return false
      }
    },
    // 上传图片成功 (富文本)
    uploadSuccessHandle (res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', res.data.url)
    },
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.dataForm.communityId = this.dataForm.streetId = this.dataForm.gridId = null
        this.communityList = this.gridList = []
        // 富文本
        this.hideUpload = false
        this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/oss/file/upload?token=${Cookies.get('token')}`
        if (this.quillEditor) {
          this.quillEditor.deleteText(0, this.quillEditor.getLength())
        } else {
          this.quillEditorHandle()
        }
        // 富文本end
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        } else {
          this.dataForm = {}
        }
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/news/notice/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = { ...this.dataForm, ...res.data }
        this.quillEditor.root.innerHTML = res.data.noticeContent
        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(() => { })
    },
    removeHTMLTag (str) {
      str = str.replace('<p><br></p>', '')
      return str
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      console.log(this.dataForm.noticeContent)
      if (this.dataForm.noticeContent != null && this.dataForm.noticeContent !== undefined) {
        this.dataForm.noticeContent = this.removeHTMLTag(this.dataForm.noticeContent)
        if ((this.dataForm.noticeContent).length > 10000) {
          return this.$message.error('您输入的的内容已超过字数不能提交')
        } else if (this.dataForm.noticeContent.length === 0) {
          return this.$message.error('通知内容不能空')
        }
      } else {
        return this.$message.error('通知内容不能为空')
      }
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/news/notice', 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')
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    // 获取部门列表
    getDeptInfoList (dataReceiver, faDeptId) {
      this.$http.get(`/sys/dept/sublist/` + faDeptId).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (dataReceiver === 'street') {
          this.streetList = res.data
        } else if (dataReceiver === 'community') {
          this.communityList = res.data
        } else if (dataReceiver === 'grid') {
          this.gridList = res.data
        }
      }).catch(() => { })
    },
    changeStreet () {
      // 给街道变量赋值
      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', this.dataForm.streetId)
    },
    changeCommunity () {
      // 给社区变量赋值
      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', this.dataForm.communityId)
    },
    changeGrid (item) {
      console.log(item)
      // 给网格变量赋值
      // let choosenItem = this.gridList.filter(item => item.id === this.dataForm.gridId)[0]
      // this.dataForm.grid = choosenItem.name
      // this.dataForm = Object.assign(this.dataForm, { gridId: item })
      console.log(this.dataForm)
    }

  }
}
</script>
