<script setup>
import { getCurrentInstance, onMounted, ref } from 'vue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import { useDrillsStepsStore } from '@/stores/drillsSteps.js';
import { showFailToast } from 'vant';

const drillsSteps = useDrillsStepsStore();

const {
  proxy
} = getCurrentInstance();

const drills_url = '/sgsafe/EmergencyDrills';
const plan_url = '/sgsafe/EmergencyPlanMaster';
const onsite_url = '/sgsafe/OnsiteDisposalContent';

/* 通用方法： 重新获取list数据 */
const reacquireData = () => {
  finished.value = false;
  loading.value = true;
  pageNum.value = 1;
  list.value = [];
  onLoad();
};

/* 返回上一级页面 */
const router = useRouter();

/* 查询数据 */
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
const resultData = ref([]);
const fetchData = ref({
  planName: ''
});

const resetCondition = () => {
  fetchData.value = {
    planName: ''
  };
  reacquireData();
};

/* 查询请求 */
const queryFetch = async () => {
  let url = drills_url + '/queryByCurrentDept';
  if (stepsMark.value === 1) {
    url = plan_url + '/queryByCurrentDept';
  }
  const param = {
    page: pageNum.value,
    rows: pageSize.value,
    params: JSON.stringify(fetchData.value)
  };
  try {
    const res = await proxy.$axios.post(url, param);
    if (res.data.code === 0) {
      total.value = res.data.data.total;
      resultData.value = res.data.data.records;
    } else {
      console.log('操作失败!' + res.data.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

/* 列表加载与下拉刷新 */
const list = ref([]);
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const onLoad = async () => {
  if (refreshing.value) {
    list.value = [];
    pageNum.value = 1;
    refreshing.value = false;
  }
  try {
    await queryFetch();
    await excludeFinished();
    if (pageSize.value * pageNum.value < total.value) {
      list.value = [...list.value, ...resultData.value];
      pageNum.value++;
    } else {
      list.value = [...list.value, ...resultData.value];
      finished.value = true;
    }
  } catch (error) {
    console.log(error);
    finished.value = true;
  } finally {
    loading.value = false;
  }
};

const stepsMark = ref(0);
const selectedId = ref('');

const switchPrevState = () => {
  stepsMark.value = 0;
  reacquireData();
};

const switchNextState = () => {
  if (!selectedId.value) {
    showFailToast('请先选择');
    return;
  }
  if (stepsMark.value === 0) {
    drillsSteps.$patch({
      drillsId: selectedId.value
    });
    selectedId.value = '';
  }
  stepsMark.value = 1;
  reacquireData();
};

const switchFinish = () => {
  if (!selectedId.value) {
    showFailToast('请先选择');
    return;
  }
  drillsSteps.$patch({
    planId: selectedId.value
  });
  selectedId.value = '';
  sessionStorage.setItem('drillsSteps', JSON.stringify({
    drillsId: drillsSteps.drillsId,
    planId: drillsSteps.planId
  }));
  router.push('/specificSteps');
};

const excludeFinished = async () => {
  const idList = resultData.value.map(item => item.id);
  const url = onsite_url + '/queryEligibleData';
  const param = {
    json: JSON.stringify(idList)
  };
  const res = await proxy.$axios.post(url, param);
  if (res.data.code === 0) {
    const eligibleIds = res.data.data;
    if (eligibleIds.length > 0) {
      resultData.value.forEach(item => {
        if (eligibleIds.includes(item.id)) {
          item.isFinished = true;
        }
      });
    }
  }
};

const selectedRow = (item) => {
  if (item.isFinished) {
    showFailToast('该演练计划已完成');
    return;
  }
  selectedId.value = item.id;
};

let stepTotal = 2;
const totalData = ref(['选择演练计划', '选择应急预案']);

/**
 * 路由跳转前，pinia中缓存数据
 */
onBeforeRouteLeave((to, from, next) => {
  next();
});

onMounted(async () => {
  reacquireData();
});
</script>

<template>
  <div class="container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="app-title">
        <i class="fas fa-mobile-alt"></i>掌上演练
      </div>
    </div>

    <!-- 导航栏 -->
    <div class="nav-container">
      <div class="step-indicator">当前步骤: {{ stepsMark + 1 }}/{{ stepTotal }}</div>
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: ((stepsMark / (stepTotal - 1)) * 100) + '%' }"></div>
      </div>

      <van-steps :active="stepsMark" class="custom-steps" active-color="#1a73e8">
        <van-step v-for="(item, idx) in totalData" :key="idx">
          {{ item }}
        </van-step>
      </van-steps>

      <div class="nav-buttons">
        <div v-if="stepsMark !== 0" class="nav-button prev-button" @click="switchPrevState">
          <i class="fas fa-arrow-left" style="margin-right: 8px;"></i>上一步
        </div>
        <div v-else style="width: 10px;"></div>

        <div v-if="stepsMark !== 1" class="nav-button next-button" @click="switchNextState">
          下一步<i class="fas fa-arrow-right" style="margin-left: 8px;"></i>
        </div>

        <div v-else class="nav-button finish-button" @click="switchFinish">
          开始演练<i class="fas fa-play-circle" style="margin-left: 8px;"></i>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="scroll-container">
      <div class="custom-search">
        <van-search
          v-model="fetchData.planName"
          @search="reacquireData"
          @clear="resetCondition"
          placeholder="搜索应急预案名称"
          shape="round"
          background="transparent"
        />
      </div>

      <van-pull-refresh
        v-model="refreshing"
        success-text="刷新成功"
        @refresh="reacquireData"
      >
        <van-list
          class="list-container"
          :immediate-check="false"
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-cell
            v-for="item in list"
            :key="item.id"
            @click="selectedRow(item)"
            :class="['custom-cell', { 'selected-cell': selectedId === item.id }]"
          >
            <template #title>
              <span class="bold-title">
                <van-icon name="description" style="margin-right: 5px;" />
                {{ item.planName }}
              </span>
            </template>
            <template #label>
              <div class="bold-label">
                <span v-if="stepsMark === 0">
                  <van-icon name="calendar" />月度：{{ item.planYear + '年' + item.planMonth + '月' }}
                </span>
                <span v-if="stepsMark === 0">
                  <van-icon name="bar-chart-o" />层级：{{ item.planLevel }}
                </span>
                <div v-if="stepsMark === 1">
                  <van-icon name="idcard" />
                  文件编号：{{ item.planNo }}
                </div>
                <div v-if="stepsMark === 1">
                  <van-icon name="clock-o" />
                  发布日期：{{ item.publishDate }}
                </div>
              </div>
            </template>
            <template #right-icon>
              <van-icon name="arrow" style="color: #c8c9cc;" />
            </template>
          </van-cell>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

body {
  background-color: #f7f9fc;
  color: #333;
  line-height: 1.6;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding-bottom: 216px;
}

.header {
  background: linear-gradient(135deg, #1a73e8 0%, #6c14d0 100%);
  color: white;
  padding: 20px 0;
  border-radius: 0 0 20px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.app-title {
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.app-title i {
  margin-right: 12px;
  font-size: 28px;
}

.nav-container {
  background: white;
  border-radius: 16px;
  margin: 20px 0;
  padding: 15px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.step-content {
  background: white;
  border-radius: 16px;
  padding: 25px 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.step-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a73e8;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.step-title i {
  margin-right: 10px;
  font-size: 20px;
}

.step-instruction {
  background: #f0f7ff;
  padding: 15px;
  border-radius: 12px;
  margin-bottom: 20px;
  border-left: 4px solid #1a73e8;
  font-size: 15px;
  line-height: 1.7;
}

.input-area {
  margin-bottom: 20px;
}

.attachment-area {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  margin-top: 25px;
}

.attachment-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #5f6368;
  display: flex;
  align-items: center;
}

.attachment-title i {
  margin-right: 10px;
  color: #1a73e8;
}

.nav-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.nav-button {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 25px;
  border-radius: 10px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.nav-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.prev-button {
  background: #fff;
  color: #dc3545;
  border: 1px solid #dc3545;
}

.finish-button {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  color: white;
}

.step-indicator {
  text-align: center;
  margin: 15px 0;
  font-size: 14px;
  color: #5f6368;
}

.progress-bar {
  height: 8px;
  background: #e9ecef;
  border-radius: 4px;
  margin: 15px 0;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(135deg, #1a73e8 0%, #6c14d0 100%);
  border-radius: 4px;
  transition: width 0.5s ease;
}

/* 自定义步骤条样式 */
.custom-steps .van-step--horizontal .van-step__circle {
  width: 26px;
  height: 26px;
  background: #e9ecef;
  color: #5f6368;
}

.custom-steps .van-step--horizontal.van-step--process .van-step__circle {
  background: #1a73e8;
  color: white;
}

.custom-steps .van-step--horizontal.van-step--finish .van-step__circle {
  background: #28a745;
  color: white;
}

/* 响应式设计 */
@media (max-width: 600px) {
  .container {
    padding: 0 12px;
  }

  .app-title {
    font-size: 20px;
  }

  .nav-button {
    padding: 10px 20px;
    font-size: 14px;
  }
}


/* 统一顶部导航栏样式 */
.custom-navbar {
  background: linear-gradient(135deg, #1a73e8 0%, #6c14d0 100%);
  color: white;
}

.custom-navbar .van-nav-bar__title {
  font-weight: 600;
  font-size: 18px;
}

.nav-button {
  padding: 8px 16px;
  border-radius: 18px;
  font-weight: 500;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
}

.nav-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

/* 统一步骤条样式 */
.custom-steps {
  background: rgba(255, 255, 255, 0.15);
  padding: 12px 16px;
  backdrop-filter: blur(10px);
}

/* 统一搜索框样式 */
.custom-search {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  padding: 12px 16px;
}

.custom-search .van-search {
  border-radius: 20px;
  overflow: hidden;
}

/* 统一内容区域样式 */
.scroll-container {
  background: white;
  border-radius: 16px;
  padding: 25px 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.list-container {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

/* 统一列表项样式 */
.custom-cell {
  padding: 18px;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f0f0f0;
}

.custom-cell:last-child {
  border-bottom: none;
}

.custom-cell:hover {
  background-color: #f8f9fa;
  transform: translateY(-1px);
}

.selected-cell {
  background: linear-gradient(135deg, #e3f2fd, #bbdefb) !important;
  border-left: 4px solid #2196f3;
}

.bold-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
}

.bold-label {
  margin-top: 10px;
  font-size: 14px;
  color: #7f8c8d;
}

.bold-label span {
  display: inline-block;
  margin-right: 15px;
  padding: 5px 10px;
  background: #f0f7ff;
  border-radius: 6px;
  font-size: 13px;
}

.step-title i {
  margin-right: 10px;
  font-size: 20px;
}

.attachment-title i {
  margin-right: 10px;
  color: #1a73e8;
}

/* 统一按钮样式 */
.nav-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.prev-button {
  background: #fff;
  color: #dc3545;
  border: 1px solid #dc3545;
}

.next-button {
  background: #007bff;
  color: white;
}

.finish-button {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  color: white;
}

/* 步骤指示器和进度条样式 */
.step-indicator {
  text-align: center;
  margin: 15px 0;
  font-size: 14px;
  color: #5f6368;
}

.progress-bar {
  height: 8px;
  background: #e9ecef;
  border-radius: 4px;
  margin: 15px 0;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(135deg, #1a73e8 0%, #6c14d0 100%);
  border-radius: 4px;
  transition: width 0.5s ease;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .bold-title {
    font-size: 15px;
  }

  .bold-label {
    font-size: 13px;
  }

  .custom-steps {
    padding: 8px 12px;
  }

  .nav-button {
    padding: 8px 12px;
    font-size: 14px;
  }
}
</style>
