<template>
  <view class="todo-container">
    <!-- 顶部搜索 + tab -->
    <view class="search-header">
      <view class="search-row">
        <uv-input placeholder="请输入审批名称" v-model="queryParams.instTitle" prefixIcon="search"
          prefixIconStyle="color: #999; font-size: 32rpx;" clearable shape="circle"
          customStyle="background-color: #f5f7fa; border: none;"></uv-input>
      </view>

      <view class="type-tabs">
        <uv-tabs :list="tabList" :current="currentTab" @change="onTabChange"
          :activeStyle="{ color: '#1c9bfd', fontWeight: 'bold', transform: 'scale(1.05)' }"
          :inactiveStyle="{ color: '#666' }" lineColor="#1c9bfd" lineWidth="40"
          :itemStyle="{ height: '88rpx', flex: 1 }" :scrollable="false"></uv-tabs>
      </view>
    </view>

    <!-- 列表区域 -->
    <view class="list-container">
      <scroll-view scroll-y class="scroll-list" :scroll-top="scrollTopValue" scroll-with-animation refresher-enabled
        :refresher-triggered="isTriggered" @refresherrefresh="onRefresh" @scroll="onScroll" @scrolltolower="loadMore"
        :show-scrollbar="false">
        <uv-empty v-if="!todoStore.list.length && loadStatus !== 'loading'" mode="list"></uv-empty>

        <view class="common-list-card" v-for="item in todoStore.list" :key="item.id || item.taskId">
          <view class="card-header">
            <text class="title">{{ item.instTitle || '未命名流程' }}</text>
            <text class="status-tag" :class="item.isFinish == '10' ? 'status-done' : 'status-undo'">
              {{ item.isFinish == '10' ? '已完成' : '未完成' }}
            </text>
          </view>
          <view class="card-body" @click="viewDetail(item)">
            <view class="info-item">
              <text class="label">审批类型：</text>
              <text class="value">{{ (item as any).defName || '-' }}</text>
            </view>
            <view class="info-item">
              <text class="label">申请人：</text>
              <text class="value">{{ item.startUserName || '-' }}</text>
            </view>
            <view class="info-item">
              <text class="label">创建时间：</text>
              <text class="value">{{ formatDate(item.createdTime, 'YYYY-MM-DD HH:mm') }}</text>
            </view>
          </view>
          <view class="card-footer" v-if="currentType === 'approval'">
            <uv-button v-if="item.isFinish == '20'" type="primary" text="审批" size="small"
              customStyle="padding: 0 24rpx; height: 60rpx;" @click="openApprove(item)"></uv-button>
          </view>
        </view>

        <uv-load-more v-if="todoStore.list.length > 0 || loadStatus === 'loading'" :status="loadStatus"
          @loadmore="loadMore"></uv-load-more>
      </scroll-view>

      <uv-back-top :scrollTop="currentScrollTop" :bottom="100" :right="30" @click="backToTop"></uv-back-top>
    </view>

  </view>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { debounce } from 'lodash-es';
import { useTodoStore } from '@/store/modules/todo';
import { onRouterPush } from '@/utils/router';
import { formatDate } from '@/utils/date';
import type { TodoItem } from '@/types/todo';
import { TODO_TAB_LIST } from '@/constants/index';
import { useExecutionApi } from '@/api/execution';
import { useProjectApi } from '@/api/project';
import to from 'await-to-js';

const todoStore = useTodoStore();
const executionApi = useExecutionApi();
const projectApi = useProjectApi();

const tabList = ref(TODO_TAB_LIST);

const currentTab = ref(0);
const currentType = computed(() => tabList.value[currentTab.value].type);

const queryParams = ref({
  platformId: 100010,
  defName: '',
  instTitle: '',
  pageNum: 1,
  pageSize: 20,
  orderBy: ''
});

const scrollTopValue = ref(0);
const currentScrollTop = ref(0);
const isTriggered = ref(false);
const loadStatus = ref<'loadmore' | 'loading' | 'nomore'>('loadmore');

/**
 * 获取列表数据
 */
const fetchListData = async (reset = false) => {
  if (todoStore.loading) return;

  if (reset) {
    queryParams.value.pageNum = 1;
  }

  loadStatus.value = 'loading';
  const res = await todoStore.fetchList(currentType.value, queryParams.value, !reset);

  if (res.success) {
    if (todoStore.list.length >= todoStore.total) {
      loadStatus.value = 'nomore';
    } else {
      loadStatus.value = 'loadmore';
      queryParams.value.pageNum += 1;
    }
  } else {
    loadStatus.value = 'nomore';
  }

  if (reset) {
    isTriggered.value = false;
  }
};

