<!-- 首页 -->
<template>
  <div class="top-bg">
    <div class="top-header">
      <span class="top-title">安全管理信息系统</span>
      <van-icon name="bell" size="30" color="#fff" :badge="requiredScheduleCount" @click="router.push('/pendingMatters')" />
    </div>
  </div>
  <div class="stat-card-group">
    <div class="stat-card stat-card-blue">
      <div class="stat-card-label">履职</div>
      <div class="stat-card-desc">新增履职</div>
      <div class="stat-card-num">{{ performDutiesTodayCount }}</div>
    </div>
    <div class="stat-card stat-card-cyan">
      <div class="stat-card-label">作业</div>
      <div class="stat-card-desc">新增作业</div>
      <div class="stat-card-num">{{ jobTodayCount }}</div>
    </div>
    <div class="stat-card stat-card-red">
      <div class="stat-card-label">隐患</div>
      <div class="stat-card-desc">新增隐患</div>
      <div class="stat-card-num">{{ hiddenDangerTodayCount }}</div>
    </div>
  </div>
  <div class="app-grid">
<!--    <div class="stat-data-title">应用中心</div>-->
    <div class="app-grid-item" v-for="(item,idx) in functionList" :key="idx">
      <img :src="item.img" class="app-grid-icon" @click="router.push({ path: item.jumpPath })" />
      <div class="app-grid-text">{{ item.title }}</div>
    </div>
  </div>
  <div class="notice-card" @click="router.push('/pendingMatters')">
    <div v-if="toDoList" class="notice-row" v-for="(item,idx) in toDoList" :key="idx">
      <span class="notice-tag notice-tag-blue">{{ item.type === '0' ? '待办' : '已办' }}</span>
      <span class="notice-dot" :class="item.type === '0' ? 'notice-dot-red' : 'notice-dot-yellow'"></span>
      <span class="notice-text">{{ item.title }}</span>
      <span class="notice-date">{{ item.time }}</span>
    </div>
    <div v-else class="notice-row">
      <span class="notice-dot notice-dot-yellow"></span>
      <span class="notice-text">暂无隐患</span>
    </div>
  </div>
  <div class="notice-card" @click="router.push('/annex')">
    <div class="stat-data-title">安全文件</div>
    <div v-if="fileList" class="notice-row" v-for="(item,idx) in fileList" :key="idx">

  <span class="notice-text">
  {{ item.fileName }} &nbsp;- {{ item.fileSubmit }}
</span>

      <span class="notice-date">{{ item.fileContent }}</span>
    </div>
    <div v-else class="notice-row">
      <span class="notice-dot notice-dot-yellow"></span>
      <span class="notice-text">暂无隐患</span>
    </div>
  </div>

  <div class="stat-data-card">
    <div class="stat-data-title">安全管理数据统计</div>
    <div class="stat-data-list">
      <div class="stat-data-item">
        <div class="stat-data-left">
          <span class="stat-data-icon">
            <img src="../../public/images/c1.png" />
          </span>
          <span class="stat-data-label">隐患排查总数</span>
        </div>
        <span class="stat-data-value">{{ hdAllTotal }}</span>
      </div>
      <div class="stat-data-item">
        <div class="stat-data-left">
          <span class="stat-data-icon">
            <img src="../../public/images/c2.png" />
          </span>
          <span class="stat-data-label">本月答题人数</span>
        </div>
        <span class="stat-data-value">{{ numOfRespondentsThisMonthTotal }}</span>
      </div>
      <div class="stat-data-item">
        <div class="stat-data-left">
          <span class="stat-data-icon">
            <img src="../../public/images/c3.png" />
          </span>
          <span class="stat-data-label">职工履职总数</span>
        </div>
        <span class="stat-data-value">{{ empPerformanceTotal }}</span>
      </div>
      <div class="stat-data-item">
        <div class="stat-data-left">
          <span class="stat-data-icon">
            <img src="../../public/images/c4.png" />
          </span>
          <span class="stat-data-label">安全制度发布</span>
        </div>
        <span class="stat-data-value">{{ allInstitutionRegimeCount }}</span>
      </div>
      <div class="stat-data-item">
        <div class="stat-data-left">
          <span class="stat-data-icon">
            <img src="../../public/images/c5.png" />
          </span>
          <span class="stat-data-label">作业总数</span>
        </div>
        <span class="stat-data-value">{{ allOemOverhaulPlanCount }}</span>
      </div>
      <div class="stat-data-item">
        <div class="stat-data-left">
          <span class="stat-data-icon">
            <img src="../../public/images/c6.png" />
          </span>
          <span class="stat-data-label">剩余待办</span>
        </div>
        <span class="stat-data-value">{{ requiredScheduleCount }}</span>
      </div>
    </div>
  </div>
  <div class="stat-data-card">
    <div class="stat-data-title">隐患类型统计</div>
    <v-chart ref="pieChartRef" :option="pieOption" style="height: 240px; width: 100%;" />
  </div>
  <van-popup
    v-model:show="showBottom"
    closeable
    position="bottom"
    :style="{ height: '30%' }"
    @click-close-icon="closePopup"
  >
    <div class="popup-notice-content" v-if="currentNotice">
      <div class="popup-notice-title">{{ currentNotice.processInstanceId }}</div>
      <div class="popup-notice-body">{{ currentNotice.tContent }}</div>
      <div class="popup-notice-time">{{ currentNotice.addTime }}</div>
    </div>
    <div v-else class="popup-notice-empty">暂无通知</div>

    <!-- 确定按钮 -->
    <div class="popup-confirm-btn" @click="handleNextNotice">确定</div>
  </van-popup>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted,computed} from 'vue';
