<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view v-if="!refreshPage" class="main-container">
      <wk-nav-bar title="日志" />

      <view class="filter-group">
        <wk-base-filter
          ref="wkBaseFilter"
          :tabs="taskOptions"
          @filter="handleFilter" />
      </view>

      <wk-scroll-view
        :status="listStatus"
        class="list-scroll"
        @refresh="getList({}, true)"
        @loadmore="getList()">
        <view
          v-for="(item, index) in listData"
          :key="index"
          class="journal-item-wrapper">
          <journal-item
            :journal-data="item"
            show-read-more
            @comment="handleToCommand(index)"
            @read-more="handleReadMore"
            @update-data="data => handleUpdate(data, index)"
            @click="handleToDetail(item)" />
        </view>
      </wk-scroll-view>

      <wk-drag-button
        @click="handleAdd">
        <view class="wk-drag-btn">
          <text class="wk wk-plus icon" />
        </view>
      </wk-drag-button>

      <uni-popup
        ref="popup"
        radius="10rpx 10rpx 0 0"
        type="actionsheet">
        <wk-action-sheet
          :list="logTypeOptions"
          label="label"
          value="value"
          @select="handleCommand" />
      </uni-popup>

      <uni-popup
        ref="commentPopup"
        radius="20rpx 20rpx 0 0"
        type="bottom"
        @click.stop>
        <comment-popup
          v-if="activeItem && activeCommandData"
          :journal-data="activeItem"
          :reply-data="activeCommandData"
          @update="handleUpdateComment"
          @close="handleCloseCommentPopup" />
      </uni-popup>
    </view>
  </view>
</template>

