<template>
  <home-container>
    <div class="title">
      <user-info :name="checkerName" :sub-title="userInfo" />

      <div>
        <span class="btn">
          <img alt="" src="@/static/images/clock.png">{{ todayCheckInTime }}
        </span>
        <span class="btn">
          <img alt="" src="@/static/images/status.png">执勤中
        </span>
      </div>
    </div>

    <div class="tab">
      <div v-for="tab in tabs" :key="tab.id" :class="{ 'unread': tab.hasUnread, 'item': true }"
        @click="goToPage(tab.appUrl)">
        <img alt="" :src="tab.workbenchIcon">
        <view class="text">{{ tab.appName }}</view>
      </div>
    </div>
    <div class="work">
      <!-- <div class="item">
        <div class="text">
          一键报警
          <span>紧急情况</span>
        </div>
        <div class="icon"><img alt="" src="@/static/images/done.png"></div>
      </div> -->
      <div class="item" @click="goworkDocu">
        <div class="text">
          工作手册
          <span>查询规则制度</span>
        </div>
        <div class="icon"><img alt="" src="@/static/images/pending.png"></div>
      </div>
    </div>


    <Notice ref="notice" />
    <!--  今日待办  -->
    <!-- <myToDo /> -->

    <!--  最新公告  -->
    <announcement ref="announcement" />
    <!-- 
    <img alt="" class="banner" src="@/static/images/banner.png"> -->
    <!--  今日待办  -->
    <!-- <task /> -->
  </home-container>
</template>
<script>
import HomeContainer from "@/components/HomeContainer.vue";
import UserInfo from "@/components/UserInfo.vue";
import HeadTitle from "@/components/HeadTitle.vue";
import Announcement from "@/pages/home/components/announcement.vue";
import myToDo from "@/pages/home/components/myToDo.vue";
import Task from "@/pages/home/components/task.vue";
import Notice from "@/pages/home/components/notice.vue";
import { getUserProfile,getAppListByRoleId,getAppList } from "@/api/system/user";
import { getAttendanceList } from "@/api/attendance/attendance"
import { getUnreadCount } from "@/api/check/checkTask"
import { checkRolePermission } from "@/utils/common.js";

export default {
  components: { Task, Announcement, myToDo, HeadTitle, UserInfo, HomeContainer, Notice },
  data() {
    return {
      checkerId: this.$store.state.user.id,
      userInfo: '',
      todayCheckInTime: '未打卡',
      unreadCount: 0,
      appList: [] // 存储接口返回的应用列表
    }
  },
  computed: {
    checkerName() {
      if (this.$store.state.user) {
        if (this.$store.state.user.userInfo && this.$store.state.user.userInfo.nickName) {
          return this.$store.state.user.userInfo.nickName
        }
      }
      return this.$store.state.user.name
    },
    role() {
      return this.$store?.state?.user?.roles[0]
    },
    tabs() {
      // 如果接口返回了应用列表，则使用接口数据
      if (this.appList && this.appList.length > 0) {
        return this.appList.map((app, index) => {
          // 根据应用名称映射到对应的路径和图标
          return {
            ...app,
            showUnread: app.appName === '巡视检查' ? this.unreadCount > 0 : false
          };
        });
      }
    }
  },

  onShow() {

    this.updateCurrentDate();
    this.getUnreadCount()

    // 页面显示时，刷新子组件的数据 - 使用$nextTick确保DOM已渲染完成
    this.$nextTick(() => {
      console.log("notice====", this.$refs.notice)
      this.$refs.notice?.refreshData();
      this.$refs.announcement?.refreshData();
    });

  },
  onLoad() {
    this.getUser()
    this.loadTodayRecord();

  },
  methods: {

    goworkDocu() {
      uni.navigateTo({
        url: '/pages/workDocu/index'
      });
    },
    async getUnreadCount() {
      const res = await getUnreadCount();
      this.unreadCount = res.data
    },
    async getUser() {
      const data = await getUserProfile();
      console.log("data====", data)
      //data.postGroup + "  " +
      this.userInfo = data.data.dept.deptName
      await this.loadAppList(data.data);
      // this.formData.securityLocationText = data.data.dept.deptName
      // this.formData.positionText = data.postGroup
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const week = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()];
      return `${year}年${month}月${day}日 星期${week}`;
    },
    updateCurrentDate() {
      this.currentDate = this.formatDate(new Date());
    },
    handleGridClick(item) {
      console.log('点击了宫格：', item);
      if (item.path) {
        uni.navigateTo({
          url: item.path
        });
      } else {
        this.$modal.showToast('功能开发中，敬请期待');
      }
    },
    goToAttendance() {
      uni.navigateTo({
        url: '/pages/attendance/index'
      });
    },
    changeGrid(e) {
      const index = e.detail.index;
      const item = this.items[index];
      this.handleGridClick(item);
    },
    goToPage(path) {
      // if (checkRolePermission(this.role, path)) {
        uni.navigateTo({ url: path });
      // } else {
      //   this.$modal.showToast('此角色不需要查看该功能，无需操作～');
      // }
    },
    async loadAppList(userInfo) {
      // const roleId = userInfo.roles && userInfo.roles.length ? userInfo.roles[0].roleId : null;

      try {
        // if (roleId) {
          const res = await getAppList({homePage:1});
          if (res.code === 200) {
  
            this.appList = res.data;
          }
        // }
      } catch (error) {
        console.error('获取应用列表失败:', error);
        this.appList = [];
      }
    },



    async loadTodayRecord() {
      if (this.yesterday) {
        return;
      }
      const today = this.formatDate(new Date());
      const { data } = await getAttendanceList({
        type: 1,
        checkInDate: today,
        userId: this.$store.state.user.id
      });

      // 接口 data 可能是多条（按天），我们取第一条里的 items
      const todayData = data && data.length ? data[0] : null;
      const items = todayData ? todayData.items : [];
      const lastMorning = items.find(r => r.checkInType == 'CLOCK_IN');
      if (lastMorning) {
        console.log(lastMorning);
        this.todayCheckInTime = '已打卡  ' + lastMorning.checkInTime

      } else {

      }


    },
    // 日期格式化（昨天、今天查询用）
    formatDate(date) {
      const y = date.getFullYear();
      const m = String(date.getMonth() + 1).padStart(2, '0');
      const d = String(date.getDate()).padStart(2, '0');
      return `${y}-${m}-${d}`;
    },
  }
}
</script>

