<template>
  <div class="h5-container">
    <van-nav-bar title="课程管理" @click-left="onClickLeft" @click-right="handAdd">
      <template #right>
        <van-icon name="add" size="25" color="#000" />
      </template>
    </van-nav-bar>
    <van-search v-model="query.name" show-action placeholder="请输入课程名称" @search="onRefresh"
      @cancel="handdelect" />

    <!-- 年份选择 -->
    <van-field
      v-model="selectedYearText"
      readonly
      is-link
      label="年份"
      placeholder="请选择年份"
      @click="showYearPicker = true"
    />

    <!-- 项目列表 -->
    <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="queryInfo(item)">
                  <template #title>
                    <div class="cell-title">
                      {{ item.projectName }}
                    </div>
                  </template>
                  <template #label>
                    <div>培训学时：{{ item.trainHours }}</div>
                    <div>培训类别：{{ item.projectType }}</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="handleDelete(item)" />
              <van-button square class="submit-button" text="添加人员" @click="openClassName(item)" />
              <van-button square class="submit-button" text="添加小节" @click="jumpsection(item)" />
            </template>
          </van-swipe-cell>
        </div>

      </van-list>
    </van-pull-refresh>

    <!-- 删除确认弹窗 -->
    <van-dialog v-model:show="deleteDialogVisible" show-cancel-button @confirm="confirmDelete">
      <template #title>
        <div>删除确认</div>
      </template>
      <div style="padding: 30px;">确定要删除该课程吗？</div>
    </van-dialog>

    <!-- 年份选择器 -->
    <van-popup v-model:show="showYearPicker" round position="bottom">
      <van-picker
        :columns="yearOptions"
        @confirm="onYearConfirm"
        @cancel="showYearPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick, toRaw } from 'vue';
import { Dialog, showDialog, showSuccessToast, showToast, Toast, showConfirmDialog } from 'vant';
import { useRouter } from 'vue-router';

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

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

const searchShow = ref(false);
const query = ref({
  year: '',
  name: ''
});

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 tableData = ref([]);
const deleteDialogVisible = ref(false);
const deleteId = ref('');

const currentYear = ref(new Date().getFullYear());
const years = Array.from({ length: 5 }, (_, i) => {
  const year = new Date().getFullYear();
  return year - 4 + i;
});

const yearOptions = years.map(year => ({
  text: String(year),
  value: String(year)
}));

const selectedYearText = ref(String(currentYear.value));
const showYearPicker = ref(false);

const onYearConfirm = ({ selectedOptions }) => {
  query.value.year = selectedOptions[0].value;
  selectedYearText.value = selectedOptions[0].text;
  showYearPicker.value = false;
  onRefresh();
};

const getTableData = async () => {
  const url = '/sgsafe/Class/query';
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  };
  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 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 handdelect = () => {
  query.value.name = '';
  onRefresh();
};

const handAdd = () => {
  router.push({
    path: "/courseManagementList",
    query: {
      mark: -1
    }
  });
};

const openTrain = (row) => {
  router.push({
    path: "/courseManagementList",
    query: {
      mark: 1,
      data: JSON.stringify(row)
    }
  });
};

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

const jumpsection = (row) => {
  router.push({
    path: '/section',
    query: {
      data: JSON.stringify(row)
    }
  });
};

const queryInfo = (row) => {
  router.push({
    path: "/courseManagementList",
    query: {
      mark: 1,
      data: JSON.stringify(row),
      readOnly: 'true'
    }
  });
};

const handleDelete = (item) => {
  deleteId.value = item.id;
  deleteDialogVisible.value = true;
};

const confirmDelete = () => {
  const qiyong = ref({});
  qiyong.value = { ...resultData.value.find(item => item.id === deleteId.value) };
  qiyong.value.cancelFlag = '1';
  const url = '/sgsafe/Class/save';
  const param = {
    json: JSON.stringify(qiyong.value)
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      showSuccessToast('删除成功');
      deleteDialogVisible.value = false;
      onRefresh();
    } else {
      showToast({
        type: 'error',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};

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

onMounted(() => {
  query.value.year = String(currentYear.value);
  selectedYearText.value = String(currentYear.value);
});
</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;
  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;
}

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