<template>
  <!--  <transition name="todo" appear>-->
  <!--    <li>-->
  <!--      <label>-->
  <!--        <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)">-->
  <!--        <span v-show="!todo.isEdit">{{ todo.title }}</span>-->
  <!--        <input v-show="todo.isEdit" type="text" @blur="handleBlur(todo, $event)" ref="inputFocus" :value="todo.title">-->
  <!--      </label>-->
  <!--      <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>-->
  <!--      <button v-show="!todo.isEdit" class="btn btn-edit" @click="handleEdit(todo)">编辑</button>-->
  <!--    </li>-->
  <!--  </transition>-->
  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)">
      <span v-show="!todo.isEdit">{{ todo.title }}</span>
      <input v-show="todo.isEdit" type="text" @blur="handleBlur(todo, $event)" ref="inputFocus" :value="todo.title">
    </label>
    <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
    <button v-show="!todo.isEdit" class="btn btn-edit" @click="handleEdit(todo)">编辑</button>
  </li>

</template>

<script>
import pubsub from 'pubsub-js'

export default {
  name: "TodoItem",
  // 从todoList中接收数据todos和函数checkTodo、deleteTodo
  props: ['todo'],
  methods: {
    // 触发全局事件总线中的方法，触发app中发回调方法
    handleCheck(id) {
      this.$bus.$emit('checkTodo', id)
    },
    // 通过订阅消息形式实现
    handleDelete(id) {
      if (confirm("确认删除？")) {
        pubsub.publish('itemDel', id)
      }
    },
    // 实现编辑逻辑
    handleEdit(todo) {
      if (todo.hasOwnProperty('isEdit')) {
        todo.isEdit = true
      } else {
        this.$set(todo, 'isEdit', true)
      }
      this.$nextTick(function () {
        this.$refs.inputFocus.focus()
      })
    },
    // 失去焦点时更新数据
    handleBlur(todo, e) {
      todo.isEdit = false
      console.log('updateTodo', todo.id, e.target.value)
      if (!e.target.value.trim()) return alert("输入不能为空！")
      this.$bus.$emit('updateTodo', todo.id, e.target.value)
    }
  }
}
</script>

<style scoped>
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background-color: #ddd;
}

li:hover button {
  display: block;
}

/*.todo-enter-active {*/
/*  animation: td 0.5s linear;*/
/*}*/

/*.todo-leave-active {*/
/*  animation: td 0.5s linear reverse;*/
/*}*/

/*@keyframes td {*/
/*  from {*/
/*    transform: translateX(100%);*/
/*  }*/
/*  to {*/
/*    transform: translateX(0);*/
/*  }*/
/*}*/
</style>