<template>
  <div :class="prefixCls">
    <Popover title="" arrow-point-at-center :overlayClassName="`${prefixCls}__overlay`">
      <Badge :count="count" dot :numberStyle="numberStyle">
        <IconFontSymbol icon="tongzhi" fontSize="22" />
      </Badge>
      <template #content>
        <Tabs>
          <template v-for="item in listData" :key="item.key">
            <TabPane>
              <template #tab>
                {{ item.name }}
                <span v-if="item.unreadNum !== 0">({{ item.unreadNum }})</span>
              </template>

              <div v-if="item.key === '4'" class="h-450px">
                <div class="h-193px overflow-hidden">
                  <div class="list-item">
                    <span class="header-title">{{ t('流程审批') }}</span>
                    <router-link
                      class="opr"
                      :to="{
                        path: '/task/processtasks',
                        query: {
                          name: 'ToDoTasks',
                        },
                      }"
                    >
                      <RightCircleFilled style="font-size: 14px" />
                    </router-link>
                  </div>
                  <div v-if="item.list.length > 0">
                    <div class="readed-mark" v-for="it in item.list" :key="it.id">
                      <div
                        class="list-item"
                        :class="it.read ? 'readed' : ''"
                        @click="ApprovalHandle(it, item.key, 1)"
                      >
                        <span class="list-title">{{ it.title }}</span>
                        <span class="list-item-time">{{ it.timeFormat }}</span>
                      </div>
                    </div>
                  </div>
                  <a-empty :image="simpleImage" v-else />
                </div>
                <div class="h-193px overflow-hidden">
                  <div class="list-item">
                    <span class="header-title">{{ t('流程传阅') }}</span>
                    <router-link
                      class="opr"
                      :to="{
                        path: '/task/processtasks',
                        query: { name: 'MyCirculation' },
                      }"
                    >
                      <RightCircleFilled style="font-size: 14px" />
                    </router-link>
                  </div>
                  <div v-if="item.read!.length>0">
                    <div class="readed-mark" v-for="it in item.read" :key="it.id">
                      <div
                        class="list-item"
                        :class="it.read ? 'readed' : ''"
                        @click="ApprovalHandle(it, item.key, 2)"
                      >
                        <span class="list-title">{{ it.title }}</span>
                        <span class="list-item-time">{{ it.timeFormat }}</span>
                      </div>
                    </div>
                  </div>
                  <a-empty :image="simpleImage" v-else />
                </div>
                <div class="notice-footer">
                  <span @click="setReadAll(item.key)" class="view">{{ t('全部设置已读') }}</span>
                </div>
              </div>
              <div v-else-if="item.key === '5'" class="h-450px">
                <div v-if="item.list.length > 0" class="h-386px">
                  <div
                    class="list-item readed-mark"
                    v-for="(it, index) in item.list"
                    :key="index"
                    :class="it.read ? 'readed' : ''"
                    @click="
                      () => {
                        it.read = 1;
                        setReadSingle(it.id, item.key);
                      }
                    "
                  >
                    <a-tooltip class="flex items-center">
                      <template #title>
                        <div style="max-height: 400px; overflow: auto">{{ it.messageContent }}</div>
                      </template>
                      <a-tag color="red">通知</a-tag>
                      <span class="list-title"> {{ it.messageContent }}</span>
                    </a-tooltip>
                    <span class="list-item-time">{{ it.sendTime }}</span>
                  </div>
                  <div class="notice-footer">
                    <span @click="setReadAll(item.key)" class="view">{{ t('全部设置已读') }}</span>
                    <span @click="prevSystemPage" class="pry">{{ t('上一页') }}</span>
                    <span @click="nextSystemPage" class="pry">{{ t('下一页') }}</span>
                  </div>
                </div>
                <a-empty :image="simpleImage" v-else />
              </div>
              <div v-else class="h-450px">
                <div v-if="item.list.length > 0" class="h-386px">
                  <div
                    class="list-item readed-mark"
                    v-for="it in item.list"
                    :key="it.id"
                    :class="it.read ? 'readed' : ''"
                    @click="
                      () => {
                        it.read = 1;
                        setReadSingle(it.id, item.key);
                      }
                    "
                  >
                    <router-link
                      :to="{
                        path: '/OA001/schedule',
                        query: { name: 'MySchedule' },
                      }"
                      v-if="item.key == '3'"
                      class="list-item-title"
                    >
                      <a-tooltip class="flex items-center">
                        <template #title>{{ it.title }}</template>
                        <a-tag color="green">日程</a-tag>
                        <span class="list-title !w-full">{{ it.title }}</span>
                      </a-tooltip>
                    </router-link>
                    <div v-else class="list-item-title">
                      <a-tooltip class="flex items-center">
                        <template #title>{{ it.title }}</template>
                        <a-tag color="blue" v-if="item.key == '1'">新闻</a-tag>
                        <a-tag color="orange" v-if="item.key == '2'">公告</a-tag>
                        <span class="list-title !w-full">{{ it.title }}</span>
                      </a-tooltip>
                    </div>
                  </div>
                  <div class="notice-footer"
                    ><span @click="setReadAll(item.key)" class="view">{{ t('全部设置已读') }}</span
                    ><span v-if="item.key == '1'" class="pry"
                      ><router-link
                        class="opr"
                        :to="{
                          path: '/OA001/oaNews',
                        }"
                      >
                        {{ t('查看更多') }}
                      </router-link></span
                    ><span v-if="item.key == '2'" class="pry"
                      ><router-link
                        class="opr"
                        :to="{
                          path: '/OA001/oaNotices',
                        }"
                      >
                        {{ t('查看更多') }}
                      </router-link></span
                    ><span v-if="item.key == '3'" class="pry"
                      ><router-link
                        class="opr"
                        :to="{
                          path: '/OA001/schedule',
                        }"
                      >
                        {{ t('查看更多') }}
                      </router-link></span
                    ></div
                  >
                </div>
                <a-empty :image="simpleImage" v-else />
              </div>
            </TabPane>
          </template>
        </Tabs>
      </template>
    </Popover>
    <ModalPanel
      :visible="viewOpen"
      :width="800"
      :title="viewData.briefHead"
      @submit="viewOpen = false"
      @close="viewOpen = false"
    >
      <ViewModal v-if="viewOpen" :viewData="viewData" />
    </ModalPanel>
    <a-modal
      v-if="Approval.visible"
      :visible="Approval.visible"
      wrapClassName="full-modal"
      width="100%"
      :footer="null"
    >
      <ApprovalProcess
        v-if="Approval.visible"
        :taskId="Approval.taskId || ''"
        :processId="Approval.processId || ''"
        :schemaId="Approval.schemaId || ''"
        :visible="Approval.visible"
        @close="
          () => {
            Approval.visible = false;
          }
        "
      />
    </a-modal>
    <a-modal
      v-if="LookData.visible"
      :visible="LookData.visible"
      wrapClassName="full-modal"
      width="100%"
      :footer="null"
    >
      <LookProcess
        v-if="LookData.visible"
        :taskId="LookData.taskId || ''"
        :processId="LookData.processId || ''"
        :visible="LookData.visible"
        @close="
          () => {
            LookData.visible = false;
          }
        "
      />
    </a-modal>
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, onUnmounted, reactive } from 'vue';
  import { Popover, Tabs, Badge } from 'ant-design-vue';
  import { tabListData } from './data';

  import { useDesign } from '/@/hooks/web/useDesign';
  import { RightCircleFilled } from '@ant-design/icons-vue';
  import {
    getOaMessage,
    getOaNews,
    setOaRead,
    setSingleRead,
    setWorkReadAll,
    getScheduleMsg,
    setScheduleRead,
    setScheduleReadAll,
    getSystemMessage,
    getApproveState,
    setSystemReadAll,
  } from '/@/api/system/login';
  import { Empty } from 'ant-design-vue';
  import { ModalPanel } from '/@/components/ModalPanel/index';
  import ApprovalProcess from '/@/views/workflow/task/components/ApprovalProcess.vue';
  import LookProcess from '/@/views/workflow/task/components/LookProcess.vue';
  import ViewModal from '/@/views/dataconfig/oaNews/components/View.vue';
  import { getInfo } from '/@/api/system/oa';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { OaType } from '/@/enums/oa';
  import { useUserStore } from '/@/store/modules/user';
  import IconFontSymbol from '/@/components/IconFontSymbol/Index.vue';

  const { t } = useI18n();
  export default defineComponent({
    components: {
      Popover,
      Tabs,
      TabPane: Tabs.TabPane,
      Badge,
      IconFontSymbol,
      ApprovalProcess,
      LookProcess,
      ModalPanel,
      ViewModal,
      RightCircleFilled,
    },
    setup() {
      const Approval = ref<{
        taskId?: string;
        processId?: string;
        schemaId?: string;
        visible: boolean;
      }>({
        visible: false,
      });
      const LookData = ref<{
        taskId?: string;
        processId?: string;
        visible: boolean;
      }>({
        visible: false,
      });
      const userStore = useUserStore();
      const loginUserId = userStore.getUserInfo?.id;

      const viewOpen = ref(false);
      let viewData = ref({ briefHead: '' });
      const { prefixCls } = useDesign('header-notify');
      let times: any = ref();
      const listData = ref(tabListData);
      const simpleImage = ref(Empty.PRESENTED_IMAGE_SIMPLE);
      const systemPage = reactive({
        limit: 1,
        total: 10,
        size: 5,
      });
      getDatas();
      times.value = setInterval(() => {
        getDatas();
      }, 10000);
      async function getDatas() {
        listData.value.forEach((o) => {
          o.list = [];
          o.unreadNum = 0;
          if (o.read) o.read = [];
        });
        try {
          let res = await getOaNews({ type: 1, loginUserId });
          res.list.forEach((o) => {
            if (!o.readId) listData.value[0].unreadNum += 1;
            listData.value[0].list.push({
              id: o.id,
              avatar: '',
              title: o.briefHead,
              description: '',
              datetime: o.releaseTime,
              color: '',
              type: '3',
              read: o.isRead,
            });
          });
          let res1 = await getOaNews({ type: 2, loginUserId });
          res1.list.forEach((o) => {
            if (!o.readId) listData.value[1].unreadNum += 1;
            listData.value[1].list.push({
              id: o.id,
              avatar: '',
              title: o.briefHead,
              description: '',
              datetime: o.releaseTime,
              color: '',
              type: '3',
              read: o.isRead,
            });
          });
          let res2 = await getOaMessage({ loginUserId });
          res2.forEach((o) => {
            if (o.messageType === 0) {
              if (!o.isRead) listData.value[2].unreadNum += 1;
              listData.value[2].list.push({
                id: o.id,
                avatar: '',
                title: o.messageContent,
                description: '',
                datetime: o.sendTime,
                timeFormat: o.timeFormat,
                color: '',
                type: '3',
                read: o.isRead,
              });
            } else if (o.messageType == 1) {
              if (!o.isRead) listData.value[3].unreadNum += 1;
              listData.value[3].list.push({
                id: o.id,
                avatar: '',
                title: o.messageContent,
                description: '',
                datetime: o.sendTime,
                timeFormat: o.timeFormat,
                color: '',
                type: '3',
                taskId: o.objectId,
                processId: o.processId,
                schemaId: o.schemaId,
                read: o.isRead,
              });
            } else if (o.messageType == 2) {
              if (!o.isRead) listData.value[3].unreadNum += 1;
              listData.value[3].read?.push({
                id: o.id,
                avatar: '',
                title: o.messageContent,
                description: '',
                datetime: o.sendTime,
                read: o.isRead,
                timeFormat: o.timeFormat,
                color: '',
                type: '3',
                taskId: o.objectId,
                processId: o.processId,
              });
            }
          });
          let res3 = await getScheduleMsg({ loginUserId });
          res3.list.forEach((item) => (item.read = item.isRead));
          listData.value[2].unreadNum = res3.list.filter((x) => !x.isRead).length;
          listData.value[2].list.push(...res3.list);
          await getSystemList();
        } catch (error) {
          clearInterval(times.value);
        }
      }
      async function getSystemList() {
        let res4 = await getSystemMessage({
          limit: systemPage.limit,
          size: systemPage.size,
          loginUserId,
        });
        res4.list.forEach((o) => {
          o.read = o.isRead;
        });
        listData.value[4].list = res4.list;
        systemPage.total = res4.total;
        listData.value[4].unreadNum = res4.unReadCount || 0;
      }
      const count = computed(() => {
        let count = 0;
        for (let i = 0; i < listData.value.length; i++) {
          count += listData.value[i].unreadNum;
        }
        return count;
      });
      async function prevSystemPage() {
        if (systemPage.limit > 1) {
          systemPage.limit--;
          await getSystemList();
        }
      }
      async function nextSystemPage() {
        if (systemPage.total - systemPage.limit * systemPage.size > 0) {
          systemPage.limit++;
          await getSystemList();
        }
      }
      async function setReadAll(type) {
        if (type == 1 || type == 2) {
          let ids: string[] = [];

          listData.value[type - 1].list.forEach((o) => {
            o.read = 1;
            ids.push(o.id);
          });

          await setOaRead(ids);
        } else if (type == 3) {
          await setScheduleReadAll();
          listData.value[type - 1].list.forEach((o) => {
            o.read = 1;
          });
        } else if (type == 4) {
          listData.value[type - 1].list.forEach((o) => {
            o.read = 1;
          });
          await setWorkReadAll();
        } else if (type == 5) {
          listData.value[type - 1].list.forEach((o) => {
            o.read = 1;
          });
          await setSystemReadAll();
        }
        listData.value[type - 1].unreadNum = 0;
      }

      async function setReadSingle(ids, num) {
        if (num == 3) {
          await setScheduleRead([ids]);
        } else if (num == 4 || num == 5) {
          await setSingleRead(ids);
        } else {
          await setOaRead([ids]);
        }
        if (listData.value[num - 1].unreadNum > 0) listData.value[num - 1].unreadNum -= 1;
        if (num == 1 || num == 2) {
          const record = await getInfo(ids);
          record.typeId = num == 1 ? OaType.NEWS : OaType.NOTICE;
          viewData.value = record;
          viewOpen.value = true;
        }
      }
      onUnmounted(() => {
        clearInterval(times.value);
      });
      async function ApprovalHandle(it, key, type) {
        if (type == 1) {
          let res = await getApproveState(it.taskId);
          if (res) {
            Approval.value = {
              taskId: it.taskId,
              processId: it.processId,
              schemaId: it.schemaId,
              visible: true,
            };
          } else {
            LookData.value = {
              taskId: it.taskId,
              processId: it.processId,
              visible: true,
            };
          }
        } else {
          LookData.value = {
            taskId: it.taskId,
            processId: it.processId,
            visible: true,
          };
        }
        it.read = 1;
        setReadSingle(it.id, key);
      }
      return {
        prefixCls,
        listData,
        count,
        setReadAll,
        simpleImage,
        numberStyle: {
          top: '24px',
          right: '2px',
        },
        setReadSingle,
        ApprovalHandle,
        Approval,
        LookData,
        t,
        viewOpen,
        viewData,
        systemPage,
        prevSystemPage,
        nextSystemPage,
      };
    },
  });
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-header-notify';

  .@{prefix-cls} {
    padding-top: 2px;

    &__overlay {
      width: 400px;
      padding-top: 4px;

      .ant-popover-inner {
        box-shadow: 0 0 15px 0 rgb(0 0 0 / 25%);
        border-radius: 16px;

        &-content {
          padding: 0;

          .ant-tabs-nav {
            height: 50px;
            margin: 0;

            .ant-tabs-tab {
              padding: 0 16px;

              & + .ant-tabs-tab {
                margin: 0;
              }
            }
          }
        }

        .ant-tabs-ink-bar {
          height: 1px;
        }
      }
    }

    .ant-tabs-content {
      width: 300px;
    }

    .ant-badge {
      font-size: 18px;
      display: flex;
      align-items: center;

      .ant-badge-multiple-words {
        padding: 0 4px;
      }

      svg {
        width: 0.9em;
      }
    }
  }
