<template>
  <div>
    <el-dialog
      :title="formTitle"
      :close-on-click-modal="false"
      v-dialogDrag
      width="1200px"
      @close="close"
      :visible.sync="visible">
      <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''" :disabled="method === 'view'"
               label-width="90px" @submit.native.prevent>
        <el-row  :gutter="15">

          <el-col :span="24">
            <el-form-item label="主题" prop="title"
                          :rules="[
                          {required: true, message:'主题不能为空', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.title" placeholder="请填写主题"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="类型" prop="typeId"
                          :rules="[
                          {required: true, message:'分享类型不能为空', trigger:'blur'}
                 ]">
              <el-select v-model="inputForm.typeId" placeholder="请选择" style="width:100%;">
                <el-option
                  v-for="item in typeList"
                  :value="item.id"
                  :label="item.klgsType"
                  :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col>
            <el-form-item label="内容" prop="detail"
                          :rules="[
                          {required: true, message:'内容不能为空', trigger:'blur'}
                 ]">
              <WangEditor ref="contentEditor" v-model="inputForm.detail"
                          @getUrl="(url, lsUrl) => {
                        inputForm.editorFilesDTOList.push({temporaryUrl: lsUrl, url: url});
                        }"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 附件 -->
        <UpLoadComponent ref="uploadComponent"></UpLoadComponent>

        <el-divider v-if="method === 'view'" content-position="left"><i class="el-icon-document"></i>访问日志</el-divider>
        <el-row :gutter="15" >
          <vxe-table
            border
            show-overflow
            v-if="method === 'view'"
            ref="detailTable"
            class="vxe-table-element"
            :data="inputForm.visits"
            @cell-click=""
            @edit-closed=""
            highlight-current-row
            :edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true}"
          >
            <vxe-table-column field="userId" title="访问人" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input :disbale="method === 'view'" v-model="scope.row.userId" ></el-input>
              </template>
            </vxe-table-column>
            <vxe-table-column field="firstTime" title="首次访问时间" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input :disbale="method === 'view'" v-model="scope.row.firstTime" ></el-input>
              </template>
            </vxe-table-column>
            <vxe-table-column field="lastTime" title="最近访问时间" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input :disbale="method === 'view'" v-model="scope.row.lastTime" ></el-input>
              </template>
            </vxe-table-column>
            <vxe-table-column field="num" title="访问次数" :edit-render="{}">
              <template v-slot:edit="scope">
                <el-input v-model="scope.row.num" ></el-input>
              </template>
            </vxe-table-column>
          </vxe-table>
        </el-row>

        <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''" :disabled="false" @submit.native.prevent>
        <el-divider v-if="method === 'view'" content-position="left"><i class="el-icon-document"></i>发表评论</el-divider>
          <el-row>
            <el-col>
              <el-form-item v-if="method === 'view'" prop="content">
                <el-input v-model="inputForm.content"
                          type="textarea"
                          :rows="5"
                          :disabled="method !== 'view'"
                          maxlength="500"
                          placeholder="请输入评论信息"
                          show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
            <el-button v-if="method === 'view'" style="float: right" type="primary" size="mini" @click="pushComment()" plain>
              发表
            </el-button>
            <el-button v-if="method === 'view'" style="float: right; margin-right: 20px" type="primary" size="mini" @click="cleanComment()" plain>
              清空
            </el-button>
          </el-row>

          <el-divider v-if="method === 'view'" content-position="left"><i class="el-icon-document"></i>全部评论({{inputForm.comments.length}}条)</el-divider>
          <div v-if="method === 'view'" v-for="(item, index) in inputForm.comments">
            <el-divider></el-divider>
            <div class="font_div" style="width: 100%; height:30px;"><span>{{item.userId}}</span></div>
            <div style="margin-left: 20px; height:45px;"><span>{{item.content}}</span></div>
            <div style="width: 100%; height:30px;">
              <span>{{item.deff}}</span>
              <a v-if="create === item.createBy || isAdmin" style="float: right" type="text" size="mini" @click="delComment(item.id)">删除</a>
            </div>
          </div>

        </el-form>

        <KnowledgeShareTypePageForm ref="knowledgeShareTypePageForm" @getProgram="getProgram"></KnowledgeShareTypePageForm>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="close()" icon="el-icon-circle-close">关闭</el-button>
      <el-button size="small" type="primary" v-if="method != 'view'" @click="doSubmit()" icon="el-icon-circle-check" v-noMoreClick>确定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  import KnowledgeShareInfoService from '@/api/sys/KnowledgeShareInfoService'
  import KnowledgeShareTypeService from '@/api/sys/KnowledgeShareTypeService'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import UserService from '@/api/sys/UserService'
  import KnowledgeShareTypePageForm from '@/views/modules/finance/invoice/KnowledgeShareTypePageForm'
  import WangEditor from '@/components/editor/WangEditor'
  export default {
    data () {
      return {
        formTitle: '',
        method: '',
        visible: false,
        loading: false,
        isAdmin: false,
        create: '',
        typeList: [],
        inputForm: {
          id: '',
          typeId: '',
          title: '',
          detail: '',
          visits: [],
          comments: [],
          files: [],
          content: '',
          editorFilesDTOList: []
        }
      }
    },
    knowledgeShareInfoService: null,
    userService: null,
    created () {
      this.knowledgeShareInfoService = new KnowledgeShareInfoService()
      this.knowledgeShareTypeService = new KnowledgeShareTypeService()
      this.userService = new UserService()
      this.knowledgeShareTypeService.list().then(({data}) => {
        this.typeList = data.records
      })
    },
    components: {
      UpLoadComponent,
      KnowledgeShareTypePageForm,
      WangEditor
    },
    methods: {
      init (method, id) {
        this.knowledgeShareTypeService.list().then(({data}) => {
          this.typeList = data.records
        })
        this.method = method
        this.inputForm = {
          id: '',
          typeId: '',
          typeName: '',
          title: '',
          detail: '',
          visits: [],
          comments: [],
          files: [],
          content: '',
          editorFilesDTOList: []
        }
        if (method === 'add') {
          this.formTitle = `新建知识分享`
        } else if (method === 'edit') {
          this.inputForm.id = id
          this.formTitle = '修改知识分享'
        } else if (method === 'view') {
          this.inputForm.id = id
          this.formTitle = '查看知识分享'
        }
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.uploadComponent.setDividerName('附件')
          if (method === 'add') {
            this.$refs.contentEditor.enable()
          }
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            // 富文本处理
            this.$refs.contentEditor.clear()
            this.is()
            this.create = JSON.parse(localStorage.getItem('user')).id
            this.$refs.inputForm.resetFields()
            this.$refs.uploadComponent.clearUpload()
            this.knowledgeShareInfoService.findById(this.inputForm.id, method).then(({data}) => {
              // 富文本处理
              if (method === 'view') {
                this.$refs.contentEditor.disable()
              } else {
                this.$refs.contentEditor.enable()
              }
              this.inputForm = this.recover(this.inputForm, data)
              this.$refs.uploadComponent.newUpload(method, this.inputForm.files, 'knowledgeShare')
              this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
              this.inputForm.comments = JSON.parse(JSON.stringify(this.inputForm.comments))
              // 富文本处理
              if (this.commonJS.isNotEmpty(this.inputForm.detail)) {
                this.$refs.contentEditor.init(this.inputForm.detail)
              }
              this.loading = false
            })
          }
        })
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            if (this.$refs.uploadComponent.checkProgress()) {
              this.loading = false
              return
            }
            if (this.commonJS.isEmpty(this.inputForm.files)) {
              this.inputForm.files = []
            }
            this.getEditorFilesDTOList()
            this.inputForm.files = this.$refs.uploadComponent.getDataList()
            this.knowledgeShareInfoService.save(this.inputForm).then(({data}) => {
              this.close()
              this.$message.success(data)
              this.loading = false
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      close () {
        this.inputForm = {
          id: '',
          typeId: '',
          typeName: '',
          title: '',
          detail: '',
          visits: [],
          comments: [],
          files: [],
          content: '',
          editorFilesDTOList: []
        }
        this.$refs.inputForm.resetFields()
        this.$refs.uploadComponent.clearUpload()
        // 富文本处理
        this.$refs.contentEditor.clear()
        this.visible = false
        this.$emit('refreshDataList')
      },
      pushComment () {
        if (this.commonJS.isEmpty(this.inputForm.content)) {
          this.$message.error('请输入评论内容')
          return
        }
        this.commentForm = {
          detailId: this.inputForm.id,
          content: this.inputForm.content
        }
        this.loading = true
        this.knowledgeShareInfoService.addComment(this.commentForm).then(({data}) => {
          this.init('view', this.inputForm.id)
          this.$message.success(data)
          this.loading = false
        })
      },
      cleanComment () {
        this.inputForm.content = ''
      },
      delComment (id) {
        this.knowledgeShareInfoService.delComment(id)
        this.init('view', this.inputForm.id)
      },
      is () {
        this.userService.is().then(({data}) => {
          this.isAdmin = data
        })
      },
      // 知识分享类型弹窗选择
      openProgramPageForm () {
        this.$refs.knowledgeShareTypePageForm.init()
      },
      getProgram (rows) {
        this.inputForm.typeId = rows[0].id
        this.inputForm.typeName = rows[0].klgsType
        this.$forceUpdate()
      },
      getEditorFilesDTOList () {
        let a = []
        if (this.commonJS.isNotEmpty(this.inputForm.editorFilesDTOList)) {
          this.inputForm.detail = this.inputForm.detail.replace(/&amp;/g, '&')
          this.inputForm.editorFilesDTOList.forEach((item) => {
            if (this.inputForm.detail.includes(item.temporaryUrl)) {
              a.push(item)
            }
          })
        }
        this.inputForm.editorFilesDTOList = []
        a.forEach((item) => {
          this.inputForm.editorFilesDTOList.push(item)
        })
      }
    }
  }
</script>

<style>
  .font_div {
    font-weight: bold; /*加粗*/
  }

</style>
