<template>
  <div class="h5-container">
    <van-nav-bar title="小节管理" @click-left="onClickLeft">
      <template #right>
        <van-dropdown-menu>
          <van-dropdown-item v-model="addType" :options="addTypeOptions" @change="handleAddType" />
        </van-dropdown-menu>
      </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: flex-start;" @click="openTrain(item)">
                  <template #title>
                    <div class="cell-title">
                      {{ item.sectionName }}
                    </div>
                  </template>
                  <template #label>
                    <div>小节类型：{{ item.studyorExam }}</div>
                    <div v-if="item.studyorExam === 'study'">观看时长：{{ item.watchTime }} 分钟</div>
                    <div v-if="item.studyorExam === 'exam'">关联题库：{{ item.questionName }}</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>
              <van-button square class="edit-button" text="编辑" @click="openTrain(item)" />
              <van-button square class="delete-button" text="删除" @click="deleteRow(item)" />
            </template>
          </van-swipe-cell>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 考试弹窗 -->
    <van-popup v-model:show="examDialogVisible" round position="bottom" :style="{ height: '90%' }">
      <div class="popup-container">
        <van-nav-bar title="新增考试" left-arrow @click-left="examDialogVisible = false" />
        <div class="popup-content">
          <van-form @submit="submitStudy">
            <van-field
              v-model="form.sectionName"
              label="小节名称"
              name="sectionName"
              required
              placeholder="请输入小节名称"
              :rules="[{required: true, message: '请输入小节名称'}]"
            />

            <van-field
              v-model="form.sectionOrder"
              label="顺序"
              name="sectionOrder"
              type="number"
              required
              placeholder="请输入顺序"
              :rules="[{required: true, message: '请输入顺序'}]"
            />

            <van-field
              v-model="selectedQuestionText"
              readonly
              is-link
              label="关联题库"
              placeholder="请选择题库"
              @click="showQuestionPicker = true"
            />

            <van-field
              v-model="totalExamScoreText"
              label="试卷总分"
              readonly
            />

            <van-field
              v-model="form.singleChoice"
              label="单选数量"
              name="singleChoice"
              type="number"
              placeholder="请输入单选数量"
            />

            <van-field
              v-model="form.singleChoiceScore"
              label="每题分数"
              name="singleChoiceScore"
              type="number"
              placeholder="请输入每题分数"
            />

            <van-field
              v-model="totalScoreText"
              label="总分"
              readonly
            />

            <van-field
              v-model="form.multipleChoice"
              label="多选数量"
              name="multipleChoice"
              type="number"
              placeholder="请输入多选数量"
            />

            <van-field
              v-model="form.multipleChoiceScore"
              label="每题分数"
              name="multipleChoiceScore"
              type="number"
              placeholder="请输入每题分数"
            />

            <van-field
              v-model="totalChoiceText"
              label="总分"
              readonly
            />

            <van-field
              v-model="form.judge"
              label="判断数量"
              name="judge"
              type="number"
              placeholder="请输入判断数量"
            />

            <van-field
              v-model="form.judgeScore"
              label="每题分数"
              name="judgeScore"
              type="number"
              placeholder="请输入每题分数"
            />

            <van-field
              v-model="totaljudgeText"
              label="总分"
              readonly
            />

            <van-field
              v-model="form.qualifiedScore"
              label="及格分数"
              name="qualifiedScore"
              type="number"
              placeholder="请输入及格分数"
            />

            <div style="margin: 16px;">
              <van-button round block type="primary" native-type="submit">
                确定
              </van-button>
            </div>
          </van-form>

          <van-popup v-model:show="showQuestionPicker" round position="bottom">
            <van-picker
              :columns="questionOptions"
              @confirm="onQuestionConfirm"
              @cancel="showQuestionPicker = false"
            />
          </van-popup>
        </div>
      </div>
    </van-popup>

    <!-- 学习弹窗 -->
    <van-popup v-model:show="studyDialogVisible" round position="bottom" :style="{ height: '90%' }">
      <div class="popup-container">
        <van-nav-bar title="新增学习" left-arrow @click-left="studyDialogVisible = false" />
        <div class="popup-content">
          <van-form @submit="submitStudy">
            <van-field
              v-model="form.sectionName"
              label="小节名称"
              name="sectionName"
              required
              placeholder="请输入小节名称"
              :rules="[{required: true, message: '请输入小节名称'}]"
            />

            <van-field
              v-model="form.sectionOrder"
              label="顺序"
              name="sectionOrder"
              type="number"
              required
              placeholder="请输入顺序"
              :rules="[{required: true, message: '请输入顺序'}]"
            />

            <van-field
              v-model="form.watchTime"
              label="观看时长/分"
              name="watchTime"
              type="number"
              required
              placeholder="请输入观看时长"
              :rules="[{required: true, message: '请输入观看时长'}]"
            />

            <van-field label="附件上传">
              <template #input>
                <AttachmentS3Required ref="attachmentRef" :f-id="fId" />
              </template>
            </van-field>

            <div style="margin: 16px;">
              <van-button round block type="primary" native-type="submit">
                确定
              </van-button>
            </div>
          </van-form>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue';
