<template>
  <el-card id="todo-card" class="box-card" shadow="hover">
    <div slot="header" class="clearfix">
      <SvgIcon style="color: var(--theme-color);width: 22px;height: 22px;" icon-class="notice" />
      <span
        style="padding-left: 15px"
      >待办事项</span>
      <i class="el-icon-more" style="margin-left: auto; font-size: 20px" />
    </div>

    <div style="position: relative;height: 100%;width: 100%;">
      <div style="position: absolute;top: 0;left: 0;right: 0;bottom: 0;">
        <el-table
          v-loading="loading"
          style="width: 100%;"
          size="mini"
          :header-cell-style="{
            'font-weight': '600',
            'background': '#f8f8f9',
            'color': '#515a6e'
          }"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255, 255, 255, 0.8)"
          :show-header="false"
          :height="tableHeight"
          :loading="loading"
          :data="list"
        >
          <el-table-column type="index" width="46" align="center" />
          <el-table-column
            v-for="(item, index) in table"
            :key="index"
            :width="item.width"
            :label="item.title"
            :prop="item.key"
            :show-overflow-tooltip="item['show-overflow-tooltip']"
            header-align="center"
            :align="item.align"
            :formatter="item.formatter"
          />
          <el-table-column label="操作" header-align="center" width="160" fixed="right">
            <template #default="{ row }">
              <el-button size="mini" style="padding: 5px 10px;background: #f0f3fa;color: #333;border: 1px solid #dae1f0;" @click="read(row)">设为已读</el-button>
              <el-button size="mini" type="primary" style="padding: 5px 10px;" @click="handle(row)">办理</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          style="display: flex;justify-content: center;"
          layout="prev, pager, next"
          :total="total"
          :page-size.sync="select.page_size"
          @current-change="e => {
            select.page = e;
            getNotices();
          }"
        />
      </div>
    </div>

    <vxe-modal
      v-model="isShowModal"
      :z-index="zIndex"
      transfer
      resize
      show-zoom
      :fullscreen="$store.getters.device === 'mobile'"
      title="办理"
      :width="defaultModalSize.width"
      :height="defaultModalSize.height"
      esc-closable
    >
      <iframe :src="modalUrl" style="width: 100%;height: 100%" frameborder="0" />
    </vxe-modal>
  </el-card>
</template>

<script>
import { PopupManager } from 'element-ui/lib/utils/popup'
import SvgIcon from '@/components/SvgIcon/index.vue'
import ElementResize from 'element-resize-detector'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { defaultModalSize } from '@/settings'

export default {
  name: 'ToDo',
  components: {
    SvgIcon
  },
  layout: {
    x: 4,
    y: 0,
    w: 6,
    h: 4,
    i: 'ToDo',
    name: '待办事项'
  },
  data() {
    return {
      defaultModalSize,
      zIndex: PopupManager.nextZIndex(),
      isShowModal: false,
      modalUrl: '/',
      select: {
        page: 1,
        page_size: 10
      },
      timer: null,
      tableHeight: 120,
      loading: false,
      list: [],
      total: 0,
      table: [
        {
          title: '收件时间',
          key: 'created_at',
          width: 156,
          align: 'center',
          formatter: (row, column, cellValue) => {
            return this.$moment(cellValue).format('YYYY-MM-DD HH:mm:ss')
          }
        },
        {
          title: '内容',
          key: 'data.title',
          align: 'left',
          'show-overflow-tooltip': true,
          minWidth: 200
        }
      ]
    }
  },
  computed: {},
  watch: {
    isShowModal(newVal) {
      if (newVal) {
        this.zIndex = PopupManager.nextZIndex()
      } else {
        this.modalUrl = ''
      }
    }
  },
  created() {
    this.getNotices(true)
    this.timer = setInterval(this.getNotices, 5000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  mounted() {
    this.init()
  },
  methods: {
    async getNotices(loading = false) {
      try {
        if (loading) {
          this.loading = true
        }
        const res = await axios.get(`${process.env.VUE_APP_BASE_API}/api/notification/todo`, {
          headers: {
            'Authorization': `Bearer ${getToken()}`
          },
          params: this.select
        })
        if (res.status === 200) {
          this.list = res.data.data?.result
          this.total = res.data.data?.total
        }
        this.loading = false
      } catch (err) {
        console.error(err)
        this.loading = false
      }
    },

    init() {
      const cardDom = document.getElementById('todo-card')
      const cardTitleH = 59
      const elementResize = ElementResize({
        strategy: 'scroll'
      })
      elementResize.listenTo(cardDom, (ele) => {
        this.tableHeight =
          cardDom.getBoundingClientRect().height -
          40 -
          cardTitleH - 32
      })
    },

    async read(row) {
      try {
        this.loading = true
        const res = await axios.get(`${process.env.VUE_APP_BASE_API}/api/notification/read`, {
          headers: {
            'Authorization': `Bearer ${getToken()}`
          },
          params: {
            id: row.id
          }
        })
        if (res.status === 200) {
          await this.getNotices()
        }
        this.loading = false
      } catch (err) {
        console.error(err)
        this.loading = false
      }
    },
    handle(row) {
      try {
        const data = row.data
        if (data.from === 'ht') {
          this.modalUrl = `/${data.from}/#/contract/contractList?auth_token=${window.encodeURIComponent(getToken())}&module_name=${data.from}&keyword=${(/\[(.*?)]/.exec(data.title) ? /\[(.*?)]/.exec(data.title)[1] : '')}&isSinglePage=1`
        } else if (data.from === 'oa') {
          this.modalUrl = `/${data.from}/#/flow/create?auth_token=${window.encodeURIComponent(getToken())}&module_name=${data.from}&flow_id=${data.other?.flow_id}&isSinglePage=1`
        }
        console.log(this.modalUrl)
        this.isShowModal = true
      } catch (err) {
        this.$message.warning('未找到流程')
        console.error(err)
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-card__body {
  width: 100%;
  height: calc(100% - 58px);
}
::v-deep .el-table th,::v-deep .el-table td {
  border-bottom-style: dashed;
}
.clearfix {
  display: flex;
  align-items: center;
}
::v-deep .vxe-modal--content {
  padding: 0;
}
</style>
