<template>
  <van-popup v-model:show="props.modelValue" class="training-popup">
    <div class="head">{{ props.title }}</div>
    <div class="companyBox">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" offset="20" :immediate-check="false">
        <van-cell @click="handleItemClick(item)" v-for="(item, index) in listData" :key="index" :title="item.name" clickable>
          <template #right-icon>
            <van-checkbox v-model="item.checked" :shape="props.isRadio ? 'round' : 'square'" :checked="isSelected(item)" />
          </template>
        </van-cell>
        <van-empty v-if="listData.length <= 0" description="暂无数据" image="default" />
      </van-list>
    </div>
    <div class="footBtns">
      <van-button round block type="primary" class="btn" @click="handleClose">取消</van-button>
      <van-button round block type="primary" class="btn" @click="submitForm">确认</van-button>
    </div>
  </van-popup>
</template>

<script setup>
import { Toast } from 'vant';
import { getItem } from "@/utils/storage";
import { http } from "@/api/http";
import { ref, defineProps, defineEmits, watch } from 'vue'
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  isRadio: {
    type: Boolean,
    default: true
  },
  title: {
    type: String,
    default: '请选择数据'
  },
  type: {
    type: String,
    default: ''//选择的类型
  }
})
const emit = defineEmits(['update:modelValue', 'change'])
const finished = ref(false);
const loading = ref(false);
const listData = ref([])
const selectedItems = ref([]);
const page = ref(0)
const total = ref(0)

// 添加缓存对象，用于存储不同类型的完整数据
const dataCache = ref({})


// 获取对应的列表
const getList = () => {
  // 检查缓存中是否已经有完整的数据
  if (dataCache.value[props.type] && dataCache.value[props.type].length > 0) {
    // 使用缓存数据
    listData.value = dataCache.value[props.type];
    total.value = dataCache.value[props.type].length;
    finished.value = true;
    loading.value = false;
    return;
  }

  let params = { pageNum: page.value, pageSize: 10 };
  let url = null, methods = 'post'
  let nameKey = ''
  switch (props.type) {
    case 'zfjly':
      nameKey = 'xmmc'
      try {
        let siteArray = JSON.parse(getItem("userInfo").siteArray) || [];
        listData.value = siteArray.map(site => ({ name: site.siteName, id: site.siteCode }));
      } catch (error) { }
      // url = '/mosty-base/baxx/pxxm/page' //接口需要换，现在不知道接口，这个是乱写的接口
      break;
  }
  if (!url) return false;
  loading.value = true;
  http[methods](params, url).then(res => {
    loading.value = false;
    const arr = res.records.map((el) => {
      return { name: el[nameKey], ...el }
    }) || [];
    listData.value = page.value == 1 ? arr : listData.value.concat(arr);
    total.value = res.total;
    // 当数据全部加载完成后，将数据存入缓存
    if (listData.value.length >= total.value) {
      dataCache.value[props.type] = listData.value;
    }
  }).catch(() => {
    loading.value = false;
  })
}
//触底加载
function onLoad() {
  if (listData.value.length == total.value) return (finished.value = true);
  page.value += 1;
  getList();
}

const isSelected = (item) => {
  return selectedItems.value.some((i) => i.id === item.id); // 多选
};

// 选择数据
const handleItemClick = (item) => {
  if (props.isRadio) { //单选
    selectedItems.value = [item]
  } else { //多选
    const index = selectedItems.value.findIndex((i) => i.id === item.id);
    index > -1 ? selectedItems.value.splice(index, 1) : selectedItems.value.push(item);
  }
};
// 关闭
const handleClose = () => {
  emit('update:modelValue', false)
}

// 提交
const submitForm = () => {
  if(selectedItems.value.length <= 0) return Toast('请至少选择一项');
  emit('update:modelValue', false)
  emit('change', selectedItems.value)
}
watch(() => props.modelValue, val => {
  if (val) {
    // 重置分页状态，但保留listData以便在请求失败时显示缓存数据
    page.value = 1;
    finished.value = false;
    loading.value = false;
    // 只有在缓存为空时才清空listData
    if (!dataCache.value[props.type]) {
      listData.value = [];
    }
    getList();
  }
}, { immediate: true, deep: true })
</script>

<style lang="scss" scoped>
.companyBox {
  height: 60vh;
  overflow: auto;
}

.head {
  border-bottom: 1px solid #e7e7e7;
  text-align: center;
  font-size: 14px;
  line-height: 40px;
}

.footBtns{
  margin-top: 16px;
  margin-bottom: 16px;
  display: flex;
  padding-left: 10px;
  padding-right: 10px;
  .btn{
    margin-left: 10px;
    margin-right: 10px;
  }
}
</style>
<style>
.training-popup {
  width: 90%;
  border-radius: 5px;
}
</style>
