<template>
  <div>
    <section class="todoapp">
      <TodoHeader v-bind:addTask="addTodo"></TodoHeader>
      <TodoContent
        :todoList="renderList()"
        :choose="handleChoose"
        :remove="handleDelete"
        :all="handleAll"
      ></TodoContent>
      <TodoFooter
        :count="countSelected()"
        :selectedMain="handleSelect"
        :newFilter="filters"
        :removeComplete="handleRemove"
      ></TodoFooter>
    </section>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoFooter from "./components/TodoFooter.vue";
import TodoContent from "./components/TodoContent.vue";
// 添加方法
const addTodo = (val: string) => {
  let obj = {
    id: Date.now(),
    text: val,
    completed: false,
  };
  todoList.value.push(obj);
};
export interface Todo {
  id: number;
  text: string;
  completed: boolean;
}
// 数组
const todoList = ref<Todo[]>([
  {
    id: 1,
    text: "吃饭",
    completed: false,
  },
  {
    id: 2,
    text: "睡觉",
    completed: true,
  },
]);
// 过滤
const filters = ref("all");
// 未选中的数量
function countSelected() {
  return todoList.value.filter((item) => !item.completed).length;
}
// 选中
function handleChoose(val: number) {
  for (var i = 0; i < todoList.value.length; i++) {
    if (todoList.value[i].id == val) {
      todoList.value[i].completed = !todoList.value[i].completed;
    }
  }
}
// 渲染数组
const renderList = () => {
  if (filters.value == "all") return todoList.value;
  // if(filters.value == 'avtive') {
  //   return  todoList.value.filter((item) => !item.completed)
  // }
  // if(filters.value == 'completed') {
  //   return  todoList.value.filter((item) => item.completed)
  // }
  return todoList.value.filter((item) =>
    filters.value === "active" ? !item.completed : item.completed
  );
};
// 修改filters的值
const handleSelect = (val: string) => {
  filters.value = val;
};
// 删除单条数据
const handleDelete = (val:number) => {
  console.log("删除",val)
  if(!window.confirm("确定删除该条信息么？")) return;
  todoList.value =  todoList.value.filter((item)=>item.id != val);
}
// 删除所有完成项
const handleRemove=() => {
  if(!window.confirm("确定删除所有完成项目么？")) return;
  todoList.value =  todoList.value.filter((item)=> !item.completed );
}
// 全选
function handleAll(val:any) {
  console.log("全选",val.checked)
  todoList.value.map((item) => {
   return item.completed = val.checked
  })
}
</script>
<!-- npm install sass -->
<style lang="scss" scoped>
</style>
