<template>
  <div class="h5-container">
    <van-nav-bar title="学习课程小节">

      <template #right>
        <van-icon
          name="add"
          size="24"
          color="var(--van-nav-bar-icon-color)"
          @click="handAdd"
        />
        <van-popover
          v-model:show="showPopover"
          :actions="actions"
          placement="bottom-end"
          @select="onSelect"
        >
          <template #reference>
            <van-icon name="filter-o" size="24px" />
          </template>
        </van-popover>
      </template>
    </van-nav-bar>


    <!-- 项目列表 -->
    <van-pull-refresh v-model="isRefreshing" success-text="刷新成功" @refresh="onRefresh">
      <van-list v-model:loading="isLoading" :finished="isFinished" finished-text="没有更多了" offset="200" @load="onLoad">
        <div v-for="(item, idx) in resultData" :key="item.id">
          <van-swipe-cell title-style="color: #007aff" style="height: 80px;" :ref="el => getSwipeCellRef(el, idx)">
            <template #default>
              <div class="swipe-cell-default">
                <van-cell style="height: 100%; display: flex; align-items: center;" >
                  <template #title>
                    <div class="cell-title">
                      {{ item.sectionName }}
                    </div>
                  </template>
                  <template #label>
                    <div> 小节类型：{{ getProjectTypeName(item.studyorExam)}} </div>
                    <div style="width: 112px" :class="getStatusClass(item.isFinish)">
                      状态：
                      <span v-if="item.isFinish == '1'" style="width: 200px">已完成</span>
                      <span v-else-if="item.isFinish == '2'" style="width: 200px">不及格</span>
                      <span v-else>未完成</span>
                    </div>
                  </template>
                </van-cell>
                <div class="swipe-cell-default-icon">
                  <van-icon v-if="openStatus[idx]" name="arrow-double-left" @click.stop="openSwipe(idx)" />
                  <van-icon v-else name="arrow-double-right" @click.stop="closeSwipe(idx)" />
                </div>
              </div>
            </template>

            <template #right>
              <div style="display: flex; align-items: center; justify-content: flex-end; height: 100%;">
                <van-button v-if="item.studyorExam =='study'" @click="goaddLearn(item)" class="red-rounded-box-wide" text="学习"/>
                <van-button
                  v-if="item.isFinish === '1'"
                  @click="openWrongRecord(item)"
                  class="red-rounded-box-wide"
                  text="错题集"
                />
                <van-button v-else-if="item.studyorExam =='exam'"  @click="goaddPeo(item)" class="red-rounded-box-wide" text="考试"/>
              </div>
            </template>
          </van-swipe-cell>
        </div>

      </van-list>
    </van-pull-refresh>
    <QuizResultPopup
      v-model:show="showWrongPopup"
      :course-id="selectedCourseId"
      :user-id="userId"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick, toRaw } from 'vue';
import { Dialog, showDialog, showSuccessToast, showToast, Toast } from 'vant';
import QuizResultPopup from '@/components/QuizResultPopup.vue'; // 路径按你实际的改
const { proxy } = getCurrentInstance();





const route = useRoute()
const rouData =ref({})
rouData.value = JSON.parse(route.query.data)



// 将字符串转为 Date 对象进行比较
const parseDate = (str) => {
  if (!str) return null;
  // 支持 "YYYY-MM-DD HH:mm:ss" 或 ISO 格式
  return new Date(str);
};


// 当前时间是否在 fromDate 之前（未开始）
const isBefore = (fromDateStr) => {
  const now = new Date();
  const fromDate = parseDate(fromDateStr);
  return fromDate && now < fromDate;
};

// 当前时间是否在 toDate 之后（已结束）
const isAfter = (toDateStr) => {
  const now = new Date();
  const toDate = parseDate(toDateStr);
  return toDate && now > toDate;
};




const getProjectTypeName = (code) => {
  const map = {
    'exam': '考试',
    'study': '学习',


  };
  return map[code] || '未知类型';
}
const onClickLeft = () => {
  history.back();
};

