<template>
  <view
    v-if="journalData"
    class="journal-item"
    @click.stop="handleClick">
    <view v-if="journalData.createUser" class="user">
      <wk-avatar
        :name="journalData.createUser.realname"
        :avatar="journalData.createUser.img"
        :size="12"
        :preview="false"
        class="avatar" />
      <view class="user-info">
        <view class="username">
          <text class="text">
            {{ journalData.createUser.realname }}
          </text>
        </view>
        <view class="time">
          {{ journalData.createTime }}
        </view>
      </view>

      <view class="right">
        <image
          v-if="showReadMore"
          :src="$static('images/oa/log_record.png')"
          class="read-more"
          @click.stop="handleReadMore" />
        <view class="badge">
          {{ categoryText }}
        </view>
      </view>
    </view>

    <view v-if="sendUserList.length > 0" class="send-user">
      接收人: {{ sendUserList }}
    </view>

    <view class="content">
      <view v-if="journalData.content" class="box">
        <view class="box-title">
          {{ getCategory(journalData.categoryId, 0) }}工作内容：
        </view>
        <view class="box-content">
          <view>{{ journalData.content }}</view>
        </view>
      </view>
      <view v-if="journalData.tomorrow" class="box">
        <view class="box-title">
          {{ getCategory(journalData.categoryId, 1) }}工作内容：
        </view>
        <view class="box-content">
          <view>{{ journalData.tomorrow }}</view>
        </view>
      </view>
      <view v-if="journalData.question" class="box">
        <view class="box-title">
          遇到的问题：
        </view>
        <view class="box-content">
          <view>{{ journalData.question }}</view>
        </view>
      </view>
    </view>

    <view
      v-if="!$isEmpty(journalData.bulletin)"
      class="sale-box">
      <view class="sale-title">
        销售简报
      </view>
      <view class="sale-list">
        <view
          v-for="(saleItem, index) in saleList"
          :key="index"
          class="sale-list-item"
          @click.stop="handleToBulletin(saleItem)">
          <text
            :style="{color: saleItem.color}"
            :class="saleItem.icon"
            class="wk" />
          <text>
            {{ getCategory(journalData.categoryId, 0) }}{{ saleItem.label }}
          </text>
          <text>
            <!-- {{ saleItem.num }} -->
            {{ journalData[saleItem.key] }}
          </text>
        </view>
      </view>
    </view>

    <wk-image-content
      v-if="!$isEmpty(journalData.img)"
      :list="journalData.img" />

    <wk-file-content
      v-if="!$isEmpty(journalData.file) && isDetail"
      :list="journalData.file"
      @click.native.stop />

    <relevance-section
      v-if="showRelevance && isDetail"
      :relevance-data="journalData" />

    <view class="control-btn" @click.stop>
      <view
        :class="{active: isFavourFlag}"
        class="control-btn-item"
        @click.stop="handleToggleFavour">
        <image
          :src="favPicUrl"
          class="icon-pic" />
        <text
          v-if="favourUserList.length > 0"
          class="text">
          {{ favourUserList.length }}
        </text>
      </view>
      <view
        class="control-btn-item"
        @click.stop="handleToComment">
        <image
          :src="$static('images/oa/log_comment.png')"
          class="icon-pic" />
        <text
          v-if="journalData.replyNum > 0"
          class="text">
          {{ journalData.replyNum }}
        </text>
      </view>
    </view>

    <view
      v-if="showFavourContent || showCommentContent"
      :class="{
        'padding-bottom': !showCommentContent
      }"
      class="others">
      <view
        v-if="showFavourContent"
        class="fav-section"
        @click.stop="handleToFavour">
        <image
          :src="$static('images/oa/log_favour.png')"
          class="icon-pic" />
        <view
          v-if="!$isEmpty(favourUserList)"
          class="sec-content">
          <text
            v-for="(user, index) in favourUserList.slice(0, 10)"
            :key="user.userId"
            class="username">
            {{ user.realname }}
            <template v-if="index < favourUserList.slice(0, 10).length - 1">
              ，
            </template>
          </text>
          <text
            v-if="favourUserList.length > 10"
            class="more-text">
            等{{ favourUserList.length }}人点赞
          </text>
        </view>
      </view>

      <comment-list
        v-if="showCommentContent && !$isEmpty(replyDataList)"
        :show-avatar="isDetail"
        :reply-list="replyDataList"
        @choose="handleChooseUser" />

      <view
        v-if="!isDetail && journalData.replyNum > 5"
        class="more-comment">
        查看全部{{ journalData.replyNum }}条评论
        <text class="wk wk-arrow-right" />
      </view>
    </view>

    <template v-if="isDetail">
      <view
        v-if="!journalData.replyNum"
        :class="{
          'border-top': !showFavourContent && !showCommentContent
        }"
        class="empty-reply">
        暂无评论，发表第一条评论吧
      </view>
      <view v-else class="empty-box" />
    </template>
  </view>
</template>

