import TextInput from '@/components/shared-components/inputs/TextInput';
import SelectInput from '@/components/shared-components/inputs/SelectInput';
import SupportMaterialService from '@/services/resources/SupportMaterialService';
import UploadImage from '@/components/shared-components/FileInput';
import { objectToFormData } from '@/utils/convert.js';

const service = SupportMaterialService.build();

const record = {
  image: '',
  title: '',
  embed: '',
  description: '',
  attachment_url: ''
};
export default {
  name: 'support-material-detail',
  components: {
    TextInput,
    SelectInput,
    UploadImage
  },
  data: () => {
    return {
      record,
      loading: false
    };
  },
  methods: {
    onImageChange(file) {
      this.record.attachment = file;
    },
    closeModal() {
      this.$modal.hide('support-material-detail');
      this.$emit('closed');
    },
    async beforeOpenModal(event) {
      this.reset();
      const { id } = event.params || {};
      if (!id) {
        return;
      }
      try {
        this.record = await service.read(id);
      } catch (error) {
        this.showError(error);
      }
    },
    async save() {
      try {
        if (this.record.id) {
          const obj = objectToFormData({
            ...this.record,
            _method: 'PUT'
          });
          await service.update(obj);
        } else {
          await service.create(objectToFormData(this.record));
        }

        this.$fire({
          title: 'Sucesso',
          type: 'success',
          text: 'Registro salvo com sucesso'
        });

        this.closeModal();
        this.$emit('success');
      } catch (error) {
        this.showError(error);
      }
    },
    showError(error) {
      let html = '';
      try {
        const getData = () => {
          try {
            const resp = JSON.parse(error.response.data);
            return resp.msg || resp;
          } catch {
            return {};
          }
        };

        html = Object
          .entries(getData())
          .map(([key, messages]) => `<div>${key}: ${messages.join('</br>')}<div>`)
          .join('</br>');
      } catch {
        html = 'Ocorreu um erro na operação';
      }

      this.$fire({
        title: 'Erro',
        type: 'error',
        html
      });
    },
    reset() {
      this.record = { ...record };
      this.closeModal();
    }
  }
};
