<template>
  <a-card>
    <a-tabs v-model="activeKey">
      <a-tab-pane key="reminder">
        <template slot="tab">
          催办提醒
          <a-badge v-if="unreadCount[type.reminder] > 0" dot />
        </template>
        <sd-data-table
          ref="reminder"
          data-url="api/framework/v1/person/messages/reminder-with-trustor"
          :columns="reminderColumns"
          :row-key="'reminderId'"
          :search-fields="['msgTitle']"
          @rowClick="(...args) => rowClick(type.reminder, ...args)"
        >
          <msg-title-display
            slot="msgTitle"
            slot-scope="text, record"
            :context="_self"
            :text="text"
            :read="!!record.msgStatus"
          />
        </sd-data-table>
      </a-tab-pane>
      <a-tab-pane key="expiry">
        <template slot="tab">
          到期提醒
          <a-badge v-if="unreadCount[type.expiry] > 0" dot />
        </template>
        <sd-data-table
          ref="expiry"
          data-url="api/framework/v1/person/messages/expiry-with-trustor"
          :columns="expiryColumns"
          :search-fields="['msgTitle']"
          @rowClick="(...args) => rowClick(type.expiry, ...args)"
        >
          <msg-title-display
            slot="msgTitle"
            slot-scope="text, record"
            :context="_self"
            :text="text"
            :read="!!record.msgStatus"
          />
          <div slot="flowTimeToDeadLine" slot-scope="text, record">
            <div
              v-if="record.flowTimeToDeadline"
              :class="{
                [$style.limittime]: record.flowColor === 'blue',
                [$style.expiretime]: record.flowColor === 'orange',
                [$style.overtime]: record.flowColor === 'red',
              }"
            >
              <a-icon type="sd-3-circle" title="全流程限时" :class="$style.remind" />{{
                deadline(record.flowColor)
              }}:
              <div :class="$style.time" :title="record.flowTimeToDeadline"
                >{{ record.flowTimeToDeadline }}
              </div>
            </div>
          </div>
          <div slot="stepTimeToDeadLine" slot-scope="text, record">
            <div
              v-if="record.stepTimeToDeadline"
              :class="{
                [$style.limittime]: record.stepColor === 'blue',
                [$style.expiretime]: record.stepColor === 'orange',
                [$style.overtime]: record.stepColor === 'red',
              }"
            >
              <a-icon type="exclamation-circle" title="本环节限时" :class="$style.remind" />{{
                deadline(record.stepColor)
              }}:
              <div :class="$style.time" :title="record.stepTimeToDeadline"
                >{{ record.stepTimeToDeadline }}
              </div>
            </div>
          </div>
        </sd-data-table>
      </a-tab-pane>
      <a-tab-pane key="xitong">
        <template slot="tab">
          系统提醒
          <a-badge v-if="unreadCount[type.sys] > 0" dot />
        </template>
        <sd-data-table
          ref="xitong"
          data-url="api/framework/v1/person/messages/sys-with-trustor"
          :columns="columns"
          :actions="actions"
          :search-fields="['msgTitle']"
          :filter-expressions="xtexpressions"
          :show-selection="true"
        >
          <msg-title-display
            slot="msgTitle"
            slot-scope="text, record"
            :context="_self"
            :text="text"
            :read="!!record.msgStatus"
            :clickable="!!record.module"
            tool-tip
            @click="sysRemindClick(record)"
          />
        </sd-data-table>
      </a-tab-pane>
      <a-tab-pane key="inform" tab="知会提醒">
        <sd-data-table
          ref="inform"
          data-url="api/framework/v1/person/messages/inform"
          :columns="informColumns"
          :search-fields="['msgTitle']"
          @rowClick="(...args) => rowClick('', ...args)"
        >
          <div slot="msgTitle" slot-scope="text, record">
            <a v-if="record.openLink" @click="rowClick('', record)">{{ text }}</a>
            <span v-else>{{ text }}</span>
          </div>
        </sd-data-table>
      </a-tab-pane>
    </a-tabs>
  </a-card>
</template>

<script>
import storeMixin from '@/common/store-mixin'
import TodoListService from '@/todo/todo-list-service'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import { Message, Modal, Tooltip, Badge } from 'ant-design-vue'
import eventBus from '@/common/services/event-bus'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import loginService from '@/login/login-service'
import navMenuService from '@/frame/nav-menu-service'
import components from './_import-components/sd-message-remind-import'
import WorkbenchService from './workbench-service'