import { use } from 'echarts/core';
import { PieChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { LegendComponent, TooltipComponent } from 'echarts/components';
import VChart from 'vue-echarts';
import { useRouter } from 'vue-router';
import { showFailToast } from 'vant';

const {
  proxy
} = getCurrentInstance();
const router = useRouter();

use([PieChart, CanvasRenderer, LegendComponent, TooltipComponent]);
/**
 * 弹框（通知公告）
 */
const noticeList = ref([]);
const queryNoticeList =async () => {
  var url = 'sgsafe/Notice/queryNoticeByUser';
  var params = {
    userCode: localStorage.getItem('userCode')
  };
  const res = await proxy.$axios.get(url, params);
  if (res.data.code == 0) {
     noticeList.value = res.data.data;
    openNoticePopup()
  }
}


// 新增状态
const showBottom = ref(false);
const currentIndex = ref(0); // 当前显示第几条
const currentNotice = computed(() => {
  if (noticeList.value && noticeList.value.length > 0 && currentIndex.value < noticeList.value.length) {
    return noticeList.value[currentIndex.value];
  }
  return null;
});
// 打开弹窗（从第0条开始）
const openNoticePopup = () => {
  console.log(noticeList.value);
  if (noticeList.value && noticeList.value.length > 0) {
    currentIndex.value = 0;
    showBottom.value = true;
  }
};

// 点击“确定”：显示下一条 或 关闭
const handleNextNotice = () => {
  const nextIndex = currentIndex.value + 1;
  if (nextIndex < noticeList.value.length) {
    currentIndex.value = nextIndex;
  } else {
    // 已到最后一条，关闭弹窗
    showBottom.value = false;
    currentIndex.value = 0; // 重置
  }
};

// 点击右上角 × 也重置
const closePopup = () => {
  currentIndex.value = 0;
};
/**
 * 用于查询隐患排查的总数 hdAllTotal
 */
const hdAllTotal = ref(0);
const queryHdAllTotal = () => {
  var url = 'sgsafe/Hiddendanger/queryHdAllTotal';
  var params = {};
  proxy.$axios.get(url, params).then(response => {
    if (response.data.code == 0) {
      hdAllTotal.value = response.data.data;
    }
  });
};

/**
 * 用于职工履职记的总数 empPerformanceTotal
 */
const empPerformanceTotal = ref(0);
const queryEmpPerformanceTotal = () => {
  var url = 'sgsafe/RecordItems/queryEmpPerformanceTotal';
  var params = {};
  proxy.$axios.get(url, params).then(response => {
    if (response.data.code == 0) {
      empPerformanceTotal.value = response.data.data;
    }
  });
};

/**
 * 用于获取作业总数
 */
const allOemOverhaulPlanCount = ref(0);
const queryAllOemOverhaulPlanCount = () => {
  const url = '/sgsafe/OemOverhaulPlan/allCount';
  const params = {};
  proxy.$axios.get(url, params).then(response => {
    if (response.data.code === 0) {
      allOemOverhaulPlanCount.value = response.data.data;
    }
  });
};

/**
 * 用于本月答题人次总数 numOfRespondentsThisMonthTotal
 */
const numOfRespondentsThisMonthTotal = ref(0);
const queryNumOfRespondentsThisMonthTotal
  = () => {
  var url = 'sgsafe/ExamHead/queryNumOfRespondentsThisMonthTotal';
  var params = {};
  proxy.$axios.post(url, params).then(response => {
    if (response.data.code == 0) {
      numOfRespondentsThisMonthTotal.value = response.data.data;
    }
  });
};

/**
 * 用于获取安全制度总数
 */
const allInstitutionRegimeCount = ref(0);
const queryAllInstitutionRegimeCount = () => {
  const url = '/sgsafe/InstitutionRegimeMaster/allCount';
  const params = {};
  proxy.$axios.get(url, params).then(response => {
    if (response.data.code === 0) {
      allInstitutionRegimeCount.value = response.data.data;
    }
  });
};

/**
 * 获取待办
 */
const toDoList = ref([]);
const getUserSchedule = () => {
  const url = '/sgsafe/ToDoList/queryToDoListByUserId';
  const param = {
    userId: localStorage.getItem('userId')
  };
  proxy.$axios.get(url, param).then(res => {
    toDoList.value = res.data.data.map(item => ({
      title: item.title,
      time: formatTimestamp(item.startTime),
      type: item.dealFlag
    }));
    requiredScheduleCount.value = getRequiredScheduleCount(toDoList.value);
    toDoList.value = toDoList.value.slice(0, 2);
  });
};
/**
 * 文件管理
 */
const fileList = ref([]);
const queryfile = ref({
  fileId:'',
  fileName:'',
  fileType:'',
  fileSubmit:''
})
const getfileData= () => {
  var url = '/sgsafe/ResponFile/query1'
  var param = {
    page: 1,
    rows: 3,
    params: JSON.stringify(queryfile.value)
  }
  proxy.$axios.get(url, param).then(res => {
    fileList.value = res.data.data.records
  });
};


/* 获取剩余待办总数 */
const requiredScheduleCount = ref(0);
const getRequiredScheduleCount = (toDoList) => {
  const requiredList = toDoList.filter(item => item.type === '0');
  return requiredList.length;
};

const formatTimestamp = (timestamp) => {
  const date = new Date(Number(timestamp));
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

/**
 * 获取当天新增履职
 */
const performDutiesTodayCount = ref(0);
const queryPerformDutiesCount = () => {
  const url = '/sgsafe/ItemsResult/queryNewDayCount';
  const params = {};
  proxy.$axios.get(url, params).then(response => {
    if (response.data.code === 0) {
      performDutiesTodayCount.value = response.data.data;
    }
  });
};

/**
 * 获取当天新增隐患
 */
const hiddenDangerTodayCount = ref(0);
const queryHiddenDangerCount = () => {
  const url = '/sgsafe/Hiddendanger/queryNewDayCount';
  const params = {};
  proxy.$axios.get(url, params).then(response => {
    if (response.data.code === 0) {
      hiddenDangerTodayCount.value = response.data.data;
    }
  });
};

/**
 * 获取当天新增作业
 */
const jobTodayCount = ref(0);
const queryJobTodayCount = () => {
  const url = '/sgsafe/OemOverhaulPlan/queryNewDayCount';
  const params = {};
  proxy.$axios.get(url, params).then(response => {
    if (response.data.code === 0) {
      jobTodayCount.value = response.data.data;
    }
  });
};

onMounted(() => {
  queryPerformDutiesCount();
  queryJobTodayCount();
  queryHiddenDangerCount();

  queryHdAllTotal();
  queryEmpPerformanceTotal();
  queryAllOemOverhaulPlanCount();
  queryNumOfRespondentsThisMonthTotal();
  queryAllInstitutionRegimeCount();
  getUserSchedule();
  queryMenuRecently();

  getQuerySumByType();
  getfileData()
  queryNoticeList()

});

const pieChartRef = ref(null);

const chartData = ref([]);

const pieOption = ref({});
let myChart = null;
const getQuerySumByType = async () => {
  var url = '/sgsafe/Hiddendanger/querySumByType1';
  var param = {};

  const response = await proxy.$axios.get(url, param);

  if (response.data.code === 0) {
    chartData.value = response.data.data.map(item => ({
      name: item.hd_type,
      value: item.total
    }));

    pieOption.value = {
      tooltip: { trigger: 'item' },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: [
          '物的不安全状态',
          '人的不安全行为',
          '管理缺陷',
          '环境因素'
        ]
      },
      color: ['#20D4B4', '#FEA346', '#409EFF', '#FF6B5B'],
      series: [
        {
          name: '隐患类型',
          type: 'pie',
          radius: ['25%', '50%'],
          center: ['35%', '45%'],
          avoidLabelOverlap: false,
          padAngle: 2,
          itemStyle: {
            borderRadius: 5
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}'
          },
          labelLine: {
            show: true,
            length: 20,
            length2: 10
          },
          data: chartData.value
        }
      ]
    }
  } else {
    showFailToast('操作失败！' + response.data.msg);
  }
};

