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

const service = BannerService.build();

const banner = {
  image: '',
  title: '',
  type: '',
  description: '',
  image_url: '',
  priority: 0,
  campaign: null
};
export default {
  name: 'banner-detail',
  components: {
    TextInput,
    SelectInput,
    UploadImage,
    searchCampaign,
    NumberInput
  },
  data: () => {
    return {
      banner,
      loading: false,
      typeList: [
        {value: 'LARGER', text: "Home"}, 
        {value: 'SMALL', text: "Interno"}, 
        {value: 'MOBILE', text: "Celular"}
      ],
      perfilList: [
        {value: 'ADM', text: "Administrador"}, 
        {value: 'Analyst', text: "Analista"}, 
        {value: 'Marketing', text: "Marketing"}, 
        {value: 'SalesConsultant', text: "Consultora"}, 
        {value: 'ManagerSalesConsultant', text: "Gerente"}
      ],
      loadedImage: true
    };
  },
  computed:{
    formtoSend(){
      var form = {};
      Object.assign(form, this.banner);

      if(typeof(form.image) == 'string'){
        delete form.image;
    }

    form.campaign_id = (form.campaign ==  null)? null : form.campaign.id;

    return form;

    }
  },
  methods: {
    onImageChange(file) {
      this.banner.image = file;
    },
    closeModal() {
      this.$modal.hide('banner-detail');
      this.$emit('closed');
    },
    async beforeOpenModal(event) {
      this.reset();
      const { id } = event.params || {};
      if (!id) {
        return;
      }
      try {
       this.loadedImage = false;
        this.banner = await service.read(id);
       this.loadedImage = true;
        
      } catch (error) {
        this.showError(error);
      }
    },
    async save() {
      try {
        if (this.banner.id) {
         
          const obj = objectToFormData({
            ...this.formtoSend,
            _method: 'PUT'
          });

          await service.update(obj);
        } else {
          await service.create(objectToFormData(this.formtoSend));
        }

        this.$fire({
          title: 'Sucesso',
          type: 'success',
          text: 'Banner 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.banner = { ...banner };
      this.closeModal();
    }
  }
};