var userId = localStorage.getItem('userId')
const switchIconState = (idx) => {
  openStatus.value[idx] = !openStatus.value[idx]
  openStatus.value = new Array(resultData.value.length).fill(true);
}

// const onClickRight = () =>{
//   searchShow.value = !searchShow.value;
// }

const searchShow = ref(false);

/**
 时间
 */
// 当前年份
const currentYear = new Date().getFullYear();

// 生成年份：往前3年，往后1年 → 共5年
const yearRange = Array.from({ length: 5 }, (_, i) => currentYear - 3 + i);

// 构造 actions（符合 van-popover 要求）
const actions = yearRange.map(year => ({
  text: `${year}年`
}));

// 默认选中的年份（用于请求）
const selectedYear = ref(currentYear);

// 控制 popover 显示（可选，你用了 v-model:show 就够了）
const showPopover = ref(false);

// 选择回调
const onSelect = (action, index) => {
  query.value.year = yearRange[index];
  // 👇 触发刷新（带上 selectedYear）
  console.log(selectedYear.value);
  resetAndRefresh();
};
const query = ref({
  year: currentYear, // ← 默认就是今年
  name: '',
});

// 重置并刷新（你已有类似逻辑）
const resetAndRefresh = () => {
  isFinished.value = false;
  isLoading.value = false;

  resultData.value = [];
  onRefresh();
};

function formatDate(date, format) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();

  return format
    .replace('yyyy', year)
    .replace('MM', month.toString().padStart(2, '0'))
    .replace('dd', day.toString().padStart(2, '0'))
    .replace('HH', hours.toString().padStart(2, '0'))
    .replace('mm', minutes.toString().padStart(2, '0'))
    .replace('ss', seconds.toString().padStart(2, '0'));
}

const tableData = ref([]);
const selectedRows = ref([]);
const dialogVisibleLook = ref(false);
const deleteDialogVisible = ref(false);
const currentDeleteItem = ref([]);
const dialogVisible = ref(false);
const dialogVisibleFile = ref(false);
const date = ref(null);

const kz = ref(true);
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();

const handAdd =  () => {

  router.push({ path: "/checkList",
    query: {
      mark:-1
    } });

};
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
const todayStr = `${year}-${month}-${day}`;
const goaddPeo =async (item) => {
  //在这的时候生成题目
  await prepareQuizData(item.id)

  router.push({
    path: "/line",
    query: {
      courseId: item.id,
      userId: userId,
      todayStr: todayStr,

    },
  });
}
const goaddLearn =async (item) => {
  router.push({
    path: '/learning1',
    query: {
      data: JSON.stringify(item)
    }
  })
}

const showWrongPopup = ref(false);
const selectedCourseId = ref('');
const openWrongRecord = (item) => {
  selectedCourseId.value = item.id; // 或 item.courseId，看你字段名
  showWrongPopup.value = true;
};

const openWrongQuestions = async (item) => {
  // 1. 先获取该小节的所有题目（和你 goaddPeo 里 prepareQuizData 一样）
  await prepareQuizData(item.id);

  // 2. 模拟或获取用户的答题记录（你可能需要调另一个接口）
  //    假设你已经有 userAnswers 数据结构，或者可以从本地/接口获取
  //    这里我们假设有一个 getUserAnswers(sectionId) 方法

  const userAnswers = await getUserAnswers(item.id); // ← 你需要实现这个！

  // 3. 把题目 + 用户答案 + 得分等传给弹窗
  currentSectionWrongData.value = {
    questions: questionData.value,
    userAnswers: userAnswers,
    totalScore: calculateScore(questionData.value, userAnswers), // 你自己的评分逻辑
    sectionName: item.sectionName
  };

  // 4. 显示弹窗
  showWrongQuestionsPopup.value = true;
};








const  questionData=ref([])
const prepareQuizData = async (sectionId) => {

  var url = '/sgsafe/Class/getQuestionBysectionId'
  var param = {

    params: sectionId
  }
  const response = await proxy.$axios.get(url, param)
  if (response.data.code == '0') {
    questionData.value = response.data.data
    console.log(questionData.value)

  }

}