import { showFailToast, showSuccessToast, showToast, showConfirmDialog } from 'vant';
import { useRoute, useRouter } from 'vue-router';
import AttachmentS3Required from '@/components/AttachmentS3Required.vue';

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

const onClickLeft = () => {
  router.back();
};

const rowData = ref({});
const ClassId = ref('');

onMounted(async () => {
  if (route.query.data) {
    const rowData1 = JSON.parse(route.query.data);
    rowData.value = rowData1;
    ClassId.value = rowData.value.id;
    queryFetch();
  } else {
    showToast({
      type: 'error',
      message: '未接收到数据参数'
    });
  }
  getQuestionId();
});

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

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

const form = ref({
  sectionName: '',
  sectionOrder: '',
  studyorExam: '',
  classId: '',
  watchTime: '',
  fileId: '',
  sectionId: '',
  questionName: '',
  questionId: '',
  singleChoice: '',
  multipleChoice: '',
  judge: '',
  singleChoiceScore: '',
  multipleChoiceScore: '',
  judgeScore: '',
  qualifiedScore: ''
});

const getTableData = async () => {
  if (!ClassId.value) {
    return;
  }

  const url = '/sgsafe/Class/querySection';
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: ClassId.value
  };

  try {
    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 || 0;
    } else {
      showToast({
        type: 'error',
        message: '操作失败！' + response.data.msg
      });
    }
  } catch (error) {
    console.error('获取数据失败：', error);
    showToast({
      type: 'error',
      message: '获取数据失败'
    });
  }
};

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

const onLoad = async () => {
  if (isRefreshing.value) {
    resultData.value = [];
    currentPage.value = 1;
    isRefreshing.value = false;
  }

  try {
    await getTableData();
    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;
  }
};

const basicReset = () => {
  isFinished.value = false;
  isLoading.value = true;
  currentPage.value = 1;
  resultData.value = [];
};

const addType = ref('');
const addTypeOptions = [
  { text: '新增', value: '' },
  { text: '考试', value: 'exam' },
  { text: '学习', value: 'study' }
];

const examDialogVisible = ref(false);
const studyDialogVisible = ref(false);
const fId = ref('');

const generateCode = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const formattedDate = `${year}${month}${day}`;
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const formattedTime = `${hours}${minutes}${seconds}`;
  const sequenceNumber = Math.floor(Math.random() * 1000);
  const paddedSequence = String(sequenceNumber).padStart(3, '0');
  return `XJXX${formattedDate}${formattedTime}${paddedSequence}`;
};

const generatedCode = ref(generateCode());

const regenerateCode = () => {
  generatedCode.value = generateCode();
};

const handleAddType = (value) => {
  if (!value) {
    return;
  }

  const cId = ClassId.value;

  if (value === 'exam') {
    form.value = {
      sectionName: '',
      sectionOrder: '',
      studyorExam: 'exam',
      classId: cId,
      questionName: '',
      questionId: '',
      singleChoice: '',
      multipleChoice: '',
      judge: '',
      singleChoiceScore: '',
      multipleChoiceScore: '',
      judgeScore: '',
      qualifiedScore: ''
    };
    examDialogVisible.value = true;
  } else if (value === 'study') {
    regenerateCode();
    form.value = {
      sectionName: '',
      sectionOrder: '',
      studyorExam: 'study',
      classId: cId,
      watchTime: '',
      fileId: generatedCode.value
    };
    fId.value = generatedCode.value;
    studyDialogVisible.value = true;
  }
  addType.value = '';
};

