import TextInput from '@/components/shared-components/inputs/TextInput';
import Email from '@/components/shared-components/inputs/Email';
import SelectInput from '@/components/shared-components/inputs/SelectInput';
import UserService from '@/services/resources/UserService';

const service = UserService.build();

const user = {
  id: null,
  name: '',
  email: '',
  username: '',
  ramal: '',
  login: '',
  role: 'Analyst',
  password: '',
  password_confirmation: ''
};
export default {
  name: 'user-create-edit',
  components: {
    TextInput,
    Email,
    SelectInput
  },
  data: () => {
    return {
      user,
      roles:[
        {value: 'ADM', text: "Administrador"}, 
        {value: 'Analyst', text: "Analista"}, 
        {value: 'Marketing', text: "Marketing"}, 
        {value: 'ProcessOrders', text: "Gestor de Pedidos"}, 
        {value: 'Integration', text: "Intagração "},
        {value: 'ManagerComercial', text: "Diretor Comercial"},
        {value: 'SAC', text: "SAC"}
      ] ,
      loading: false
    };
  },
  methods: {
    closeModal() {
      this.$modal.hide('user-create-edit');
      this.$emit('closed');
    },
    async beforeOpenModal(event) {
      this.reset();
      const { userId } = event.params || {};
      if (!userId) {
        return;
      }
      try {
        let callbackUser = await service.read(userId);
        this.user = Object.assign(callbackUser);
        console.log( callbackUser.roles[0].name);
        this.user.role = (callbackUser.roles.length === 0)? null : callbackUser.roles[0].name;
      } catch (error) {
        this.showError(error);
      }
    },
    async save() {
      try {
        if (this.user.id) {
          await service.update({
            ...this.user,
            _method: 'PUT'
          });
        } else {
          await service.create(this.user);
        }

        this.$fire({
          title: 'Sucesso',
          type: 'success',
          text: 'Usuário 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.data || 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.user = { ...user };
      this.closeModal();
    }
  }
};