const onTabChange = (e: any) => {
  currentTab.value = e.index;
  fetchListData(true);
};

// 监听查询条件变化
const debouncedFetchList = debounce(() => {
  fetchListData(true);
}, 500);

watch(() => queryParams.value.instTitle, () => {
  debouncedFetchList();
});

const onRefresh = async () => {
  isTriggered.value = true;
  await fetchListData(true);
};

const loadMore = async () => {
  if (loadStatus.value !== 'loadmore') return;
  await fetchListData(false);
};

const onScroll = (e: any) => {
  currentScrollTop.value = e.detail.scrollTop;
};

const backToTop = () => {
  scrollTopValue.value = currentScrollTop.value;
  nextTick(() => {
    scrollTopValue.value = 0;
  });
};

const viewDetail = (item: TodoItem) => {
  onRouterPush(`/pages/todo/detail?mode=view&id=${item.id || ''}&taskId=${item.taskId || ''}&taskCode=${item.businessCode || ''}&defCode=${item.defCode || ''}`);
};

const openApprove = async (item: TodoItem) => {
  // 审批前增加学术不端行为校验
  uni.showLoading({ title: '校验中...', mask: true });

  // 1. 获取参与者列表，找出发起人
  const [err, res] = await to(executionApi.getParticipantByProcInstID({ id: item.id }));

  if (err || !res?.data) {
    uni.hideLoading();
    // 如果获取失败，出于流程通畅考虑，直接跳转
    onRouterPush(`/pages/todo/detail?mode=approval&id=${item.id || ''}&taskId=${item.taskId || ''}&taskCode=${item.businessCode || ''}&defCode=${item.defCode || ''}`);
    return;
  }

  const participants = res.data as any[];
  const startUser = participants.find(p => p.type === 'start');
  const startUserId = startUser?.userId;

  if (!startUserId) {
    uni.hideLoading();
    onRouterPush(`/pages/todo/detail?mode=approval&id=${item.id || ''}&taskId=${item.taskId || ''}&taskCode=${item.businessCode || ''}&defCode=${item.defCode || ''}`);
    return;
  }

  // 2. 调用学术不端校验接口
  const [err2, res2] = await to(projectApi.checkUserViolationStatus({ personId: startUserId }));
  uni.hideLoading();

  if (!err2 && res2?.data?.hasViolation) {
    const { restrictions } = res2.data;
    let restrictionList = [];
    if (restrictions.limitProjectApply) restrictionList.push('限制项目申报');
    if (restrictions.limitFundApply) restrictionList.push('限制申请经费');
    if (restrictions.limitRewardApply) restrictionList.push('限制成为奖励对象');

    uni.showModal({
      title: '学术不端行为提醒',
      content: `发起人 [${startUser?.userName || '未知'}] 存在学术不端记录，已被限制：${restrictionList.join('、')}。`,
      confirmText: '我知道了',
      showCancel: false
    });
    // 不跳转
  } else {
    onRouterPush(`/pages/todo/detail?mode=approval&id=${item.id || ''}&taskId=${item.taskId || ''}&taskCode=${item.businessCode || ''}&defCode=${item.defCode || ''}`);
  }
};

onShow(() => {
  fetchListData(true);
});

onLoad(() => {
  // onLoad 只执行一次基础初始化
});
</script>

<style lang="scss" scoped>
.todo-container {
  height: calc(100vh - var(--window-top));
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  box-sizing: border-box;
}

.search-header {
  background-color: #fff;
  padding: 20rpx 30rpx 0;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
  position: sticky;
  top: 0;
  z-index: 99;

  .search-row {
    margin-bottom: 24rpx;
  }

  .type-tabs {
    margin-top: 10rpx;
  }
}

.list-container {
  padding: 30rpx;
  flex: 1;
  overflow: hidden;
  box-sizing: border-box;
}

.scroll-list {
  flex: 1;
  height: 100%;
}

.common-list-card {
  .card-header {
    .status-tag {
      &.status-done {
        color: #52c41a;
        background-color: rgba(82, 196, 26, 0.1);
      }

      &.status-undo {
        color: #fa8c16;
        background-color: rgba(250, 173, 20, 0.1);
      }
    }
  }
}
</style>
