<template>
  <z-paging class="page" ref="paging" v-model="dataList" @query="loadData">
    <template #top>
      <uni-row style="padding-top: 8px">
        <uni-badge
          v-for="(item, index) of tabs"
          :key="index"
          absolute="rightTop"
          :offset="[0, 4]"
          :text="index === 2 ? unreadMessageCount : 0"
          style="margin-right: 20px">
          <text :class="index === currentTab ? 'tab-selected' : 'tab-normal'" @click="onTabChanged(index)">
            {{ item }}
          </text>
        </uni-badge>
      </uni-row>
    </template>
    <view class="list">
      <template v-if="currentTab === 0">
        <view v-for="(item, index) of dataList">
          <view class="todo-item flex-row align-center" @click="navigateToDetail(item)">
            <view style="flex: 1">
              <view class="flex-row align-center msg-title justify-between">
                <view class="flex-row align-center">
                  <view class="dot" />
                  <view>{{ item.processInstance?.name }}</view>
                </view>
                <view class="msg-content">
                  {{ item.createTime ? dayjs(item.createTime).format('YYYY-MM-DD HH:mm') : '' }}
                </view>
              </view>
              <view class="msg-content" style="margin-top: 5px">{{ $t('message.id') + ' ' + item.id }} </view>
            </view>
          </view>
          <view v-if="index !== dataList.length - 1" class="todo-divider" />
        </view>
      </template>
      <template v-else-if="currentTab === 1">
        <view v-for="(item, index) of dataList">
          <view class="todo-item flex-row align-center" @click="navigateToDetail(item)">
            <view style="flex: 1">
              <view class="flex-row align-center msg-title justify-between">
                <view style="margin-left: -8px">【{{ getStatusName(item.status) }}】</view>
                <view class="msg-content">
                  {{ dayjs(item.startTime).format('YYYY-MM-DD HH:mm') }}
                </view>
              </view>
              <view class="msg-content" style="margin-top: 5px">
                {{ item.id + getApprovalUser(item) + getStatusName(item.status) }}
              </view>
            </view>
          </view>
          <view v-if="index !== dataList.length - 1" class="todo-divider" />
        </view>
      </template>
      <template v-else-if="currentTab === 2">
        <view v-for="(item, index) of dataList" class="flex-col" @click="navigate(item)">
          <view class="sys-msg-item flex-row" style="justify-content: center">
            <image src="~@/static/message/system-message-logo.png" style="width: 20px; height: 20px; margin-top: 5px" />
            <div class="flex-col" style="flex: 1; margin-left: 10px">
              <text class="msg-title">系统消息</text>
              <text class="msg-content">{{ item.templateContent }}</text>
            </div>
            <text class="msg-content" style="margin-top: 10px">{{
              item.createTime ? dayjs(item.createTime).format('YYYY-MM-DD HH:mm') : ''
            }}</text>
          </view>
          <view v-if="index !== dataList.length - 1" class="divider" />
        </view>
      </template>
    </view>
  </z-paging>
</template>

<script setup>
  import { getCurrentInstance, nextTick, onMounted, ref } from 'vue';
  import { getMessageList, markReadMessage } from '@/api/message';
  import { getTodoList, getApprovalList } from '@/api/task';
  import dayjs from 'dayjs';
  import { useDataDictStore } from '@/store/modules/dataDict';
  import { messageNavigate } from '@/utils/navigate';
  import { onLoad } from '@dcloudio/uni-app';

  const { appContext } = getCurrentInstance();
  const t = appContext.config.globalProperties.$t;

  const currentTab = ref(0);
  const tabs = [t('message.tab1'), t('message.tab2'), t('message.tab3')];
  const onTabChanged = index => {
    currentTab.value = index;
    paging.value.reload();
  };

  const paging = ref(null);
  const dataList = ref([]);
  const unreadMessageCount = ref(0);
  const loadData = async (pageNo, pageSize) => {
    try {
      const params = {
        pageNo,
        pageSize,
      };
      let response;
      if (currentTab.value === 0) {
        response = await getTodoList(params);
      } else if (currentTab.value === 1) {
        response = await getApprovalList(params);
      } else {
        response = await getMessageList(params);
      }
      unreadMessageCount.value = response.data.length;
      paging.value.complete(response.data.list);
    } catch (e) {
      console.log(e);
      paging.value.complete(false);
    }
  };

  const navigateToDetail = item => {
    if (currentTab.value === 0) {
      uni.navigateTo({
        url: `/pages/message/detail/index?id=${item.id}&processInstanceId=${item.processInstanceId}`,
      });
    } else {
      uni.navigateTo({
        url: `/pages/message/detail/index?processInstanceId=${item.id}`,
      });
    }
  };

  // 根据 businessType 和 businessId 进行跳转
  const navigate = item => {
    markReadMessage(item.id);
    messageNavigate({
      ...item.templateParams,
      id: item.templateParams.businessId,
      type: item.templateParams.businessType,
    });
  };

  /**
   * 获取当前审批人
   * @param item
   * @returns {string}
   */
  const getApprovalUser = item => {
    if (item && item.tasks && item.tasks.length > 0 && item.tasks[0].assigneeUser) {
      return item.tasks[0].assigneeUser.nickname;
    } else {
      return '';
    }
  };

  const statusList = ref([]); // 审批状态列表
  const getStatusName = status => {
    for (const item of statusList.value) {
      if (Number.parseInt(item.value) === Number.parseInt(status)) {
        return item.label;
      }
    }
  };

  const { getDataDictList } = useDataDictStore();

  onLoad(options => {
    currentTab.value = Number(options.currentTab) || 0;
  });

  onMounted(() => {
    statusList.value = getDataDictList('bpm_process_instance_status');
    uni.$once('update', () => nextTick(() => paging.value.reload()));
  });
</script>

<style scoped lang="scss">
  .page {
    box-sizing: border-box;
    padding: 10px !important;
  }

  .root {
    width: 100%;
    height: 100%;
    position: relative;
    box-sizing: border-box;
    overflow: hidden;
  }

  .tab-selected {
    color: #333333;
    font-size: 18px;
    font-weight: bold;
  }

  .tab-normal {
    color: #666666;
    font-size: 14px;
  }

  .list {
    margin-top: 10px;
    background-color: white;
    border-radius: 6px;
  }

  .msg-title {
    color: #333333;
    font-size: 14px;
    font-weight: 500;
  }

  .msg-content {
    color: #999999;
    font-size: 12px;
  }

  .sys-msg-item {
    padding: 19px 20px 14px 15px;
  }

  .divider {
    margin: 0 19px 0 45px;
    height: 0.5px;
    background-color: #cacccf;
  }

  .dot {
    width: 3px;
    height: 3px;
    border-radius: 2px;
    background-color: #ff3b36;
    margin-right: 6px;
  }

  .todo-item {
    padding: 20px;
    width: 100%;
    height: auto;
    box-sizing: border-box;
  }

  .todo-divider {
    margin: 0 20px;
    border-bottom: 0.5px solid #cacccf;
  }
</style>