/**
 * 获取最近使用页面记录
 */
const functionList = ref([]);
const coincideNotList = ref([]);
const queryMenuRecently = () => {
  const url = '/sgsafe/MenuRecentlyUsed/queryRecentlyUsed';
  const param = {
    applicationId: 'c77da6a732d34400b24374e2cea811ee'
  };
  proxy.$axios.get(url, param).then(res => {
    functionList.value = res.data.data.map(item => ({
      title: item.menuName,
      img: 'images/' + item.menuIcon,
      jumpPath: item.jumpPath
    }));

    if (functionList.value.length < 7) {
      coincideNotList.value = defaultPageList.value
      for (let item of functionList.value) {
        coincideNotList.value = coincideNotList.value.filter(info => info.jumpPath !== item.jumpPath);
      }
      coincideNotList.value = coincideNotList.value.slice(0, 7 - functionList.value.length);
      functionList.value = [...functionList.value, ...coincideNotList.value];
    }

    functionList.value.push({
      title: '查看更多',
      img: 'images/gd.png',
      jumpPath: '/home2',
      // jumpPath: '/homeRole'
    })
  });

};
/**
 * 默认页面
 */
const defaultPageList = ref([
  { title: '隐患登记', img: 'images/yhdj.png', jumpPath: '/yinhuan/registration' },
  { title: '隐患台账', img: 'images/yh.png', jumpPath: '/yinhuan/hdLedger' },
  { title: '每日答题', img: 'images/dt.png', jumpPath: '/dailyproblem' },
  { title: '履职记录', img: 'images/lz.png', jumpPath: '/lvzhi' },
  { title: '安全制度管理', img: 'images/aqzd.png', jumpPath: '/institution/institutionRegime' },
  { title: '证件管理', img: 'images/zj.png', jumpPath: '/cardManager' },
  { title: '隐患待办', img: 'images/yhdb.png', jumpPath: '/yinhuan/todo' },
])