const reminderColumns = [
  {
    title: '标题',
    dataIndex: 'msgTitle',
    sdClickable: true,
    scopedSlots: { customRender: 'msgTitle' },
  },
  {
    title: '发送人',
    dataIndex: 'senderName',
  },
  {
    title: '催办内容',
    dataIndex: 'msgContent',
  },
  {
    title: '接收时间',
    dataIndex: 'sentDate',
    sdRender: TableColumnTypes.dateTime,
    sorter: true,
    defaultSortOrder: 'desc',
  },
]

const expiryColumns = [
  {
    title: '标题',
    dataIndex: 'msgTitle',
    sdClickable: true,
    scopedSlots: { customRender: 'msgTitle' },
  },
  {
    title: '接收时间',
    dataIndex: 'sentDate',
    sdRender: TableColumnTypes.dateTime,
    sorter: true,
    defaultSortOrder: 'desc',
  },
  {
    title: '截止时间',
    dataIndex: 'dueDate',
    sdRender: TableColumnTypes.dateTime,
  },
  {
    title: '全流程限时',
    dataIndex: 'flowTimeToDeadLine',
    scopedSlots: { customRender: 'flowTimeToDeadLine' },
  },
  {
    title: '本环节限时',
    dataIndex: 'stepTimeToDeadLine',
    scopedSlots: { customRender: 'stepTimeToDeadLine' },
  },
]

const columns = [
  {
    title: '提示内容',
    dataIndex: 'msgTitle',
    scopedSlots: { customRender: 'msgTitle' },
  },
  {
    title: '接收时间',
    dataIndex: 'sentDate',
    sorter: true,
    sdRender: TableColumnTypes.dateTime,
    defaultSortOrder: 'desc',
    width: '250px',
  },
  {
    title: '状态',
    dataIndex: 'msgStatus',
    sdHidden: true,
  },
]

const informColumns = [
  {
    title: '标题',
    dataIndex: 'msgTitle',
    scopedSlots: { customRender: 'msgTitle' },
  },
  {
    title: '审批意见',
    dataIndex: 'msgContent',
  },
  {
    title: '发送人',
    dataIndex: 'senter',
    width: '16%',
  },
  {
    title: '发送时间',
    dataIndex: 'sentDate',
    sdRender: TableColumnTypes.dateTime,
    defaultSortOrder: 'desc',
    width: '16%',
  },
  {
    title: '发送环节',
    dataIndex: 'sentStepName',
    width: '16%',
  },
]

const msgTitleDisplay = {
  props: {
    context: {
      type: Object,
      default: () => {},
    },
    read: {
      type: Boolean,
      default: false,
    },
    clickable: {
      type: Boolean,
      default: false,
    },
    text: {
      type: String,
      default: '',
    },
    toolTip: {
      type: Boolean,
      default: false,
    },
  },
  render() {
    const content = (
      <span
        class={{
          [this.context.$style.notice]: !this.read,
          [this.context.$style.readDoc]: this.clickable,
        }}
        on={{ click: () => this.$emit('click') }}
      >
        {!this.read ? <Badge dot title='未读' /> : ''}
        {this.text}
      </span>
    )
    return this.toolTip ? <Tooltip title={this.text}> {content}</Tooltip> : content
  },
}