const edits = (row) => {
  kz.value = true;
  form.value = { ...row };
  router.push({ path: "/checkList",
    query: {
      mark:1,
      data:JSON.stringify(form.value)
    } });
};
// 定义表单数据
const form = ref({
  hdPicId: '',
  hdId: '',
  hdType: '',
  discoveryTime: '',
  hdSubtype: '',
  discoverer: '',
  discovererOther: '',
  hdDescription: '',
  hdLevel: '',
  bz: '',
  hdLocation: '',
  picBefore: '',

  equipmentId: '',
  hdmanageLevel: '',
  handlingProcesses: '',
  companyId: '',
  repairLeader: '',
  repairOther: '',
  repairSuggest: '',
  repairDdl: '',
  repairDept: '',
  acceptLeader: '',
  acceptOther: '',
  picAfter: '',
  picTemp: '',
  repairDescription: '',
  discovererDept: '',
  discovererDeptCode: '',
  hdLocationCode: '',
  hdLocationName: '',

  status: '',


  hdSelect: '正常登记',
  id: ''
});
const resetForma = () => {
  form.value = {
    hdPicId: '',
    hdId: '',
    hdType: '',
    discoveryTime: '',
    hdSubtype: '',
    discoverer: '',
    discovererOther: '',
    hdDescription: '',
    hdLevel: '',
    bz: '',
    hdLocation: '',
    picBefore: '',

    equipmentId: '',
    hdmanageLevel: '',
    handlingProcesses: '',
    companyId: '',
    repairLeader: '',
    repairOther: '',
    repairSuggest: '',
    repairDdl: '',
    repairDept: '',
    acceptLeader: '',
    acceptOther: '',
    picAfter: '',
    picTemp: '',
    repairDescription: '',
    status: '',
    discovererDept: '',
    discovererDeptCode: '',
    hdLocationCode: '',
    hdLocationName: '',

    hdSelect: '正常登记',
    id: ''
  };
};

const isRefreshing = ref(false);
const isLoading = ref(false);
const isFinished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRows = ref(0);
const resultData = ref([]);

const dept=localStorage.getItem("dept")[0].deptCode;
const getTableData = async () => {

  const url = '/sgsafe/Class/querySectionList'
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: rouData.value.id
  };
  const response = await proxy.$axios.get(url, param);
  if (response.data.code === 0) {
    tableData.value = response.data.data.records;
    totalRows.value = response.data.data.total;
  } else {
    showToast({
      type: 'error',
      message: '操作失败！' + response.data.msg
    });
  }
};
const ruleIds = ref([]);
const getRuleId = () => {
  var url = '/sgsafe/ExamHead/getCheckRuleId'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      ruleIds.value = response.data.data
    } else {
      console.log("1111111");
    }
  })
  console.log('ruleIds', ruleIds)
}

const onRefresh = () => {
  basicReset();
  onLoad();
};

const onLoad = async () => {
  if (isRefreshing.value) {
    resultData.value = [];
    currentPage.value = 1;
    isRefreshing.value = false;
  }
  try {
    await getTableData();
    await getRuleId()
    if (pageSize.value * currentPage.value < totalRows.value) {
      resultData.value = [...resultData.value, ...tableData.value];
      openStatus.value = new Array(resultData.value.length).fill(true);
      currentPage.value++;

    } else {
      resultData.value = [...resultData.value, ...tableData.value];
      openStatus.value = new Array(resultData.value.length).fill(true);
      isFinished.value = true;
    }
  } catch (error) {
    console.log(error);
    isFinished.value = true;
  } finally {
    isLoading.value = false;
  }
};
/* 通用方法： 重置list数据 */
const basicReset = () => {
  isFinished.value = false;
  isLoading.value = true;
  currentPage.value = 1;
  resultData.value = [];
};

/*onMounted(() => {
  handleSearch();
});

const handleSearch = () => {
/!*  currentPage.value = 1;
  isFinished.value = false;
  tableData.value = [];*!/
  basicReset()
  onLoad()
};*/

const handdelect = () => {
  query.value.checkName = '';
  onRefresh()
};