</script>

<style scoped>
.top-bg {
  position: relative;
  width: 100%;
  min-height: 160px;
  background-image: url('../../public/images/beijing.jpg');
  background-size: cover;
  background-repeat: no-repeat;
  overflow: hidden;
  border-radius: 0px 0px 50px 50px;
}

.top-header {
  position: relative;
  z-index: 2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 32px;
  padding-left: 20px;
  padding-right: 20px;
}

.top-title {
  color: #fff;
  font-size: 26px;
  font-weight: bold;
  letter-spacing: 2px;
  flex: 1;
  text-align: left;
}

.stat-card-group {
  position: relative;
  z-index: 3;
  margin: 0 auto;
  margin-top: -80px;
  display: flex;
  justify-content: space-between;
  gap: 10px;
  width: 90%;
  max-width: 700px;
  background: #ffffff;
  border-radius: 20px;
  box-shadow: 0 4px 24px rgba(32, 123, 230, 0.08);
  padding: 10px 10px 10px 10px;
}

.stat-card {
  flex: 1;
  border-radius: 10px;
  background: #f6faff;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  min-width: 0;
}

.stat-card-label {
  font-size: 15px;
  font-weight: 600;
  color: #fff;
  background: #207be6;
  border-radius: 10px 0px 10px 0px;
  padding: 2px 16px;
  margin-bottom: 8px;
}

