<template>
  <div class="container">
    <div class="header">
      <User 
        @updateYear="updateYear" 
        :date="year" 
        :dateList="dateList"
      />
    </div>
    
    <Overview :year="year.value" />
    
    <van-list 
      v-model:loading="loading" 
      :finished="finished" 
      finished-text="没有更多了"
      @load="onLoad"
    >
      <RecordItem 
        v-for="item in dataList" 
        :key="item.id" 
        :data="item"
        @goDetails="goDetails"
      />
    </van-list>
  </div>
</template>

<script>
import axios from "axios";
import User from "../components/ServiceRecords/User.vue";
import Overview from "../components/ServiceRecords/Overview.vue";
import RecordItem from "../components/ServiceRecords/RecordItem.vue";

export default {
  components: {
    User,
    Overview,
    RecordItem,
  },
  data() {
    return {
      dataList: [],
      loading: false,
      finished: false,
      currentPage: 1,
      year: {},
      dateList: [],
    };
  },
  methods: {
    fetchYearList() {
      const that = this;
      axios.get("/api/service/yearList").then(function (response) {
        const { error, data = {} } = response.data;
        if (error === 0) {
          const list = data.list || [];
          that.dateList = list;
          that.year = list[list.length - 1];
        }
      });
    },
    fetchServiceRecords(currentPage = 1) {
      const that = this;
      const payload = {
        currentPage,
        pageSize: 10,
        year: this.year.value,
      };

      this.loading = true;
      axios
        .get("/api/service/list", { params: payload })
        .then(function (response) {
          const { error, data = {} } = response.data;
          if (error === 0) {
            const currentPage = data.current;
            const list = data.list;

            if (currentPage === 1) {
              that.dataList = list;
            } else {
              that.dataList.push(...list);
            }

            that.currentPage = currentPage;
            that.finished = data.pageCount === currentPage;
          }
        })
        .finally(function () {
          that.loading = false;
        });
    },
    onLoad() {
      this.fetchServiceRecords(this.currentPage + 1);
    },
    goDetails(id) {
      this.$router.push("/serviceDetail?id=" + id);
    },
    updateYear(yearValue) {
      this.year = yearValue;
      this.currentPage = 1;
      this.fetchServiceRecords(1);
    },
  },
  mounted() {
    this.fetchYearList();
  },
  watch: {
    "year.value"() {
      if (this.year.value) {
        this.fetchServiceRecords(1);
      }
    },
  },
};
</script>

<style scoped>
.container {
  background-color: #f7f8fa;
  padding: 10px;
  min-height: 100vh;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  margin: -10px -10px 10px -10px;
  padding: 10px;
}
</style>
