import AdmVue from '@assets/js/adm-vue';
import initVue from '@assets/js/initVue';
import copyContent from '@assets/js/copyContent';
import param from '@assets/js/param.js';

const vm = new AdmVue({
  components: {
    GroupInput: () => import(/* webpackChunkName: "GroupInput" */ '@components/GroupInput/index.vue'),
    BaseInputFile: () => import(/* webpackChunkName: "BaseInputFile" */ '@elements/BaseInputFile/index.vue'),
    BaseAspectRatio: () => import(/* webpackChunkName: "BaseAspectRatio" */ '@elements/BaseAspectRatio/index.vue'),
    HighlightEditor: () => import(/* webpackChunkName: "HighlightEditor" */ '@components/HighlightEditor/index.vue'),
    AsideContent: () => import(/* webpackChunkName: "AsideContent" */ '@components/AsideContent/index.vue'),
    BaseTabs: () => import(/* webpackChunkName: "BaseTabs" */ '@components/BaseTabs/index.vue'),
    BaseSlider: () => import(/* webpackChunkName: "BaseSlider" */ '@elements/BaseSlider/index.vue'),
  },
  data() {
    return {
      configurations: {},
      exemptConfigIe: false,
      emailTest: '',
      showPassword: false,
      buttonTestEmailLoading: false,
      buttonTextCopyKeyApi: 'Copiar chave',
      buttonTextCopyLinkTemp: 'Copiar link temporário da loja',
      tabs: [
        { text: 'Geral', active: true },
        { text: 'Contato', active: false },
        { text: 'Loja', active: false },
        { text: 'Localização', active: false },
        { text: 'Opções', active: false },
        { text: 'Imagens', active: false },
        { text: 'E-mail', active: false },
        { text: 'Servidor', active: false },
      ],
      tabsOptions: [
        { text: 'Itens', active: true },
        { text: 'Produtos', active: false },
        { text: 'Pesquisar', active: false },
        { text: 'Conta', active: false },
        { text: 'Finalização de pedido', active: false },
        { text: 'Estoque', active: false },
        { text: 'Devoluções', active: false },
        { text: 'Política de cookies', active: false },
      ],
      buttonCeoLoading: false,
      buttonCeoText: 'Testar Conexão',
      buttonCeoApperance: 'outline',
      ceoValidationInfo: {},
    };
  },
  computed: {
    sendData() {
      if (!this.configurations.config_pathlink || this.configurations.config_path == 0) {
        delete this.configurations.config_pathlink;
      }

      if (this.configurations.config_rating_status == 0) {
        delete this.configurations.config_product_list_rating_status;
      }

      return { ...this.configurations };
    },
    titleTabsOptions() {
      const { tabsOptions } = this;
      const activeTab = tabsOptions.find(item => item.active);
      const title = activeTab.text || tabsOptions[0].text;

      return title;
    },
  },
  watch: {
    'configurations.config_path': function (val) {
      if (val == 0) {
        this.configurations.config_pathlink = '';
      }
    }
  },
  mounted() {
    this.exemptConfigIe = this.configurations.config_ie === 'ISENTO';
    this.emailTest = this.configurations.config_email;
  },
  methods: {
    onExemptConfigIe() {
      if (this.exemptConfigIe) {
        this.configurations.config_ie = 'ISENTO';
      } else {
        this.configurations.config_ie = '';
      }
    },
    onDeletePhone(index) {
      this.configurations.config_telephone.splice(index, 1);
      this.configurations = { ...this.configurations };
    },
    onAddPhone() {
      this.configurations.config_telephone.push({
        display: 1,
        numero: '',
        type: 1,
      });
      this.configurations = { ...this.configurations };
    },
    onConnectTest() {
      this.buttonTestEmailLoading = true;
      this.disableForm = true;

      const method = 'post';
      const token = document.body.dataset.token;
      const url = 'index.php?route=setting/setting/connectEmail&token=' + token;
      const data = {
        config_smtp_host: this.configurations.config_smtp_host,
        config_smtp_username: this.configurations.config_smtp_username,
        config_smtp_password: this.configurations.config_smtp_password,
        config_smtp_port: this.configurations.config_smtp_port,
        config_smtp_timeout: this.configurations.config_smtp_timeout,
        config_mail_parameter: this.configurations.config_mail_parameter,
        config_mail_protocol: this.configurations.config_mail_protocol,
        config_email_test: this.emailTest,
        config_owner: this.configurations.config_owner,
      };

      axiosApi({
        method,
        url,
        data: param(data),
      })
        .then(({ data }) => {
          const { warning, errors, success } = data;
          if (warning) {
            this.alert = {
              type: 'warning',
              message: warning,
            };
          }
          if (errors) {
            this.alert = {
              type: 'error',
              message: 'Alguns campos estão incorretos. Corrija os campos em vermelho.',
            };
            this.formError(data);
          }
          if (success) {
            this.alert = {
              type: 'success',
              message: success,
            };
            this.formSuccess(data);
          }
        })
        .catch(err => {
          console.log(err);
          this.alert = {
            type: 'warning',
            message: 'Aconteceu algo de inesperado, por favor tente novamente!',
          };
        })
        .finally(() => {
          this.disableForm = false;
          this.buttonTestEmailLoading = false;
        });
    },
    handleCopy(element, buttonText) {
      copyContent(this.configurations[element]);
      const ref = this[buttonText];
      this[buttonText] = 'Copiado';
      setTimeout(() => {
        this[buttonText] = ref;
      }, 2000);
    },
    changeSelect(optionValue){
      this.configurations.config_watermark_position = Number(optionValue);
    },
    validateCeo() {
      this.buttonCeoLoading = true;
      this.disableForm = true;
      this.ceoValidationInfo = {};

      const method = 'get';
      const token = document.body.dataset.token;
      const url = 'index.php?route=setting/setting/validateCeo&token=' + token;

      axiosApi({
        method,
        url,
      })
        .then(({ data }) => {
          this.ceoValidationInfo = data;
          const { request } = data;
          this.handleCeoButton(request);
        })
        .catch(err => {
          console.log(err);
          this.alert = {
            type: 'warning',
            message: 'Aconteceu algo de inesperado, por favor tente novamente!',
          };
        })
        .finally(() => {
          this.disableForm = false;
          this.buttonCeoLoading = false;
        });
    },
    handleCeoButton(request) {
      if (request) {
        this.buttonCeoText = 'Conexão efetuada com sucesso';
        this.buttonCeoApperance = 'success';
      } else {
        this.buttonCeoText = 'Erro de conexão';
        this.buttonCeoApperance = 'error';
      }

      setTimeout(() => {
        this.buttonCeoText = 'Testar Conexão';
        this.buttonCeoApperance = 'outline';
      }, 3000);
    }
  },
});

initVue(vm);
