import AdmVue from '@assets/js/adm-vue';
import initVue from '@assets/js/initVue';
import TextWithVar from '@assets/js/valid-text-with-vars';
import validations from '@assets/components/mixins/veeValidateMixin/veeValidateMixinRules';
import copyContent from '@assets/js/copyContent';
import formMixin from '@assets/components/mixins/formMixin';

import { v4 as uuidv4 } from 'uuid';
import { validate as uuidValidate } from 'uuid';

function setTextWithVar(e){
    const message = e.target.textWithVar.insertVarNameInText(e.detail.text);
    if(message){
      window.dispatchEvent(new CustomEvent('errorVarNameInText', {detail: message}));
    }
}

const vm = new AdmVue({
  directives: {
    textareaWithVar: {
      update: function (el) {
        const textArea = el.querySelector('textarea');
        textArea.textWithVar = new TextWithVar(textArea);
        textArea.removeEventListener('add', setTextWithVar);
        textArea.addEventListener('add', setTextWithVar);
      }
    }
  },
  components: {
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    BaseInputFile: () => import(/* webpackChunkName: "BaseInputFile" */ '@elements/BaseInputFile/index.vue'),
    BaseTabs: () => import(/* webpackChunkName: "BaseTabs" */ '@components/BaseTabs/index.vue'),
    AsideContent: () => import(/* webpackChunkName: "AsideContent" */ '@components/AsideContent/index.vue'),
    BaseTextarea: () => import(/* webpackChunkName: "BaseTextarea" */ '@elements/BaseTextarea/index.vue'),
  },
  data() {
    return {
      configurations: {
        feedback_message_status: [],
        feedback_account: [],
        feedback_automatic: [],
        gupshop_api: '',
        gupshop_cellphone: '',
        gupshop_user_service: '',
        gupshop_password_service: '',
        gupshop_api_name: '',
        gupshop_url_callback : '',
      },
      disableForm: false,
      tabs: [],
      tabsIntegration: [],
      messageType: 'feedback_message_status',
      loadingBtn: false,
      buttonTextCopyUrlCallback: '',
      gupshop_cell_test : [],
      gupshop_cell_database : '',
      gupshop_url_callback_database : '',
      maxlengthTextarea: 4000
    };
  },
  created(){
    window.addEventListener('errorVarNameInText', function(e){
      this.alert = {
        type: 'error',
        message: e.detail,
      };
    }.bind(this));

  },
  watch: {},
  computed: {
    sendData() {
      return {
        ...this.configurations,
        feedback_message_status: this.configurations.feedback_message_status.map(({ id, message }) => ({
          id,
          message,
        })),
        gupshop_url_callback: this.configurations.gupshop_url_callback,
      };
    },
    titleTabsIntegration() {
      let title = this.tabsIntegration[0].text;

      this.tabsIntegration.map(tabsIntegrationItem => {
        if (tabsIntegrationItem.active) {
          title = tabsIntegrationItem.text;
        }
      });

      return title;
    },
    titleTabsMessage() {
      const messages = this.configurations[this.messageType];
      if (messages.length === 0) return '';

      const activeTab = messages.find(item => item.active);
      const activeText = { ...activeTab };
      return activeText.text || messages[0].text;
    },
    generateUrlCallback() {
      const cellphone = this.configurations.gupshop_cellphone.replace(/\D/g, '');
      const cellphoneDatabase = this.gupshop_cell_database.replace(/\D/g, '');

      return Boolean(cellphone != cellphoneDatabase);
    }
  },
  beforeMount() {

    this.tabs = this.feedbackTabs;

    this.buttonTextCopyUrlCallback = this.btn_callback_copy;

    this.gupshop_cell_database = this.configurations.gupshop_cellphone;

    this.messageType = this.Type_Feedback.Tp_OrderStatus;

    this.gupshop_url_callback_database = this.configurations.gupshop_url_callback;

    this.tabsIntegration = Object.entries(this.Type_Integration.getEnumList()).map(([id, text]) => ({ text, active: false }));

    this.configurations.feedback_account = this.setVariableMessage(
      this.configurations.feedback_account,
      this.Type_FeedbackAccount.getEnumList()
    );

    this.configurations.feedback_automatic = this.setVariableMessage(
      this.configurations.feedback_automatic,
      this.Type_FeedbackAutomatic.getEnumList()
    );

  },
  mounted() {
    let feedbackStatus = Object.entries(this.Type_FeedbackOrderStatus.getEnumList()).map(([id, text]) => ({
      id,
      text,
      message: '',
    }));

    feedbackStatus = feedbackStatus.concat(
      this.order_status.map(item => ({ id: item.order_status_id, text: item.name, message: '' }))
    );

    if (!this.configurations.feedback_message_status.length) {
      this.configurations.feedback_message_status = feedbackStatus;
    } else {
      this.configurations.feedback_message_status = feedbackStatus.map(({ id, text }) => {
        const messageStatus = this.configurations.feedback_message_status.find(message => message.id == id);
        const message = messageStatus ? messageStatus.message : '';

        return {
          id,
          text,
          message,
        };
      });
    }

  },
  methods: {
    onSubmit(){

      const
        feedback_automatic = Array.from(this.configurations.feedback_automatic).map(({id, text, message}) => ({ id, text, message })),
        objectError  = {};

      this.$refs.validationObserver.reset();

      for (var key in feedback_automatic) {
        if(!feedback_automatic[key].message.trim()){
          objectError[`feedback_automatic[${key}]`] = [this.error_message];
          this.tabs.map((option, index) => {
            if (this.Type_FeedbackTabs.Tp_Message == index) {
              option.active = true;
            } else {
              option.active = false;
            }
            return option;
          })
        }
      }

      if(Object.keys(objectError).length){
        this.$refs.validationObserver.setErrors(objectError);
        this.setObserverErrors(objectError);
        return ;
      }

      formMixin.methods.onSubmit.call(this);
    },
    parseBoolean(value) {
      return Boolean(Number(value));
    },
    isSandbox(value) {
      return value == this.Type_Environment.Tp_Sandbox ? true : false;
    },
    addElement(element, index) {
      this.$refs['personalizedText_'+this.messageType][index].$refs.textarea.dispatchEvent(new CustomEvent('add', { detail: {text : element} }));
    },
    clickTab(value){
      this.$refs.validationObserver.reset();
      this.configurations[this.messageType] = value;
    },
    setVariableMessage(arrayConfigurations, arrayType){

      if (!arrayConfigurations.length) {
        return Object.entries(arrayType).map(([id, text]) => {

            const message = (this.Type_FeedbackAutomatic.Tp_AllAutomatic == id) ? this.text_message_automatic : '';

            return {
              id,
              text,
              message,
            };

          }
        );
      } else {
        return Object.entries(arrayType).map( ([id, text]) => {
            const messageAccount = arrayConfigurations.find(message => message.id == id);
            const message = messageAccount ? messageAccount.message : '';

            return {
              id,
              text,
              message,
            };

          }
        );
      }

    },
    setRulesCellphone(){

      let retorno = '';
      if(this.parseBoolean(this.configurations.gupshop_status) && !this.isSandbox(this.configurations.gupshop_environment)){
        retorno = 'required|cellphone';
      }else if(this.isSandbox(this.configurations.gupshop_environment)){
        retorno = '';
      }

      return retorno;

    },
    sendMessageTest : async function (messageType, index){

      const
        messageIndex = {...this.configurations[messageType][index]},
        objectError  = {},
        {cellphone}    = validations;

      this.$refs.validationObserver.reset();

      if(messageIndex.message.trim() == ''){
        objectError[`${messageType}[${index}]`] = [this.error_message];
      }

      if(typeof this.gupshop_cell_test[index] == 'undefined' || this.gupshop_cell_test[index].trim() == ''){
        objectError[`gupshop_cell_test[${index}]`] = [this.error_gupshop_cell_test];
      }

      if(!cellphone.validate(this.gupshop_cell_test[index])){
        objectError[`gupshop_cell_test[${index}]`] = [this.error_gupshop_cell_test];
      }

      if(Object.keys(objectError).length){
        this.$refs.validationObserver.setErrors(objectError);
        return ;
      }


      try {

        this.loadingBtn = true;

        const {data} = await this.axiosApi({
          url: this.url_gupshop_sendmessage,
          method: 'POST',
          data: this.param({message_text: messageIndex.message, message_number: this.gupshop_cell_test[index]})
        });

        const { warning, success } = data;

        if (warning) {
          this.alert = {
            type: 'warning',
            message: warning,
          };
        }

        if (success) {
          this.alert = {
            type: 'success',
            message: success,
          };
          this.formSuccess(data);
        }

      }catch (e) {
        console.log(e);
      }finally {
        this.configurations = {...this.configurations};
        this.loadingBtn = false;
      }

    },
    async getUrlCallback(gupshop_cellphone, gupshop_environment, gupshop_user_service, gupshop_password_service){
      try {

        this.loadingBtn = true;

        const {data} = await this.axiosApi({
          url: this.url_gupshop_callback,
          method: 'POST',
          data: this.param({gupshop_cellphone, gupshop_environment, gupshop_user_service, gupshop_password_service})
        });

        const { warning, success } = data;

        if (warning) {
          this.alert = {
            type: 'warning',
            message: warning,
          };
        }

        if (success) {
          this.configurations.gupshop_url_callback = success;
          this.disableSubmitButton = false;
        }

      }catch (e) {
        console.log(e);
      }finally {
        this.configurations = {...this.configurations};
        this.loadingBtn = false;
      }

    },
    handleUrlCallback() {
      if (this.generateUrlCallback) {
        this.configurations.gupshop_url_callback = '';
        this.disableSubmitButton = true;
      } else {
        this.configurations.gupshop_url_callback = this.gupshop_url_callback_database;
        this.disableSubmitButton = false;
      }
    },
    onCopyUrlCallback(){
      copyContent(this.configurations.gupshop_url_callback);
      this.buttonTextCopyUrlCallback = this.btn_callback_coped;
      setTimeout(() => {
        this.buttonTextCopyUrlCallback = this.btn_callback_copy;
      }, 2000);
    },
    setObserverErrors(errors){

      for(const key in errors){

        if(errors[key].length){

          const [_, type, optionIndex] = key.match(/([a-z_]+)\[([0-9]+)\]/);
            this.messageType = type;
            this.configurations[this.messageType] = this.configurations[this.messageType].map((option, index) => {
              if (optionIndex == index) {
                option.active = true;
              } else {
                option.active = false;
              }
              return option;
            });
          break;

        }

      }

    }
  }
});

initVue(vm);
