<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar
        :command-list="commandList"
        :refresh-prev="refreshPrevPage"
        title="日志详情"
        @command="handleCommand" />

      <view class="container">
        <journal-item
          :journal-data="detailData"
          show-read-more
          is-detail
          @read-more="handleReadMore"
          @choose="handleChoose" />

        <add-comment
          ref="comment"
          v-model="content"
          :replay="replayInfo"
          :immediate-focus="immediateFocus"
          @change-user="changeUser"
          @submit="submit" />
      </view>
    </view>

    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog
        :content="dialogMsg"
        :duration="2000"
        type="warning"
        @confirm="deleteLog" />
    </uni-popup>
  </view>
</template>

<script>
  import { QueryById, DeleteById } from 'API/oa/journal'
  import { SetComment } from 'API/oa/comment'
  import JournalItem from './component/journalItem.vue'
  import AddComment from '@/components/base/add-comment.vue'

  export default {
    name: 'LogDetail',
    components: {
      JournalItem,
      AddComment
    },
    data() {
      return {
        id: null,
        detailData: {},
        commandList: [],
        content: '',
        replayInfo: null,

        dialogMsg: '',
        immediateFocus: false,

        refreshPage: false,
        refreshPrevPage: false
      }
    },
    onLoad(options) {
      this.id = options.id || null
      // this.immediateFocus = Boolean(options.action)
      this.getDetail()
    },
    onShow() {
      if (this.refreshPage) {
        this.refreshPage = false
        this.refreshPrevPage = true
        this.getDetail()
      }
    },
    onBackPress(evt) {
      if (evt.from === 'backbutton' && this.refreshPrevPage) {
        this.$refreshAndToPrev(this)
        return true // 返回值为 true 时，表示不执行默认的返回
      }
      return false
    },
    methods: {
      getDetail() {
        this.commandList = []
        QueryById({logId: this.id}).then(response => {
          this.detailData = response || {}
          const permission = response.permission
          if (permission.isUpdate === 1) {
            this.commandList.push({
              label: '编辑',
              value: 'edit',
              icon: 'wk-edit-pen',
              noCheck: true
            })
          }
          if (permission.isDelete === 1) {
            this.commandList.push({
              label: '删除',
              value: 'delete',
              icon: 'wk-bin',
              noCheck: true
            })
          }
        }).catch(() => {})
      },

      /**
       * 更多选项操作
       */
      handleCommand(command) {
        if (command.value === 'edit') {
          this.$Router.navigateTo({
            url: '/pages_log/add',
            query: {
              id: this.id,
              type: this.detailData.categoryId
            }
          })
        } else if (command.value === 'delete') {
          this.dialogMsg = '您确定要删除这条日志吗？'
          this.$refs.popup.open()
        }
      },

      deleteLog() {
        DeleteById({logId: this.id}).then(response => {
          this.$toast('删除成功')
          this.$refreshAndToPrev(this)
        }).catch()
      },

      /**
       * 选择回复人
       */
      handleChoose(user) {
        console.log('selected: ', user)
        if (this.replayInfo) {
          let str = `回复@${this.replayInfo.user.realname} `
          if (this.content.startsWith(str)) {
            this.content = this.content.replace(str, `回复@${user.user.realname} `)
          } else {
            this.content = `回复@${user.user.realname} ` + this.content
          }
        } else {
          this.content = `回复@${user.user.realname} ` + this.content
        }
        this.replayInfo = user
        this.$refs.comment.focus()
      },

      changeUser(data) {
        this.replayInfo = data
      },

      /**
       * 查看以往日志
       */
      handleReadMore(data) {
        this.$Router.navigateTo({
          url: '/pages_log/list',
          query: {
            userId: data.createUserId,
            title: data.realname + '的日志'
          }
        })
      },

      /**
       * 提交回复
       */
      submit() {
        let params = {
          type: 2,
          typeId: this.id,
          content: this.content
        }
        if (this.replayInfo) {
          params.pid = this.replayInfo.userId; // 被回复人的id
          params.mainId = this.replayInfo.mainId != 0 ? this.replayInfo.mainId : this.replayInfo.commentId; // 回复主id

          let str = `回复@${this.replayInfo.user.realname} `
          if (params.content.startsWith(str)) {
            params.content = params.content.replace(str, '')
          }
        }
        if (this.$isEmpty(params.content)) {
          this.$toast('回复内容不能为空')
          return
        }
        console.log('save: ', params)
        SetComment(params).then(() => {
          this.$toast('回复成功')
          this.content = ''
          this.replayInfo = null
          this.showEmoji = false
          this.$refreshAndToPrev(this, false)
          this.getDetail()
        }).catch()
      }
    }
  }
</script>

<style scoped lang="scss">
	.main-container {
		display: flex;
		flex-direction: column;
		overflow: hidden;
		padding-bottom: 110rpx;

		.container {
			flex: 1;
			overflow: auto;
		}
	}
</style>