<script>
  import { FavourOrCancel } from '@/api/oa/journal.js'
  import { QueryCommentList } from 'API/oa/comment'

  import RelevanceSection from '@/components/base/relevance-section.vue'
  import CommentList from '@/components/base/comment-list.vue'

  import { calcIcon } from 'UTIL/file'
  import { isArray } from '@/utils/types.js'

  export default {
    name: 'JournalItem',
    components: {
      RelevanceSection,
      CommentList
    },
    props: {
      journalData: {
        type: Object,
        required: true
      },
      isDetail: {
        type: Boolean,
        default: false
      },
      showReadMore: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        saleList: [
          {
            label: '新增客户',
            key: 'customerCount',
            module: 'customer',
            num: 0,
            icon: 'wk-customer',
            color: '#487dff',
          },
          {
            label: '新增商机',
            key: 'businessCount',
            module: 'business',
            num: 0,
            icon: 'wk-business',
            color: '#fb9223',
          },
          {
            label: '新增合同',
            key: 'contractCount',
            module: 'contract',
            num: 0,
            icon: 'wk-contract',
            color: '#fd5b4a',
          },
          {
            label: '新增回款',
            key: 'receivablesMoney',
            module: 'receivables_money',
            num: 0,
            icon: 'wk-receivables',
            color: '#ffb940',
          },
          {
            label: '新增跟进记录',
            key: 'recordCount',
            module: 'record',
            num: 0,
            icon: 'wk-record',
            color: '#19b5f6',
          }
        ],

        replyData: [],
        replyDataList: []
      }
    },
    computed: {
      sendUserList() {
        if (this.$isEmpty(this.journalData.sendUserList)) return ''
        let str = ''
        this.journalData.sendUserList.forEach(item => {
          str = str + item.realname + '、'
        })
        return str.slice(0, -1)
      },

      showRelevance() {
        let arr = ['customerList', 'contactsList', 'businessList', 'contractList'].map(key => {
          return isArray(this.journalData[key]) && this.journalData[key].length > 0
        })
        let length = arr.filter(flag => {
          return !flag
        }).length
        return length !== arr.length
      },
      categoryText() {
        return {
          1: '日报',
          2: '周报',
          3: '月报'
        }[this.journalData.categoryId]
      },

      showFavourContent() {
        return !this.$isEmpty(this.journalData.favourUser)
      },
      showCommentContent() {
        return this.journalData.replyNum > 0
      },

      isFavourFlag() {
        return this.journalData.isFavour
      },
      favourUserList() {
        return this.journalData.favourUser || []
      },
      favPicUrl() {
        if (this.$isEmpty(this.journalData)) return ''
        return this.journalData.isFavour ? this.$static('images/oa/log_favour_primary.png') : this.$static('images/oa/log_favour.png')
      }
    },
    watch: {
      showCommentContent: {
        handler(val) {
          if (val) {
            this.getReplyList()
          }
        },
        deep: true,
        immediate: true
      }
    },
    methods: {
      getReplyList(ignore = false) {
        if (this.journalData.replyNum === 0 && !ignore) return
        QueryCommentList({
          typeId: this.journalData.logId,
          type: 2
        }).then(res => {
          if (this.isDetail) {
            this.replyDataList = res || []
            return
          }
          this.replyData = res || []
          this.replyDataList = []
          // console.log('replyList res: ', res)
          if (this.$isEmpty(res)) return
          const max = 5
          let arr = []
          let i = 0
          let len = 0
          do {
            len++ // 总长度+1
            const child = res[i].childCommentList || []

            if (child.length < max - len) { // 子评论长度小于剩余
              arr.push(res[i])
            } else { // 子评论大于剩余
              arr.push({
              ...res[i],
              childCommentList: child.splice(0, max - len) // 取剩余长度
              })
            }
            len += child.length
            i++
          } while (len < max && i < res.length)
          this.replyDataList = arr
        }).catch(() => {})
      },

      getCategory(categoryId, flag = 0) {
        const map = {
          1: ['今日', '明日'],
          2: ['本周', '下周'],
          3: ['本月', '下月']
        }
        if (!map.hasOwnProperty(categoryId)) {
          categoryId = 1
        }
        return map[categoryId][flag]
      },

      /**
       * 选择回复人
       * @param {Object} user
       */
      handleChooseUser(user, evt) {
        // console.log('user --', user)
        this.$emit('choose', user)
        if (!this.isDetail) {
          this.handleClick(evt)
        }
      },

      /**
       * 切换点赞状态
       */
      handleToggleFavour() {
        FavourOrCancel({
          logId: this.journalData.logId,
          isFavour: !this.journalData.isFavour
        }).then(res => {
          this.$set(this.journalData, 'isFavour', res.isFavour)
          this.$set(this.journalData, 'favourUser', res.favourUser)
          this.$emit('update-data', this.journalData)
          if (this.isDetail) {
            this.$refreshAndToPrev(this, false)
          }
        }).catch(() => {})
      },

      /**
       * 查看销售简报
       * @param {Object} item
       */
      handleToBulletin(item) {
        const query = {
          logId: this.journalData.logId,
          module: item.module,
          title: this.getCategory(this.journalData.categoryId, 0) + item.label
        }

        if (item.module !== 'record') {
          query.module = item.module
          this.$Router.navigateTo({
            url: '/pages_crm/homeReport/report',
            query
          })
        } else {
          this.$Router.navigateTo({
            url: '/pages_crm/homeReport/recordCountList',
            query
          })
        }
      },

      handleReadMore() {
        this.$emit('read-more', this.journalData)
      },

      /**
       * 查看点赞详情
       */
      handleToFavour() {
        getApp().globalData.cacheDataBridge = null
        getApp().globalData.cacheDataBridge = this.journalData.favourUser || []
        this.$Router.navigateTo('/pages_log/favour')
      },

      handleClick(evt) {
        this.$emit('click', evt)
      },

      handleToComment(evt) {
        if (this.isDetail) return
        this.$emit('comment', evt)
      // this.$Router.navigateTo({
      // 	url: '/pages_log/detail',
      // 	query: {
      // 	  id: this.journalData.logId,
      // 		action: 'comment'
      // 	}
      // })
      }
    }
  }
