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: {},
      listBrandsAvailable: {},
      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],
          title: 'Tamanho',
        },
      ],
      equalSize: ['XPP', 'PP', 'P', 'M', 'G', 'GG', 'XGG', 'G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8'],
      babySize: ['Prematuro', '0-3', '3-6', '6-9', '9-12', '12-18', '18-24', '24-36'],
      kidsSize: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16'],
      tableType: '',
      mlDatabase: '',
      tableGender: '',
      sizeEqual: '',
      data: [],
    };
  },
  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));
    },
    changeObj(){
      if(this.tableType !== 'SNEAKERS'){
        const newData = this.data.map(obj=>{
          const { filtrable_size_array, filtrable_size_from, filtrable_size_to, keyName, ...body } = obj;
          return body;
        });   
        return newData;
      }; 
    }, 
    setTableGender(gender){
      if(gender === '19159491' || gender === "339668" || gender === "339667") return "(anos)";
      if(gender === '339665' || gender === '339666' || gender === '110461') return "";
      if(gender === '371795') return "(meses)";
    },
    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.changeObj() ? this.changeObj() : 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;
    },
    brandsAvailable(data) {
      this.listBrandsMl.names = this.listBrandsMl.names.filter(result => {
        return !data.some(item => item.SIZE_GRID_ID === result.id);
      });
    },
    //Find Charts in Database
    findChartSql() {
      axiosApi({
        method: 'POST',
        url: this.actionGetChartSql,
        data: param({ ajax: true }),
      })
        .then(({ data }) => {
          if (data) {
            this.brandsAvailable(data);
          }
        })
        .catch(err => console.log(err, err.response));
    },
    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) {
            this.tableGender = data.gender;
            this.title = [];
            this.title[0] = { selectopt: this.valueSize, name: 'tamanho', type: 'select', title: 'Tamanho' };
            this.checkDomain();
            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.mlDatabase = false;
                this.returnMLbrand(data.names[0].id);    
              } else {
                this.mlDatabase = true;
                this.findChartSql();       
              }
            } 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.
    },
    checkDomain() {
      if (this.chartsSearch.domain_id === 'MLB-SNEAKERS') {
        this.tableType = 'SNEAKERS';
        this.title.push(
          {
            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',
          }
        );
      } else {
        this.tableType = 'CLOTHING';
        this.tableGender = this.chartsSearch.gender;
        
        this.title.push(
          {
            name: 'filtrable_size',
            nameFrom: 'filtrable_size_from',
            nameTo: 'filtrable_size_to',
            nameArray: 'filtrable_size_array',
            type: 'selectEqual',
            mask: 'decimal',
            title: `Equivalências do tamanho  ${this.setTableGender(this.tableGender)}`,
            titleClass: 'center aligned',
            dataClass: 'center aligned',
            selectoptEqual: this.tableGender === "339668" || this.tableGender === "339667" || this.tableGender === "19159491" ?  this.kidsSize : this.equalSize,
            selectoptBaby: this.babySize,
          },
          {
            name: 'chest_circumference_from',
            nameTo: 'chest_circumference_to', 
            type: 'text',
            mask: 'decimal',
            title: 'Contorno do peito (cm)',
            titleClass: 'center aligned',
            dataClass: 'center aligned',
          },
          {
            name: 'waist_circumference_from',
            nameTo: 'waist_circumference_to', 
            title: 'Circunferência da cintura (cm)',
            type: 'text',
            mask: 'decimal',
            titleClass: 'center aligned',
            dataClass: 'center aligned',
          },
          {
            name: 'person_height_from',
            nameTo: 'person_height_to', 
            title: 'Altura da pessoa (cm)',
            type: 'text',
            mask: 'decimal',
            titleClass: 'center aligned',
            dataClass: 'center aligned',
          },
          {
            name: 'hip_circumference_from',
            nameTo: 'hip_circumference_to',
            title: 'Circunferência do quadril (cm)',
            type: 'text',
            mask: 'decimal',
            titleClass: 'center aligned',
            dataClass: 'center aligned',
          }
        );
      }
    },
    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)];

      if(this.chartsSearch.domain_id === 'MLB-SNEAKERS'){
        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'),
          });
        }
      }else{
       
        for (let i = 0; i < listDados.length; i++) {
          var newArrayReplace = [];
          var rawValue = listDados[i].attributes[0].values[0].name;
          var arrayEqual = Array.isArray(JSON.parse(rawValue)) ? JSON.parse(rawValue) : [JSON.parse(rawValue)];
          
          if(this.mlDatabase){
            let array = listDados[i].attributes[2].values;
            let newArray = [];
            array.map(item => {
              newArray.push(item.name);
            });
            arrayEqual = newArray;
          }

          arrayEqual.map(item=>{    
            newArrayReplace.push(item.substring(0, item.indexOf(' ')));  
          });
         
          if(newArrayReplace[0] !== ''){
            arrayEqual = newArrayReplace;
          }

          listAttib.push({
            id: listDados[i].id,  
            filtrable_size: arrayEqual,
            filtrable_size_array: arrayEqual, 
            filtrable_size_from: arrayEqual[0],  
            filtrable_size_to: arrayEqual[arrayEqual.length - 1],   
            chest_circumference_from: this.getInfo(listDados[i].attributes, 'CHEST_CIRCUMFERENCE_FROM'),
            waist_circumference_from: this.getInfo(listDados[i].attributes, 'WAIST_CIRCUMFERENCE_FROM'),
            chest_circumference_to: this.getInfo(listDados[i].attributes, 'CHEST_CIRCUMFERENCE_TO'),
            waist_circumference_to: this.getInfo(listDados[i].attributes, 'WAIST_CIRCUMFERENCE_TO'),
            person_height_from: this.getInfo(listDados[i].attributes, 'PERSON_HEIGHT_FROM'),
            person_height_to: this.getInfo(listDados[i].attributes, 'PERSON_HEIGHT_TO'),
            hip_circumference_from: this.getInfo(listDados[i].attributes, 'HIP_CIRCUMFERENCE_FROM'),
            hip_circumference_to: this.getInfo(listDados[i].attributes, 'HIP_CIRCUMFERENCE_TO'),
            tamanho: this.mlDatabase ? listDados[i].attributes[0].values[0].name : 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) {
          if(attr[j].values[0].name.includes("CM")){
            attr[j].values[0].name = attr[j].values[0].name.replace("CM",'').trim();
          }
          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);