<script>
  import { QueryList } from 'API/oa/journal'
  import { QueryCommentList } from 'API/oa/comment'

  import CommentPopup from './component/commentPopup.vue'
  import JournalItem from './component/journalItem.vue'
  import mainListMixins from '@/mixins/mainList.js'

  export default {
    name: 'JournalIndex',
    components: {
      JournalItem,
      CommentPopup
    },
    mixins: [mainListMixins],
    data() {
      return {
        GetListFn: QueryList,
        filterData: {
          by: 1,
          type: 'recent30'
        },
        taskOptions: [
          {
            label: '类型',
            field: 'by',
            value: 1,
            valueData: 1,
            options: [
              {label: '全部', value: '__delete__'},
              {label: '我发出的', value: 1},
              {label: '我收到的', value: 2}
            ]
          },
          // {
          //   label: '成员',
          //   field: 'userAndDept',
          // 	value: 0,
          // 	valueData: 0,
          //   options: [
          //     {label: '全部成员', value: 0 },
          //     {label: '员工与部门', value: 1, showMoreIcon: true },
          //   ]
          // },
          {
            label: '时间',
            field: 'type',
            value: 'recent30',
            valueData: 4,
            options: [
              {label: '今天', value: 'today'},
              {label: '昨天', value: 'yesterday'},
              {label: '本周', value: 'week'},
              {label: '上周', value: 'lastWeek'},
              {label: '最近30天', value: 'recent30'},
              {label: '最近60天', value: 'recent60'},
              {label: '本月', value: 'month'},
              {label: '上月', value: 'lastMonth'},
              {label: '本年', value: 'year'},
              {label: '去年', value: 'lastYear'},
            ]
          },
        ],

        filterCloseFn: null,

        logTypeOptions: [
          { label: '新增日报', value: 1 },
          { label: '新增周报', value: 2 },
          { label: '新增月报', value: 3 },
        ],

        activeItem: null,
        activeIndex: null,
        activeCommandData: null,

        refreshPage: false	// 刷新页面标志
      }
    },
    onShow() {
      if (this.refreshPage) {
        this.$nextTick(function() {
          this.refreshPage = false
          this.getList({}, true)
        })
      }
    },
    onLoad(options) {
      if (options.by) {
        const val = Number(options.by)
        if (!isNaN(val)) {
          const findIndex = this.taskOptions[0].options.findIndex(o => o.value === val)
          if (findIndex !== -1) {
            this.taskOptions[0].valueData = findIndex
            this.taskOptions[0].value = val
            this.filterData.by = val
          }
        }
      }
      this.getList()
    },
    created() {
      this.guid = this.$guid()
    },
    methods: {
      getParams() {
        let params = {}
        if (this.filterData.by) {
          params.by = this.filterData.by
          params.deptIds = []

          switch (this.filterData.by) {
          case '__delete__':
            params.createUserId = ''
            delete params.by
            // delete params.createUserId
            delete this.listParams.by
            break;
          case 1:
            params.createUserId = ''
            break;
          case 2:
            params.createUserId = ''
            break;
          }
        }
        if (
          this.filterData.userAndDept === 1 && 
          this.filterData.userAndDeptVal && 
          this.filterData.by != 1
        ) {
          const userList = this.filterData.userAndDeptVal.userList || []
          const deptList = this.filterData.userAndDeptVal.deptList || []
          if (userList.length > 0) {
            params.createUserId = userList.map(o => o.userId).join(',')
          }
          if (deptList.length > 0) {
            params.deptIds = deptList.map(o => o.deptId)
          }
        }

        params.type = this.filterData.type

        // console.log('ffff', this.filterData)
        // console.log('params', params)
        return params
      },

      handleFilter(item, tabIndex, tabs, callback) {
        // console.log('filter item', item)
        this.filterData[item.field] = item.value

        const findIndex = this.taskOptions.findIndex(o => o.field === 'userAndDept')
        if (this.filterData.by == 1) {
          if (findIndex !== -1) {
            this.taskOptions.splice(findIndex, 1)
            delete this.listParams.by
          }
        } else {
          if (findIndex === -1) {
            this.taskOptions.splice(1, 0, {
              label: '成员',
              field: 'userAndDept',
              value: 0,
              valueData: 0,
              options: [
                {label: '全部成员', value: 0 },
                {label: '员工与部门', value: 1, showMoreIcon: true },
              ]
            })
          }
        }
        this.$nextTick(function() {
          this.$refs.wkBaseFilter.setDefault(this.filterData)
        })

        if (item.field === 'userAndDept' && item.value === 1) {
          getApp().globalData.selectedValBridge.userAndDept = {
            guid: this.guid,
            defaultVal: this.filterData.userAndDeptVal || {}
          }
          uni.$on('selected-user-and-dept', this.selectUserAndDept)
          this.$Router.navigateTo({
            url: '/pages_common/selectList/userAndDept'
          })
          if (callback) {
            this.filterCloseFn = callback
          }
        } else {
          this.getList({}, true)
        }
      },

      selectUserAndDept(data) {
        if (data.guid === this.guid) {
          this.filterData.userAndDeptVal = data.data
          uni.$off('selected-user-and-dept')
          if (this.filterCloseFn) {
            this.filterCloseFn()
          }
          this.getList({}, true)
        }
      },

      handleUpdate(data, index) {
        // 修复小程序在切换点赞状态后不会刷新数据问题
        this.$set(this.listData, index, data)
      },

      handleToCommand(index) {
        this.activeItem = this.listData[index]
        this.activeIndex = index

        QueryCommentList({
          typeId: this.activeItem.logId,
          type: 2
        }).then(res => {
          this.activeCommandData = res || []
        }).catch(() => {})

        this.$refs.commentPopup.open()
      },

      handleUpdateComment() {
        const num = this.activeItem.replyNum
        this.activeItem.replyNum = 0
        this.$nextTick(function() {
          this.activeItem.replyNum = Number(num) + 1

          QueryCommentList({
            typeId: this.activeItem.logId,
            type: 2
          }).then(res => {
            this.activeCommandData = res || []
          }).catch(() => {})

          this.handleUpdate(this.activeItem, this.activeIndex)
        })
      },

      handleCloseCommentPopup() {
        this.$refs.commentPopup.close()
      },

      /**
       * 查看日志详情
       * @param data
       */
      handleToDetail(data) {
        this.$Router.navigateTo({
          url: '/pages_log/detail',
          query: {
            id: data.logId
          }
        })
      },

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

      handleAdd() {
        this.$refs.popup.open()
      },

      handleCommand(index, command, next) {
        next()
        this.$Router.navigateTo({
          url: '/pages_log/add',
          query: {
            type: command.value
          }
        })
      }
    }
  }
</script>

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

		.list-scroll {
			flex: 1;
			overflow: hidden;

			.journal-item-wrapper {
				margin-bottom: 15rpx;
			}
		}
	}
</style>
