<template>
  <home-container :customStyle="{backgroundPosition:'0px -65px'}">
    <div class="daily-task-container">
      <!-- 顶部个人信息栏 -->
      <view class="user-header" v-if="currentUser">
        <view class="user-avatar">
          <image v-if="currentUser.avatar" :src="currentUser.avatar" class="cu-avatar xl round"></image>
        </view>
        <view class="user-info">
          <text class="user-name">{{ `${userInfoAndRoles.nickName} ${userInfoAndRoles.userName}` }}</text>
          <text v-if="userInfo.userInfo.stationName" class="position-item">{{ userInfo.userInfo.stationName }}</text>
          <text v-if="userInfo.userInfo.stationName && userInfo.userInfo.departmentName" class="separator">/</text>
          <text v-if="userInfo.userInfo.departmentName" class="position-item">{{
            userInfo.userInfo.departmentName}}</text>
          <text v-if="userInfo.userInfo.departmentName && userInfo.userInfo.teamsName" class="separator">/</text>
          <text v-if="userInfo.userInfo.teamsName" class="position-item">{{ userInfo.userInfo.teamsName }}</text>
        </view>
      </view>
      <!--   <h-search v-model="keyword" placeholder="请输入题目名称" :showAction="true" actionText="搜索" 
                @search="handleSearch" @custom="handleSearch" @clear="handleClear" />-->


      <h-tabs v-model="currentTab" :tabs="tabList" value-key="type" label-key="title" @change="handleTabChange"
        style="margin-top: 60rpx;" />

      <div class="exam-list">
        <div v-for="item in filteredTaskList" :key="item.dtId" class="exam-item">
          <div class="exam-item-title">
            {{ formatBusinessDate(item.dtBusinessDate) }}
            <div :class="item.dtStatus" class="exam-item-status">
              {{ getStatusText(item.dtStatus) }}
            </div>
          </div>
          <div class="exam-item-desc">
            <div class="exam-item-desc-item time">{{ item.dtTimeLimit / 60 }}分钟</div>
          </div>
          <div class="exam-item-btn">
            <div class="exam-item-btn-score">
              <span>{{ item.questionCount || 0 }}题</span>
              <span v-if="item.dtStatus === 'COMPLETED'">
                <i>{{ item.dtTotalScore }}</i>
                /{{ item.fullScore }}分
              </span>
              <span v-if="item.dtStatus !== 'COMPLETED'">{{ item.fullScore }}分</span>
            </div>
            <span v-if="item.dtStatus === 'PENDING'" class="btn" @click="startTask(item)">开始答题</span>
            <span v-if="item.dtStatus === 'IN_PROGRESS'" class="btn" @click="continueTask(item)">继续答题</span>
            <span v-if="item.dtStatus === 'COMPLETED'" class="btn done" @click="viewResult(item)">查看结果</span>
            <span v-if="item.dtStatus === 'EXPIRED'" class="btn timeout">已过期</span>
          </div>
        </div>

        <div v-if="filteredTaskList.length === 0" class="empty-state">
          <div class="empty-icon">📋</div>
          <div class="empty-text">暂无答题任务</div>
          <div class="empty-desc">完成考勤打卡后将自动生成任务</div>
        </div>
      </div>
    </div>
  </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import { getMyTasks, hasPendingTask, getAllTasks, getPendingTasks, getCompletedTasks, getExpiredTasks } from "@/api/exam/dailyExam";
import { getInfo } from "@/api/login"

