<template>
  <div class="alarm-item">
    <div class="alarm-item-left" @click="$emit('click-edit', data)">
      <h4 class="alarm-item__title">{{data.time}}</h4>
      <p class="alarm-item__text">{{showText}}</p>
    </div>
    <div class="alarm-item-right">
      <van-switch
        v-model="checked"
        size="18px"
        active-color="#C62245"
        :loading="switchLoading"
        @change="onChange"
      />
      <van-icon name="delete" @click="onRemove" />
    </div>
  </div>
</template>

<script>
import * as api from '../api'
export default {
  name: 'AlarmItem',
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      checked: false,
      switchLoading: false
    }
  },
  watch: {
    'data.status': {
      immediate: true,
      handler(value) {
        this.checked = value === '1'
      }
    }
  },
  computed: {
    showText() {
      const type = parseInt(this.data.type)
      if (type === 1) {
        return '每天'
      } else if (type === 3) {
        return '工作日'
      } else {
        return this.selectedWeek.length ? '每周' + this.selectedWeek.join('、') : '永不'
      }
    },
    selectedWeek() {
      const weeks = ['一', '二', '三', '四', '五', '六', '日']
      const nums = this.data.week_json ? JSON.parse(this.data.week_json) : []
      return nums.map(item => weeks[item - 1])
    }
  },
  methods: {
    onChange() {
      this.switchLoading = true
      const params = Object.assign({}, this.data)
      params.status = this.checked ? 1 : 0
      api.updateAlaram(params).finally(() => {
        this.switchLoading = false
      })
    },
    onRemove() {
      this.$emit('remove', this.data)
      api.deleteAlaram(this.data.id).then(response => {
        this.$toast('删除成功')
        this.$emit('update')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.alarm-item {
  display: flex;
  align-items: center;
  padding: 20px 0;
}
.alarm-item-left {
  flex: 1;
}
.alarm-item__title {
  font-size: 20px;
  font-weight: bold;
  line-height: 1;
}
.alarm-item__text {
  margin-top: 5px;
  font-size: 13px;
  line-height: 1;
  color: #666;
}
.alarm-item-right {
  margin-left: 20px;
  font-size: 0;
  ::v-deep .van-icon {
    margin-left: 20px;
    font-size: 20px;
    color: #ccc;
  }
}
</style>