<style lang="scss" scoped>
img {
  display: inline-flex;
}

.title {
  padding: 40rpx 20rpx 20rpx;
}

.btn {
  display: inline-flex;
  align-items: center;
  padding: 10rpx 16rpx;
  font-weight: 400;
  font-size: 24rpx;
  color: #FFFFFF;
  line-height: 28rpx;
  background: rgba(255, 255, 255, 0.18);
  border-radius: 8rpx;

  img {
    display: inline-block;
    width: 32rpx;
    height: 32rpx;
  }

  &:not(:last-child) {
    margin-right: 48rpx;
  }
}

.tab {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 70rpx;
  background: #FFFFFF;
  box-shadow: 0 8rpx 32rpx 0 rgba(0, 0, 0, 0.06);
  border-radius: 32rpx;

  .item {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-flow: column;
    font-weight: 600;
    font-size: 20rpx;
    color: #3D3D3D;

    img {
      display: inline-block;
      width: 88rpx;
      height: 88rpx;
    }
    .text {
      margin-top: 10rpx;
    }
  }

  .unread {
    position: relative;
  }

  .unread::after {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 24rpx;
    height: 24rpx;
    background: #FF4D4F;
    border-radius: 50%;
  }
}

.work {
  display: flex;
  flex-shrink: 2;
  margin: 32rpx 0;
  gap: 26rpx;

  .item {
    justify-content: space-between;
    flex-grow: 1;
    display: flex;
    padding: 20rpx 30rpx 20rpx 40rpx;
    background: #FFFFFF;
    box-shadow: 0 8rpx 20rpx 0 rgba(0, 0, 0, 0.06);
    border-radius: 28rpx;
  }

  .text {
    display: flex;
    flex-flow: column;
    font-weight: bold;
    font-size: 32rpx;
    color: #3D3D3D;
    line-height: 44rpx;
    justify-content: center;

    span {
      margin-top: 12rpx;
      font-weight: 400;
      font-size: 24rpx;
      color: #999999;
      line-height: 28rpx;
    }
  }

  .icon {
    display: inline-flex;
    width: 112rpx;
    height: 112rpx;
  }
}

.tips {
  display: flex;
  align-items: center;
  padding: 16rpx 28rpx;
  background: #FFF4F4;
  border-radius: 32rpx;
  font-size: 24rpx;
  color: #222222;
  line-height: 28rpx;
  margin-bottom: 32rpx;

  img {
    width: 66rpx;
    padding-right: 28rpx;
    border-right: 1px solid rgba(0, 0, 0, 0.1);
    margin-right: 28rpx;
  }
}

.banner {
  width: 100%;
  margin-bottom: 32rpx;
}

</style>