.stat-card-blue .stat-card-label {
  background: #207be6;
}

.stat-card-cyan .stat-card-label {
  background: #2db7f5;
}

.stat-card-red .stat-card-label {
  background: #ff5b5b;
}

.stat-card-blue {
  background: #e7f2ff;
}

.stat-card-cyan {
  background: #eaf7fd;
}

.stat-card-red {
  background: #fff3f3;
}

.stat-card-desc {
  font-size: 15px;
  color: #333;
  margin-left: 10px;
  margin-bottom: 6px;
}

.stat-card-num {
  font-size: 28px;
  margin-left: 10px;
  font-weight: bold;
  color: #222;
}

.app-grid {
  margin: 15px auto 0 auto;
  width: 94%;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(32, 123, 230, 0.06);
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 18px 0;
  padding: 10px 0 18px 0;

}

.app-grid-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  /*min-width: 0;*/
}

.app-grid-icon {
  width: 45px;
  height: 45px;
/*  border-radius: 50%;*/
  margin-bottom: 8px;
  background: #f5f5f5;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(32, 123, 230, 0.08);
}

.app-grid-text {
  font-size: 16px;
/*  height: 40px;*/
  color: #333;
  margin-top: 2px;
  font-weight: 500;

/*  white-space: nowrap;*/

  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}

.notice-card {
  background: #ffffff;
  border-radius: 14px;
  box-shadow: 0 2px 12px rgba(32, 123, 230, 0.06);
  margin: 15px auto 0 auto;
  width: 90%;
  padding: 10px 10px 10px 10px;
}

.notice-row {
  display: flex;
  align-items: center;
  font-size: 16px;
  margin-bottom: 6px;
}

.notice-tag {
  font-size: 16px;
  font-weight: 600;
  padding: 2px 12px;
  border-radius: 8px;
  margin-right: 8px;
}

.notice-tag-blue {
  background: #207be6;
  color: #fff;
}

.notice-tag-gray {
  background: #ffffff;
  color: #222;
}

.notice-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 6px;
}

.notice-dot-yellow {
  background: #ffd600;
}

.notice-dot-red {
  background: #ff5b5b;
}

.notice-text {
  color: #333;
  flex: 1;
}

.notice-date {
  color: #888;
  font-size: 16px;
  margin-left: 10px;
}

.stat-data-card {
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px rgba(32, 123, 230, 0.06);
  margin: 15px auto 0 auto;
  width: 90%;
  padding: 10px 10px 10px 10px;
}

.stat-data-title {
  font-size: 17px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #222;
}

.stat-data-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 0;
}

.stat-data-item {
  width: 50%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0px;
}

.stat-data-left {
  display: flex;
  align-items: center;
}

.stat-data-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 2px;
  background: #eaf1ff;
}

.stat-data-icon img {
  width: 25px;
  height: 25px;
}

.stat-data-label {
  color: #000000;
  font-size: 14px;
}

.stat-data-value {
  color: #222;
  font-size: 16px;
  font-weight: bold;
  margin-left: 0px;
}
.notice-item {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 可选：设置子元素之间的间距 */
}
.popup-notice-content {
  padding: 20px;
  text-align: left;
}

.popup-notice-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.popup-notice-body {
  font-size: 15px;
  color: #666;
  line-height: 1.5;
  white-space: pre-wrap;
}

.popup-notice-time {
  font-size: 13px;
  color: #999;
  margin-top: 10px;
  text-align: right;
}

.popup-notice-empty {
  padding: 20px;
  text-align: center;
  color: #999;
}

.popup-confirm-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: #1989fa;
  color: white;
  text-align: center;
  padding: 12px 0;
  font-size: 16px;
  font-weight: bold;
  border-top: 1px solid #eee;
}
</style>
