import AdmVue from '@assets/js/adm-vue';
import TextWithVar from '@assets/js/valid-text-with-vars';
import copyContent from '@assets/js/copyContent';
import modelPrice from '../../../model/marketplace/marketplace/marketplacePrice.js';
import axiosApi from "@assets/js/axios-api";
import param from "@assets/js/param";

const vm = new AdmVue({
  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'),
    GroupInput: () => import(/* webpackChunkName: "BaseTabs" */ '@components/GroupInput/index.vue'),
    MarketPrice: () => import(/* webpackChunkName: "MarketPrice" */ '@components/MarketPrice/index.vue'),
    listPagination: () => import(/* webpackChunkName: "listPagination" */ '@components/ThePagination/index.vue'),
  },
  data(){ return {
    list: {
      //campos que vao ser usados na tabela de medidas
    },
    configurations: {
      mercadolivre_app_id: '',
    },
    filters: {
      description: '',
      gender: ''
      //Filtros Vindo do V-model
    },
    errors: '',
    brandType: '',
    textDescri: '',
    listBrandsMl: {

    },
    MLBrand: '',
    pagination: '',
    bInsert: false,
    currentPage: 1,
    limit: 12,
    btnSubmitLoading: false,
    disableForm: false,
    initialDate: '',
    finalDate: '',
    chartSelected: [],
    activeFilter: false,
    textFilter: '',
    countFilter: 0,
    categoryMain: [],
    subCategories: [],
    listGender: [],
    chartsSearch : {
      domain_id: '',
      gender:    '',
      brand:     '',
      boolDatabase: false,
      name: '',
      insert: false,
      chart: ''
    },
    title: [
      {
        name: 'tamanho',
        type: 'select',
        selectopt: [this.valueSize],
        // selectopt: [{id : '1', name: "name"},
        //             {id : '2', name: "val"},
        //             {id : '3', name: "aaa"}],
        title: 'Tamanho'
      },
      {
        name: 'size',
        type: 'text',
        mask: 'decimal',
        title: 'BR'
      },
      {
        name: 'length',
        type: 'text',
        mask: 'decimal',
        title: 'Comprimento do Pé (cm)'
      },
      {
        name: 'us',
        title: 'US',
        type: 'text',
        mask: 'decimal',
        titleClass: 'center aligned',
        dataClass: 'center aligned',
      },
      {
        name: 'eu',
        title: 'EU',
        type: 'text',
        mask: 'decimal',
        titleClass: 'center aligned',
        dataClass: 'center aligned',
      },
      {
        name: 'uk',
        title: 'UK',
        type: 'text',
        mask: 'decimal',
        titleClass: 'center aligned',
        dataClass: 'center aligned',
      },
    ],
    data:[
        // {
        //   id: 5,
        //   size: 20,
        //   length: "20",
        //   us: "8",
        //   eu: "38",
        //   uk: "43",
        // },
    ]

  }
  },
  created() {},
  mounted() {

    this.title[0] = ({selectopt : this.valueSize,
                    name: 'tamanho',
                    type: 'select',
                    title: 'Tamanho'});
  },
  watch: {
    "configurations.bInsert"(value){
      if(value == false)
        this.clearSelections();
    }
  },
  computed: {
    sendData() {
      return {
        ...this.list, ...this.filters, ...this.pagination
      };
    },
  },
  methods: {
    filter(selectedPage = 1){
      this.btnSubmitLoading = true;
      this.disableForm = true;

      if(selectedPage){
        this.currentPage = selectedPage;
      }
      axiosApi({
        method: 'POST',
        url: this.actionFilter,
        data: param({filters: this.filters, page: selectedPage, ajax: true}),
        // params: { filters: this.filters, page: selectedPage },
      })
        .then(({data}) => {
          if(data.list){
            this.list = data.list;
            if(data.pagination){
              this.pagination = data.pagination;
            }
            if(data.limit){
              this.limit = parseInt(data.limit);
            }
          }
          this.btnSubmitLoading = false;
          this.disableForm = false;
          this.activeFilter = false;

          this.countFilter = 0;

          if(this.filters.gender)++this.countFilter;
          if(this.filters.description)++this.countFilter;

          if(this.countFilter > 0){
            this.textFilter = this.text_limparFiltros+' ('+this.countFilter+')';
          }

        })
        .catch((err) => console.log(err, err.response))
    },
    Action(e){
      this.btnSubmitLoading = true;
      this.disableForm = true;

      if(e == 'delete'){
        axiosApi({
          method: 'POST',
          url: this.actionDelete,
          data: param({ajax: true, list: this.chartSelected }),
        }).then(({data}) => {
          if(data){
            this.filter(this.currentPage);

            notificationMsg(this.text_success, 'success');
            this.chartSelected = [];
          }else{
            notificationMsg(this.error_exclusaochart, 'error');

          }
          this.btnSubmitLoading = false;
          this.disableForm = false;
        }).catch((err) => console.log(err, err.response))
      }else if(e == 'save'){

        //Quando for BRAND não altera apenas salva
        axiosApi({
          method: 'POST',
          url: this.actionSave,
          data: param({ajax: true, rows:this.data, info:this.chartsSearch, selected: this.MLBrand, list: this.listBrandsMl, type: this.brandType }),
        }).then(({data}) => {
          if(!data.errors.length){
            //Success ao salvar tabela.
            if(data) {
              this.configurations.bInsert = false;
              this.clearSelections();
              this.filter();
              notificationMsg(this.text_success, 'success');
            }
          }else{
            this.errors = data.errors;
            notificationMsg(this.error_warning, 'error');
          }

          this.btnSubmitLoading = false;
          this.disableForm = false;
        }).catch((err) => console.log(err, err.response))
      }
    },
    toogleSelected(val){
      if(this.chartSelected.indexOf(val) > -1){
        this.chartSelected = this.chartSelected.filter((item) => item !== val);
      }
      else
        this.chartSelected.push(val);
    },removeFilters(){
      this.filters.description = '';
      this.filters.gender = '';
      this.countFilter = 0;
      this.textFilter = '';
      this.filter(1);
    },
    selectReturnCategoryMain(eVal){
      this.categoryMain.push(eVal);

      axiosApi({
        method: 'POST',
        url: this.actionSubCategory,
        data: param({ajax: true, id: eVal }),
      }).then(({data}) => {
        if(data.domain){
          this.chartsSearch.domain_id = data.domain;
          //Chamada de atualização de Gender
          axiosApi({
            method: 'POST',
            url: this.actionGetGender,
            data: param({ajax: true, domain: this.chartsSearch.domain_id }),
          }).then(({data}) => {
            if(data) {
              this.listGender = data;
            }
          }).catch((err) => console.log(err, err.response));

        }else if(data.notFind){
          //Aqui limpa por não achar categoria correta.
          notificationMsg(this.text_categoryNotFind, 'warning');
          this.clearSelections();

        }else{
          this.subCategories.push(data);
        }
        if(this.subCategories.length >= 2){
          let $select = document.getElementsByName('category_id'+(this.subCategories.length-2));

          $select.item(0).setAttribute('disabled',true);
        }
        if(this.chartsSearch.domain_id){
          for(let i = 0; i < this.subCategories.length; i = i + 1 ) {
            let $select = document.getElementsByName('category_id'+(i));
            $select.item(0).setAttribute('disabled',true);
          }
        }
      }).catch((err) => console.log(err, err.response))


    },
    clearSelections(){
      this.subCategories = [];
      this.chartsSearch.domain_id = '';
      this.chartsSearch.chart = '';
      this.categoryMain = [];
      this.listBrandsMl = [];
      this.MLBrand = '';
      this.errors = '';
      this.listBrandsMl = {"insert": false};
      this.data = [];
      this.chartsSearch.boolDatabase = false;
    },
    selectReturnBrand(eVal){
      this.chartsSearch.brand = eVal;
    },
    selectReturnGender(eVal){
      this.chartsSearch.gender = eVal;
    },
    findChart(){
      // Primeiro fazer verificação na propria base para ver se a tabela já não esta cadastrada.
      axiosApi({
        method: 'POST',
        url: this.actionGetChart,
        data: param({ajax: true, data: this.chartsSearch }),
      }).then(({data}) => {
        if(data) {
          if(data.names){
            this.listBrandsMl = data;

            if(data.insert){
              this.chartsSearch.boolDatabase = true;
            }

            let manufacturer = document.getElementsByName('Manufacturer');
            manufacturer.item(0).setAttribute('disabled',true);
            let Gender = document.getElementsByName('Gender');
            Gender.item(0).setAttribute('disabled',true);

            if(data.read){
              this.returnMLbrand(data.names[0].id);
            }

          }else{
            console.log('Erro no retorno');
          }
          this.btnSubmitLoading = false;
          this.disableForm = false;
        }
      }).catch((err) => console.log(err, err.response));

      // Caso não a tenha fazer o seu cadastro.

    },
    returnMLbrand(val){
      this.MLBrand = val;
      let names = this.listBrandsMl.names;
      let lista =  this.listBrandsMl.rows;

      for(let i = 0; i < names.length; i++){
        if (names[i].id == val){
          this.listBrandsMl.names = [names[i]];
          this.brandType =  names[i].type;
          break;
        }
      }

      for(let i = 0 ; i < lista.length;i++){
        if (Object.keys(lista[i]) == val){
          this.listBrandsMl.rows = lista[i];

          break;
        }
      }
      this.carregaInfoML();
    },
    carregaInfoML(){
      let listAttib = [];
      let listDados = this.listBrandsMl.rows[Object.keys(this.listBrandsMl.rows)];

      for(let i = 0 ; i < listDados.length;i++) {
        listAttib.push({
          "id": listDados[i].id,
          "size": this.getInfo(listDados[i].attributes,"BR"),
          "length": this.getInfo(listDados[i].attributes,"FOOT_LENGTH"),
          "us": this.getInfo(listDados[i].attributes,"US"),
          "eu": this.getInfo(listDados[i].attributes,"EU"),
          "uk": this.getInfo(listDados[i].attributes,"UK"),
          "tamanho": this.getInfo(listDados[i].attributes,"productsize_id")
        });
      }
      this.data = listAttib;

      if(!this.listBrandsMl['insert']){
        this.chartsSearch.name = this.listBrandsMl.names[0].name;
      }

    },
    getInfo(attr , $value){
      for(let j = 0; j <  attr.length; j++){
        if (attr[j].id.indexOf($value) > -1){
          return attr[j].values[0].name? attr[j].values[0].name : '-';
        }
      }
    },
    loadChart(val){
      //Carrega informações cadastradas.
      if(val){
        this.btnSubmitLoading = true;
        this.disableForm = true;
        this.configurations.bInsert = true;

        this.chartsSearch.domain_id = val['domain_id'];
        this.chartsSearch.gender    = val['GENDER'];
        this.chartsSearch.brand     = val['manufacturer_id'];
        this.chartsSearch.boolDatabase = true;
        this.chartsSearch.chart     = val['SIZE_GRID_ID'];
        this.errors = '';
        this.chartsSearch.insert = false;

        this.chartsSearch.name

        this.findChart();
      }
    },
    AddNewChart(){
      this.listBrandsMl = [];
      this.chartsSearch.insert = true;
      let arr = []
      arr.push({"name":'', "id": ''});
      this.listBrandsMl.names = arr;
      this.listBrandsMl.rows = [];
      this.data = [];
      this.chartsSearch.name = '';

      if(this.chartsSearch.insert){
        this.chartsSearch.boolDatabase = true;
      }
    }
  },

});
AdmVue.init(vm);