export default {
  name: 'SdMessageRemind',
  metaInfo: {
    title: '消息提醒',
  },
  components: {
    ...components,
    msgTitleDisplay,
  },
  mixins: [storeMixin],
  data() {
    return {
      activeKey: 'reminder',
      reminderColumns,
      expiryColumns,
      columns,
      informColumns,
      actions: [
        {
          label: '已阅',
          id: 'read',
          permission: 'oaRemindMessage-readed',
          type: TableActionTypes.batch, // 主按钮，高亮色显示
          callback: (keys, records) => {
            this.haveReadRows(keys, records)
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: 'oaRemindMessage-delete',
          type: TableActionTypes.batch, // 批处理按钮，选中文档时才能点击
          callback: (keys, records) => {
            const result = records.some((item) => item.msgStatus === 0)
            if (result) {
              Modal.confirm({
                content: '您有未阅的消息，是否删除?',
                okText: '是',
                okType: 'danger',
                cancelText: '否',
                onOk: () => {
                  this.handleDelete(keys)
                },
              })
            } else {
              this.handleDelete(keys)
            }
          },
        },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'msgStatus',
          op: 'eq',
          stringValue: '0',
        },
      ],
      xtexpressions: [
        {
          dataType: 'str',
          name: 'msgType',
          op: 'like',
          stringValue: '%%',
        },
      ],
      type: {
        reminder: 'reminder',
        expiry: 'expiry',
        sys: 'sys',
      },
      unreadCount: {},
    }
  },
  computed: {
    deadline() {
      return function(type) {
        let deadline = ''
        switch (type) {
          case 'blue':
            deadline = '限时'
            break
          case 'orange':
            deadline = '快到期'
            break
          case 'red':
            deadline = '已超时'
            break
        }
        return deadline
      }
    },
  },
  created() {
    // 初始化，未读数设置为0
    Object.keys(this.type).forEach((key) => {
      this.$set(this.unreadCount, this.type[key], 0)
    })
    this.updateUnreadCount()
  },
  methods: {
    sysRemindClick(task) {
      let url = ''
      const setUrl = (value) => (url = value)
      return eventBus.emit('sdSysMessageItemClick', task, { setUrl }).then((evt) => {
        if (evt.defaultPrevented) return
        if (!url) return
        if (task.pcAddr && !url.startsWith('http')) {
          let pcAddr = task.pcAddr.split('#')[0]
          if (pcAddr.substr(-1) !== '/') pcAddr = pcAddr + '/'
          url =
            pcAddr +
            `#/sd-thirdparty-login?redirect=${encodeURIComponent(
              url
            )}&local_token=${encodeURIComponent(loginService.getTokens().access_token)}`
        }
        return crossWindowWatcher.waitForChanged(url, task.srcTrustId)
      })
    },
    rowClick(type, record, rowIndex) {
      this.msgToRead(type, record)
      TodoListService.openTaskItem(record, this.activeKey).then((refreshFlag) => {
        if (refreshFlag) this.$refs[this.activeKey].refresh()
      })
    },
    msgToRead(type, record) {
      if (type) {
        // 消息是未读时，设置成已读
        if (!record.msgStatus) {
          WorkbenchService.haveReadMessage(record.id).then((res) => {
            if (res.status === 200) {
              record.msgStatus = 1
              this.unreadCount[type]--
              eventBus.emit('updateRemindCount', this.unreadCount)
            }
          })
        }
      }
    },

    // 系统提醒已阅功能
    haveReadRows(selectedRowKeys, records) {
      const msgStatus = records.every((item) => {
        return item.msgStatus
      })
      // 选中的只是已阅的消息
      if (msgStatus) {
        Message.warning('您选中的消息已是已阅！')
      } else {
        if (selectedRowKeys.length > 1) {
          const params = {
            ids: selectedRowKeys,
          }
          WorkbenchService.haveReadMessages(params).then((res) => {
            if (res.status === 200) {
              this.$refs.xitong.clearSelection()
              this.$refs.xitong.refresh()
              this.updateUnreadCount(this.type.sys)
            }
          })
        } else {
          WorkbenchService.haveReadMessage(selectedRowKeys.join(',')).then((res) => {
            if (res.status === 200) {
              this.$refs.xitong.clearSelection()
              this.$refs.xitong.refresh()
              this.updateUnreadCount(this.type.sys)
            }
          })
        }
      }
    },

    // 系统提醒 删除
    handleDelete(keys) {
      Modal.confirm({
        title: '您确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          const params = {
            ids: keys.join(),
          }
          WorkbenchService.delete(params).then((res) => {
            if (res.status === 200) {
              Message.success('删除成功')
              this.$refs.xitong.clearSelection()
              this.$refs.xitong.refresh()
              this.updateUnreadCount(this.type.sys)
            } else {
              Message.error(res.statusText)
            }
          })
        },
        onCancel() {
          Message.warning('删除无效')
        },
      })
    },
    updateUnreadCount(type) {
      navMenuService.getRemindCount(type).then((res) => {
        if (res.data) {
          if (type) {
            this.$set(this.unreadCount, type, Number(res.data[type.toUpperCase()]) || 0)
          } else {
            this.$set(this.unreadCount, this.type.reminder, Number(res.data.REMINDER) || 0)
            this.$set(this.unreadCount, this.type.expiry, Number(res.data.EXPIRY) || 0)
            this.$set(this.unreadCount, this.type.sys, Number(res.data.SYS) || 0)
          }
          eventBus.emit('updateRemindCount', this.unreadCount)
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.title {
  font-family: $typography-title-font-weight;
}
.timeout {
  color: $highlight-color;
}
.time {
  overflow: hidden;
  text-indent: 20px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.remind {
  margin-right: 4px;
}

/* 限时 */
.limittime {
  color: $blue-6;
}

/* 快到期 */
.expiretime {
  color: $yellow-6;
}

.overtime {
  color: $red-6;
}

.notice {
  :global(.ant-badge) {
    margin-right: 6px;
    vertical-align: baseline;
  }

  font-weight: 600;
}
.read-doc {
  color: $blue-6;
  cursor: pointer;
}
</style>
