import supportMaterialDetail from '@/components/modals/support-material/SupportMaterialDetail.vue';
import SupportMaterialService from '@/services/resources/SupportMaterialService';

const service = SupportMaterialService.build();
export default {
  components: {
    supportMaterialDetail
  },
  data() {
    return {
      rows: [],
      loading: false
    };
  },
  methods: {
    search() {
      this.loading = true;

      service
        .search()
        .then((resp) => {
          this.rows = resp;
          this.loading = false;
        })
        .catch((err) => {
          const resp = JSON.parse(err.response.data);
          this.$fire({
            title: 'Falha na solicitação',
            text: resp.msg,
            type: 'error'
          });

          this.loading = false;
        });
    },
    showModal() {
      this.$modal.show('support-material-detail');
    },
    edit(id) {
      this.$modal.show('support-material-detail', { id });
    },
    remove(row) {
      this
        .$fire({
          title: 'Remover registro',
          html: `Deseja realmente remover o registro <strong>${row.title}</strong>?`,
          type: 'question',
          showCancelButton: true,
          confirmButtonText: 'Deletar',
          cancelButtonText: 'Cancelar'
        })
        .then(async ({ value }) => {
          if (value) {
            let text = 'Registro removido com sucesso.';
            let type = 'success';
            try {
              await service.destroy(row.id);
              this.search();
            } catch (error) {
              console.error(error);
              text = 'Ocorreu um erro ao tentar remover o registro';
              type = 'danger';
            } finally {
              this.$fire({
                title: 'Remoção de registro',
                type,
                text
              });
            }
          }
        });
    }
  },
  mounted() {
    this.search();
  }
};