const handleDetailLook = (row) => {
  form.value = { ...row };
  proxy.$router.push({
    name: 'taiZhang_detail',
    query: {
      form: form.value.id
    }
  });
  // dialogVisibleLook.value = true;
};
const deleteData=ref({})

const handleDelete = (item) => {
  deleteData.value=item
  deleteData.value.cancelFlag='1'
  var url = '/sgsafe/EduCheckMaster/save';
  var param = {
    json: JSON.stringify(item)
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      showSuccessToast("删除成功")
      onRefresh();

    } else {
    }

  })
};







const resetForm = () => {
  form.value = {
    projectName: '',
    projectLeader: '',
    phone: '',
    dept: ''
  };
};



//处理人员code
const repairLL = ref('');
const repairOO = ref('');
const acceptLL = ref('');
const orJsons = () => {
  // console.log('forms',form.value)
  if (form.value.hdSelect === '正常登记') {
    nextTick(() => {
      nextTick(() => {
        repairLL.value = qq('repairLL', form.value.discoverer);//隐患发现人
        nextTick(() => {
          repairOO.value = qq('repairOO', form.value.discovererOther);//其他隐患发现人
          nextTick(() => {
            acceptLL.value = qq('acceptLL', form.value.discoverer);//隐患销号人
          });
        });
      });

      // acceptOO.value = qq('acceptOO', form.value.acceptOther)
    });
  } else {
    // console.log('noiajdoifjpoewjfopjp')
    nextTick(() => {
      nextTick(() => {
        repairLL.value = qq('repairLL', form.value.acceptLeader);//隐患发现人
        nextTick(() => {
          repairOO.value = qq('repairOO', form.value.acceptOther);//其他隐患发现人
          nextTick(() => {
            acceptLL.value = qq('acceptLL', form.value.discoverer);//隐患销号人
          });
        });
      });

      // acceptOO.value = qq('acceptOO', form.value.acceptOther)
    });
  }
};

const jsons = ref({});
const qq = (a, val) => {
  let aa = '';
  var url = 'sgsafe/Hiddendanger/qqId';
  var param = {
    params: val
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {

      aa = response.data.data;
      switch (a) {
        case 'repairLL':
          repairLL.value = response.data.data;
          // console.log('repairLL',repairLL.value);
          break;
        case 'repairOO':
          repairOO.value = response.data.data;
          // console.log('repairOO',repairLL.value);
          break;
        case 'acceptLL':
          acceptLL.value = response.data.data;
          // console.log('acceptLL',repairLL.value);
          break;
        default:
          break;
      }
      jsons.value = {
        hdConfirm: repairLL.value,
        hdConfirmO: repairOO.value,
        hdCancel: acceptLL.value
      };

      // 处理函数
      function processValue(value) {
        // 将逗号替换为分号
        const replacedValue = value.replace(/,/g, ';');
        // 分割值
        const parts = replacedValue.split(';');
        // 每个部分前加上 U_
        const processedParts = parts.map(part => `U_${part.trim()}`);
        // 重新组合
        return processedParts.join(';');
      }

      // 处理整个对象
      const processedData = {};
      for (const key in jsons.value) {
        if (jsons.value.hasOwnProperty(key)) {
          processedData[key] = processValue(jsons.value[key]);
        }
      }

      console.log('对象', toRaw(processedData));

      let b = {
        acceptL: processedData.hdConfirm,
        acceptO: processedData.hdConfirmO,
        id: form.value.id
      };

      if (form.value.hdSelect === '即查即改') {
        b = {
          hdFxr: processedData.hdCancel,
          id: form.value.id
        };
      }

      if (form.value.hdSelect === '正常登记') {
        b = {
          // hdConfirm: processedData.hdConfirm,
          // hdConfirmO: processedData.hdConfirmO,
          id: form.value.id
        };
      }

      const aaa = JSON.stringify(toRaw(b));
      sessionStorage.setItem('variables', aaa);
      console.log('aaa', aaa);
    } else {
      showToast({
        type: 'fail',
        message: '操作失败！' + response.data.msg
      });
    }
  });
  return aa;
};