const questionIds = ref([]);
const getQuestionId = () => {
  const url = '/sgsafe/Rule/getQuestionId';
  const param = {};
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      questionIds.value = response.data.data || [];
    } else {
      showToast({
        type: 'error',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};

const selectedQuestionText = ref('');
const showQuestionPicker = ref(false);

const questionOptions = computed(() => {
  return questionIds.value.map(item => ({
    text: item.questionName,
    value: item.id
  }));
});

const onQuestionConfirm = ({ selectedOptions }) => {
  form.value.questionId = selectedOptions[0].value;
  const targetItem = questionIds.value.find(item => item.id === selectedOptions[0].value);
  if (targetItem) {
    form.value.questionName = targetItem.questionName;
    selectedQuestionText.value = targetItem.questionName;
  }
  showQuestionPicker.value = false;
};

const totalScore = computed(() => {
  const num = parseInt(form.value.singleChoice) || 0;
  const score = parseFloat(form.value.singleChoiceScore) || 0;
  if (num > 0 && score >= 0) {
    return (num * score).toFixed(0);
  }
  return '0';
});

const totalScoreText = computed(() => totalScore.value);

const totalChoice = computed(() => {
  const num = parseInt(form.value.multipleChoice) || 0;
  const score = parseFloat(form.value.multipleChoiceScore) || 0;
  if (num > 0 && score >= 0) {
    return (num * score).toFixed(0);
  }
  return '0';
});

const totalChoiceText = computed(() => totalChoice.value);

const totaljudge = computed(() => {
  const num = parseInt(form.value.judge) || 0;
  const score = parseFloat(form.value.judgeScore) || 0;
  if (num > 0 && score >= 0) {
    return (num * score).toFixed(0);
  }
  return '0';
});

const totaljudgeText = computed(() => totaljudge.value);

const totalExamScore = computed(() => {
  const s1 = parseFloat(totalScore.value) || 0;
  const s2 = parseFloat(totalChoice.value) || 0;
  const s3 = parseFloat(totaljudge.value) || 0;
  const total = (s1 + s2 + s3).toFixed(0);
  return isNaN(total) ? '0' : total;
});

const totalExamScoreText = computed(() => totalExamScore.value);

const attachmentRef = ref(null);

const submitStudy = async () => {
  if (form.value.studyorExam == 'study') {
    // 验证必须上传至少一个附件
    if (!attachmentRef.value || !attachmentRef.value.validate()) {
      showFailToast('请至少上传一个附件');
      return;
    }
    form.value.fileId = fId.value;
  }

  const param = {
    json: JSON.stringify(form.value)
  };

  try {
    const response = await proxy.$axios.post('/sgsafe/Class/saveStudySection', param);
    if (response.data.code == '0') {
      showSuccessToast('保存成功');
      // 关闭弹窗
      studyDialogVisible.value = false;
      examDialogVisible.value = false;
      // 重置表单
      form.value = {
        sectionName: '',
        sectionOrder: '',
        studyorExam: '',
        classId: '',
        watchTime: '',
        fileId: '',
        sectionId: '',
        questionName: '',
        questionId: '',
        singleChoice: '',
        multipleChoice: '',
        judge: '',
        singleChoiceScore: '',
        multipleChoiceScore: '',
        judgeScore: '',
        qualifiedScore: ''
      };
      fId.value = '';
      selectedQuestionText.value = '';
      // 刷新列表
      queryFetch();
    } else {
      showFailToast('保存失败：' + response.data.msg);
    }
  } catch (error) {
    console.error('保存失败：', error);
    showFailToast('保存失败：' + (error.message || '网络错误'));
  }
};

const openTrain = (row) => {
  if (row.studyorExam == 'study') {
    form.value = { ...row };
    fId.value = row.fileId || '';
    studyDialogVisible.value = true;
  } else {
    form.value = { ...row };
    if (row.questionId) {
      const targetItem = questionIds.value.find(item => item.id === row.questionId);
      if (targetItem) {
        selectedQuestionText.value = targetItem.questionName;
      }
    }
    examDialogVisible.value = true;
  }
};

const deleteRow = (row) => {
  showConfirmDialog({
    title: '提示',
    message: '确定要删除吗？'
  }).then(() => {
    const qiyong = ref({});
    qiyong.value = { ...row };
    qiyong.value.cancelFlag = '1';
    const url = '/sgsafe/Class/saveStudySection';
    const param = {
      json: JSON.stringify(qiyong.value)
    };
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        showSuccessToast('删除成功');
        queryFetch();
      } else {
        showToast({
          type: 'error',
          message: '操作失败！' + response.data.msg
        });
      }
    });
  }).catch(() => {
  });
};

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;
}

.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;
}

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

.popup-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.popup-content {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}
</style>
