<script>
import {
  getContentProtection,
  updateContentProtection
} from '@/api/external'

export default {
  name: 'ContentProtection',
  props: {
    device: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      loading: true,
      error: false,
      open: false
    }
  },
  computed: {
    canEdit () {
      return this.accessSet.has(this.Access.MANAGE_DEVICES) || this.accessSet.has(this.Access.MANAGE_DEVICE)
    }
  },
  created () {
    this.getContentProtection()
  },
  methods: {
    getContentProtection () {
      this.loading = true
      this.error = false
      getContentProtection(this.device.id, { custom: true }).then(
        ({ data }) => {
          this.open = data ? data.protect : false
        },
        () => {
          this.error = true
        }
      ).finally(() => {
        this.loading = false
      })
    },
    toggle () {
      const open = !this.open
      updateContentProtection(this.device.id, open).then(() => {
        this.open = open
      })
    }
  },
  render (h) {
    if (this.loading) {
      return h('i', {
        class: 'el-icon-loading'
      })
    }
    if (this.error) {
      return h('el-link', {
        props: {
          type: 'warning'
        },
        on: {
          click: this.getContentProtection
        }
      }, ['获取失败，点击重试'])
    }
    if (this.canEdit) {
      return h('el-switch', {
        props: {
          value: this.open,
          'active-color': '#13ce66',
          'inactive-color': '#ff4949'
        },
        on: {
          change: this.toggle
        }
      })
    }
    return h('div', null, this.open ? '已启用' : '未启用')
  }
}
</script>