export default {
  components: { HomeContainer },
  computed: {
    currentUser() {
      return this.$store.state.user;
    },
    userInfoAndRoles() {
      return {
        ...this.userInfo.userInfo,
        roles: this.userInfo.roles
      }
    }
  },
  data() {
    return {
      taskList: [],
      filteredTaskList: [],
      keyword: '',
      currentTab: 'all',
      pageNum: 1,
      pageSize: 20,
      userInfo: {
        userInfo: {},
        roles: []
      },
      tabList: [
        {
          type: 'all',
          title: '全部'
        },
        {
          type: 'PENDING',
          title: '待答题'
        },
        {
          type: 'COMPLETED',
          title: '已完成'
        },
        {
          type: 'EXPIRED',
          title: '已过期'
        }
      ],
      statusMap: {
        PENDING: '待答题',
        IN_PROGRESS: '答题中',
        COMPLETED: '已完成',
        EXPIRED: '已过期'
      }
    }
  },
  async onLoad() {
    const userInfo = await getInfo()
    this.userInfo = userInfo || {}
    this.loadTaskList();
  },
  onShow() {
    // 每次显示页面时都重新加载任务列表，确保状态是最新的
    this.loadTaskList();
  },
  methods: {
    async loadTaskList() {
      try {
        let response;
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };

        // 根据当前tab选择不同的API接口
        switch (this.currentTab) {
          case 'all':
            response = await getAllTasks(params);
            break;
          case 'PENDING':
            response = await getPendingTasks(params);
            break;
          case 'COMPLETED':
            response = await getCompletedTasks(params);
            break;
          case 'EXPIRED':
            response = await getExpiredTasks(params);
            break;
          default:
            response = await getAllTasks(params);
        }

        this.taskList = response.rows || [];
        this.filterTaskList();
      } catch (error) {
        console.error('获取任务列表失败', error);
        uni.showToast({
          title: '获取任务列表失败',
          icon: 'none'
        });
      }
    },

    handleSearch(val) {
      if (!val) {
        this.filterTaskList();
        return;
      }
      // 本地模糊匹配
      this.filteredTaskList = this.taskList.filter(item =>
        this.formatBusinessDate(item.dtBusinessDate).includes(val)
      );
    },

    handleClear() {
      this.keyword = '';
      this.filterTaskList();
    },

    handleTabChange(tabType) {
      this.currentTab = tabType;
      this.pageNum = 1; // 重置页码
      this.loadTaskList(); // 重新请求数据
    },

    filterTaskList() {
      if (this.currentTab === 'all') {
        // 显示全部
        this.filteredTaskList = [...this.taskList];
      } else {
        // 只显示当前状态
        this.filteredTaskList = this.taskList.filter(item => item.dtStatus === this.currentTab);
      }

      // 如果有搜索关键词，进行过滤
      if (this.keyword) {
        this.filteredTaskList = this.filteredTaskList.filter(item =>
          this.formatBusinessDate(item.dtBusinessDate).includes(this.keyword)
        );
      }
    },

    formatDay(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.getDate();
    },

    formatMonth(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const month = date.getMonth() + 1;
      return `${month}月`;
    },

    formatBusinessDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}年${month}月${day}日`;
    },

    getStatusText(status) {
      return this.statusMap[status] || status;
    },

    getStatusClass(status) {
      const classMap = {
        PENDING: 'pending',
        IN_PROGRESS: 'in-progress',
        COMPLETED: 'completed',
        EXPIRED: 'expired'
      };
      return classMap[status] || '';
    },

    startTask(item) {
      uni.navigateTo({
        url: `/pages/daily-exam/answer/index?taskId=${item.dtId}&status=start`
      });
    },

    continueTask(item) {
      uni.navigateTo({
        url: `/pages/daily-exam/answer/index?taskId=${item.dtId}&status=continue`
      });
    },

    viewResult(item) {
      uni.navigateTo({
        url: `/pages/daily-exam/answer/index?taskId=${item.dtId}&status=result`
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.daily-task-container {
  padding: 0;
}

/* 顶部个人信息 */
.user-header {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 15px;
  margin-top: 50px;
  margin-bottom: 20px;
  height: 96px;
  background: #FFFFFF;
  box-shadow: 0px 4px 16px 0px rgba(0, 0, 0, 0.06);
  border-radius: 16px 16px 16px 16px;

  .user-avatar {
    width: 50px;
    height: 50px;
    border-radius: 25px;
    overflow: hidden;
    margin-right: 12px;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .user-info {
    flex: 1;

    .user-name {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      display: block;
      margin-bottom: 8px;
    }

    .position-item {
      font-size: 14px;
      color: #666;
    }

    .separator {
      font-size: 14px;
      color: #666;
      margin: 0 4px;
    }
  }
}



.exam-list {
  .exam-item {
    display: flex;
    flex-flow: column;
    justify-content: space-between;
    padding: 40rpx;
    background: #FFFFFF;
    box-shadow: 0 8rpx 20rpx 0 rgba(0, 0, 0, 0.08);
    border-radius: 16rpx;
    border: 2rpx solid #F0F8FF;
    margin-top: 32rpx;
  }

  .exam-item-title {
    display: flex;
    justify-content: space-between;
    font-size: 32rpx;
    color: #333333;
    line-height: 38rpx;

    .exam-item-status {
      background: rgba(42, 112, 209, 0.12);
      border-radius: 80rpx;
      padding: 8rpx 28rpx;
      font-size: 24rpx;
      color: #2A70D1;
      line-height: 28rpx;

      &.COMPLETED {
        background: rgba(78, 166, 26, 0.12);
        color: #4EA61A;
      }

      &.EXPIRED {
        background: rgba(234, 73, 73, 0.12);
        color: #EA4949;
      }
    }
  }

  .exam-item-desc {
    display: flex;
    gap: 48rpx;
    margin: 40rpx 0 30rpx;

    .exam-item-desc-item {
      display: flex;
      padding-left: 40rpx;
      position: relative;

      &:after {
        content: "";
        width: 32rpx;
        height: 32rpx;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        background: url("../../../static/images/clock-icon.png");
        background-size: 32rpx;
      }
    }
  }

  .exam-item-btn {
    display: flex;
    justify-content: space-between;
    font-size: 28rpx;
    color: #666666;
    line-height: 32rpx;
    align-items: flex-end;

    .exam-item-btn-score {
      display: flex;
      gap: 40rpx;
      align-items: flex-end;

      i {
        font-style: normal;
        font-size: 36rpx;
        color: #4CA518;
        line-height: 44rpx;
      }
    }

    .btn {
      padding: 10rpx 28rpx;
      background: #2A70D1;
      border-radius: 80rpx;
      font-size: 24rpx;
      color: #FFFFFF;
      line-height: 28rpx;
      border: 2px solid #FFFFFF;

      &.done {
        background: #FFFFFF;
        border-color: #2A70D1;
        color: #2A70D1;
      }

      &.timeout {
        background: #FFFFFF;
        border-color: #C4C4C5;
        color: #999999;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;

  .empty-icon {
    font-size: 120rpx;
    margin-bottom: 32rpx;
  }

  .empty-text {
    font-size: 32rpx;
    color: #666666;
    margin-bottom: 16rpx;
  }

  .empty-desc {
    font-size: 26rpx;
    color: #999999;
  }
}
</style>