const reback = () => {
  // 返回逻辑
};

const deleteRow = (row) => {
  selectedRows.value = [row];
  handleDelete(row);
};

const deleteRowa = (row) => {
  deleteRow(row);
};

const bm = (val) => {
  // 部门选择逻辑
};

//提交审批流程
import { workflowSubmit, workflowCancel } from '@/tools/workflow.js';

const flowId = ref('');
flowId.value = 'hazardManagementFlowId';


const getStatusClass = (status) => {
  switch (status) {
    case '1':
      return 'status-rectifying';
    case '2':
      return 'status-closed';
    default:
      return 'status-analyzing';
  }
};

/**
 * 按钮实现swipe-cell滑动
 */
const openStatus = ref([])
const swipeCellRefs = ref([])
const getSwipeCellRef = (el, index) => {
  if (el) {
    swipeCellRefs.value[index] = el;
  }
}
const openSwipe = (idx) => {
  openStatus.value = new Array(resultData.value.length).fill(true);
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStatus.value[idx] = false
    swipeCellRefs.value[idx].open('right')
  }
  document.addEventListener('click', handleDocumentClick)
}
/**
 * 当点击滑动单元格时，开始监听点击事件
 */
const handleDocumentClick = (event) => {
  openStatus.value = new Array(resultData.value.length).fill(true);
}

const closeSwipe = (idx) => {
  if (idx >= 0 && idx < swipeCellRefs.value.length) {
    openStatus.value[idx] = true
    swipeCellRefs.value[idx].close()
  }
}

</script>

<style scoped>
.h5-container {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-registered {
  background-color: #d1ecf1;
  color: #0c5460;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-analyzing {
  background-color: #fff8e1;
  color: #ff8f00;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-rectifying {
  background-color: #e8f5e9;
  color: #2e7d32;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-accepting {
  background-color: #e3f2fd;
  color: #1565c0;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-closed {
  background-color: #f8bbd0;
  color: #b71c1c;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-finished {
  background-color: #e8eaf6;
  color: #311b92;
  padding: 2px 4px;
  border-radius: 4px;
}

.status-unknown {
  background-color: #efebe9;
  color: #424242;
  padding: 2px 4px;
  border-radius: 4px;
}

.cell-title {
  display: -webkit-box;
  /* 旧版弹性盒子模型 */
  -webkit-box-orient: vertical;
  /* 内容垂直排列 */
  -webkit-line-clamp: 2;
  /* 限制显示行数 */
  overflow: hidden;
  /* 超出隐藏 */
  text-overflow: ellipsis;
  /* 省略号 */
  line-height: 1.5;
  /* 可选：设置行高 */
  max-height: calc(1.5em * 2);
  /* 可选：根据行高限制最大高度 */
  font-size: 16px;
  font-weight: bold;
  color: #333;
  /* 字号 */
}

.swipe-cell-default {
  display: flex;
  background-color: #ffffff;
  justify-content: center;
  align-items: center;
}

.swipe-cell-default-icon {
  width: 60px;
  display: flex;
  justify-content: center;
}

.delete-button {
  height: 100%;
  border: none;
  color: #ff0000;
  background-image: url('@/assets/img/del.png');
  background-size: auto 100%;
  background-repeat: no-repeat;
}

.red-rounded-box-wide {
  width: 80px;           /* 可容纳3个字 */
  height: 36px;          /* 高度适中 */
  border: 2px solid #51e74c;
  border-radius: 18px;   /* 圆角 = 高度 / 2 → 完美胶囊形 */
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #07c160;
  background-color: transparent;
  box-sizing: border-box;
}

.submit-button {
  height: 100%;
  border: none;
  color: #07c160;
  background-image: url('@/assets/img/sub.png');
  background-size: auto 100%;
  background-repeat: no-repeat;
}

.subsuccess {
  height: 100%;
  border: none;
  color: #07c160;
  background-image: url('@/assets/img/sub1.png');
  background-size: auto 100%;
  background-repeat: no-repeat;
}
</style>