</style>
<style scoped lang="less">
  .list-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;
    font-weight: 400;
    font-size: 14px;
    height: 50px;
    cursor: pointer;
    margin: 0 16px;

    .ant-tag {
      font-size: 12px;
      width: 34px;
      height: 20px;
      line-height: 18px;
      padding: 0;
      text-align: center;
    }

    .header-title {
      color: @primary-color;
      font-size: 14px;
      display: flex;
      align-items: center;

      &::before {
        display: inline-block;
        width: 4px;
        height: 16px;
        background: @primary-color;
        border-radius: 2px;
        content: '';
        margin-right: 8px;
      }
    }

    a {
      color: #333;
      cursor: pointer;

      &.opr {
        color: @primary-color;
      }
    }

    &.readed {
      .list-title {
        color: #333;
      }
    }
  }

  .list-item-title {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 18px;
    color: #333;
  }

  .list-title {
    width: 180px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    line-height: 18px;
    color: @primary-color;
  }

  .list-item-time {
    text-align: right;
    color: #c3c8cf;
    font-size: 12px;
  }

  .notice-footer {
    display: flex;
    justify-content: flex-end;
    position: absolute;
    bottom: 16px;
    left: 0;
    right: 0;
    height: 32px;
    font-size: 14px;
    color: #fff;
    cursor: pointer;
    text-align: center;

    span.view {
      width: 104px;
      height: 32px;
      line-height: 32px;
      background: #f70;
      border-radius: 4px;
      margin-right: 16px;
    }

    span.pry {
      width: 82px;
      height: 32px;
      line-height: 32px;
      background: @primary-color;
      border-radius: 4px;
      margin-right: 16px;

      a {
        color: #fff;
      }
    }
  }
</style>