</script>

<style scoped lang="scss">
.journal-item {
  width: 100%;
  padding: 28rpx 32rpx 0;
  background-color: white;

  .user {
    margin-bottom: 20rpx;
    @include left;
    .avatar {
      width: 72rpx;
      height: 72rpx;
      margin-right: 20rpx;
    }
    .user-info {
      .username {
        font-size: 30rpx;
        color: $dark;
        display: flex;
      }
      .time {
        font-size: 24rpx;
        color: $light;
      }
    }

    .right {
      flex: 1;
      @include right;

      .read-more {
        width: 42rpx;
        height: 42rpx;
        margin-right: 30rpx;
      }
      .badge {
        font-size: $wk-font-mini;
        color: #BBBBBB;
        line-height: 1;
        background-color: #EEEEEE;
        border-radius: 8rpx;
        padding: 12rpx 20rpx;
      }
    }
  }

  .send-user {
    font-size: 26rpx;
    color: $light;
    margin-bottom: 10rpx;
  }

  .content {
    font-size: 24rpx;
    .box {
      .box-title {
        color: $light;
      }
      .box-content {
        font-size: 28rpx;
        color: $dark;
        white-space: pre-wrap;
        word-wrap: break-word;
        padding: 10rpx 0;
      }
    }
  }

  .wk-image-content, .wk-file-content {
    margin-bottom: 20rpx;
  }

  .sale-box {
    font-size: 26rpx;
    margin-bottom: 15rpx;
    margin-top: 10rpx;
    .sale-title {
      color: $light;
      margin-bottom: 15rpx;
    }
    .sale-list {
      width: 100%;
      font-size: 24rpx;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .sale-list-item {
        width: 45%;
        height: 50rpx;
        line-height: 50rpx;
        background-color: #EFF5FF;
        border-radius: 8rpx;
        padding: 0 20rpx;
        margin-right: 30rpx;
        margin-bottom: 15rpx;
        .wk {
          font-size: 26rpx;
          margin-right: 10rpx;
        }
      }
    }
  }

  .control-btn {
    width: 100%;
    padding-bottom: 20rpx;
    @include right;
    .control-btn-item {
      color: #666666;
      margin-right: 36rpx;
      .icon-pic {
        width: 38rpx;
        height: 38rpx;
        vertical-align: middle;
        margin-right: 10rpx;
      }
      .text {
        font-size: $wk-font-base;
        color: inherit;
        vertical-align: middle;
      }

      &.active {
        color: $theme-color;
      }
      &:last-child {
        margin-right: 0;
      }
    }
  }

  .others {
    border-top: 1rpx solid $border-color;
    padding: 15rpx 0 0;

    &.padding-bottom {
      padding-bottom: 15rpx;
    }

    .fav-section {
      display: flex;
      align-items: flex-start;
      justify-content: flex-start;
      .icon-pic {
        width: 34rpx;
        height: 34rpx;
        margin: 8rpx 0;
      }
      .sec-content {
        flex: 1;
        overflow: hidden;
        margin-left: 20rpx;
        .username {
          color: $theme-color;
          font-size: $wk-font-base;
        }
        .more-text {
          font-size: $wk-font-base;
        }
      }
    }

    .more-comment {
      font-size: $wk-font-base;
      color: $theme-color;
      margin-left: 50rpx;
      padding-bottom: 15rpx;
      .wk-arrow-right {
        font-size: inherit;
      }
    }
  }

  .empty-reply {
    width: 100%;
    font-size: $wk-font-sm;
    color: $light;
    text-align: center;
    padding: 55rpx 0 70rpx;
    &.border-top {
      border-top: 1rpx solid $border-color;
      padding: 70rpx 0;
    }
  }
  .empty-box {
    width: 100%;
    height: 20rpx;
    background-color: white;
  }
}

.detail-section {
  .bg {
    width: calc(100% + 70rpx);
    height: 15rpx;
    background-color: #F3F3F3;
    margin-left: -35rpx;
  }

  .detail-comment {
    font-size: 28rpx;
    .detail-comment-title{
      padding-top: 30rpx;
    }
  }
}
</style>
