<template>
  <div>
    <el-dialog
      :title="formTitle"
      :close-on-click-modal="false"
      dialogDrag
      width="1200px"
      @close="close"
      v-model="visible">
      <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
               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 :disabled="method === 'view'" 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 :disabled="method === 'view'" 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 :span="24">
            <el-form-item label="内容" prop="detail"
                          :rules="[
                          {required: true, message:'内容不能为空', trigger:'blur'}
                 ]">
              <WangEditor :disabled="method === 'view'" 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>

		<div v-if="method === 'view'">
			<el-divider v-if="method === 'view'" content-position="left"><i class="el-icon-document"></i>访问日志</el-divider>
			<div style="height: auto">
				<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

				>
					<vxe-table-column field="userName" title="访问人" :edit-render="{}">
						<template #default="scope">
							<el-input :readonly="true" :disbale="method === 'view'" v-model="scope.row.userName" >{{scope.row.userName}}</el-input>
						</template>
					</vxe-table-column>
					<vxe-table-column field="firstTime" title="首次访问时间" :edit-render="{}">
						<template #default="scope">
							<el-input :readonly="true" :disbale="method === 'view'" v-model="scope.row.firstTime" >{{scope.row.firstTime}}</el-input>
						</template>
					</vxe-table-column>
					<vxe-table-column field="lastTime" title="最近访问时间" :edit-render="{}">
						<template #default="scope">
							<el-input :readonly="true" :disbale="method === 'view'" v-model="scope.row.lastTime" >{{scope.row.lastTime}}</el-input>
						</template>
					</vxe-table-column>
					<vxe-table-column field="num" title="访问次数" :edit-render="{}">
						<template #default="scope">
							<el-input :readonly="true" :disbale="method === 'view'" v-model="scope.row.num" >{{scope.row.num}}</el-input>
						</template>
					</vxe-table-column>
				</vxe-table>
				<div class="tableLine"><span class="midText">共有{{inputForm.visitNum}}人访问 <el-link style="color: red" type="text" size="mini" v-show="inputForm.visitNum>3&&lookList" @click="findLogList(inputForm.visits.length)">查看全部</el-link></span></div>
				<n/>
				<el-divider></el-divider>
			</div>
		</div>

		<div v-if="method === 'view'">
			<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" v-show="index<initLength">
					<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-divider></el-divider>
				<div class="tableLine"><span class="midText"><span v-show="inputForm.comments.length>3&&lookMore">还有{{inputForm.comments.length-3}}条评论</span> <el-link style="color: red" type="text" size="mini" v-show="inputForm.comments.length>3&&lookMore" @click="findComment(inputForm.comments.length)"> 查看全部</el-link></span></div>
			</el-form>

		</div>

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

<script>
  import KnowledgeShareInfoService from '@/api/knowledgeShare/KnowledgeShareInfoService'
  import KnowledgeShareTypeService from '@/api/knowledgeShare/KnowledgeShareTypeService'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import UserService from '@/api/sys/UserService'
  import KnowledgeShareTypePageForm from './KnowledgeShareTypePageForm'
  import WangEditor from '@/components/editor/WangEditor'
  export default {
    data () {
      return {
		  lookMore:true,
		  lookList:true,
		  initLength:3,
        formTitle: '',
        method: '',
        visible: false,
        loading: false,
        isAdmin: false,
        create: '',
        typeList: [],
        inputForm: {
          id: '',
          typeId: '',
          title: '',
          detail: '',
          visits: [],
          comments: [],
          files: [],
          content: '',
          editorFilesDTOList: [],
			pageSize: 3,
			visitNum:''
        }
      }
    },
    knowledgeShareInfoService: null,
    created () {
      this.knowledgeShareInfoService = new KnowledgeShareInfoService()
      this.knowledgeShareTypeService = new KnowledgeShareTypeService()
      this.knowledgeShareTypeService.list().then((data) => {
        this.typeList = data.records
      })
    },
	  computed :{
		  bus: {
			  get () {
				  // this.$refs.uploadComponent.setDividerName('附件')
				  return this.inputForm.id
			  },
			  set (val) {
				  this.inputForm.id = val
			  }
		  },
	  },
	  watch: {
		  'keyWatch': {
			  handler (newVal) {
				  if (this.bus) {
					  if (this.commonJS.isNotEmpty(this.bus)) {
						  this.init('', this.bus)
					  }
				  } else {
					  this.$nextTick(() => {
						  this.$refs.inputForm.resetFields()
					  })
				  }
			  }
		  },
		  // 'loading': {
			//   handler (newVal) {
			// 	  this.$emit('changeLoading', newVal)
			// 	  this.$refs.uploadComponent.changeLoading(newVal)
			//   }
		  // }
	  },
    components: {
      UpLoadComponent,
      KnowledgeShareTypePageForm,
      WangEditor
    },
    methods: {
		getKeyWatch (keyWatch) {
			this.keyWatch = keyWatch
		},
      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: [],
			pageSize: 3,
        }
        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 = this.$store.state.user.id
            this.$refs.inputForm.resetFields()
            this.$refs.uploadComponent.clearUpload()
            this.knowledgeShareInfoService.findById(this.inputForm.id, method,this.inputForm.pageSize).then((data) => {
            	console.log('data',data)
				this.inputForm.visitNum=data.visitNum
              // 富文本处理
              if (method === 'view') {
                this.$refs.contentEditor.disable()
              } else {
			    this.$refs.contentEditor.enable()
			  }
              this.inputForm = this.recover(this.inputForm, data)
				if (this.commonJS.isEmpty(this.inputForm.files)) {
					this.inputForm.files = []
				}

				// this.$refs.uploadComponent.newUpload(this.method, this.inputForm.files, 'knowledgeShare',null,null,null,null,false)
              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.$refs.uploadComponent.newUpload(this.method, this.inputForm.files, 'knowledgeShare')
				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')
	    this.lookMore=true,
	    this.lookList=true,
	    this.initLength=3
      },
      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.knowledgeShareInfoService.getComments(this.inputForm.id).then((da)=>{
				this.inputForm.comments = da.comments
				this.$message.success(data)
				this.inputForm.content = ""
				this.loading = false
			})

        })
      },
      cleanComment () {
        this.inputForm.content = ''
      },
      delComment (id) {
        this.knowledgeShareInfoService.delComment(id)
        this.init('view', this.inputForm.id)
      },
      is () {
        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)
        })
      },
		findComment(leg){
			this.lookMore=false
			this.initLength=leg
		},
		findLogList(){
			this.loading = true
			this.inputForm.pageSize=999999999
			console.log('method',this.method)
			this.knowledgeShareInfoService.findById(this.inputForm.id, this.method,this.inputForm.pageSize).then((data) => {
				this.$refs.uploadComponent.clearUpload()
				console.log('data',data)
				this.inputForm.visitNum=data.visitNum
				// 富文本处理
				if (this.method === 'view') {
					this.$refs.contentEditor.disable()
				} else {
					this.$refs.contentEditor.enable()
				}
				this.inputForm = this.recover(this.inputForm, data)
				if (this.commonJS.isEmpty(this.inputForm.files)) {
					this.inputForm.files = []
				}
				this.$refs.uploadComponent.newUpload('view', this.inputForm.files, 'knowledgeShare')
				this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
				this.inputForm.comments = JSON.parse(JSON.stringify(this.inputForm.comments))
				this.loading = false
				this.lookList=false
			})
		}
    }
  }
</script>

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

</style>
