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

const vm = new AdmVue({
  components: {
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    BaseTabs: () => import(/* webpackChunkName: "BaseTabs" */ '@components/BaseTabs/index.vue'),
    BaseButton: () => import(/* webpackChunkName: "BaseButton" */ '@elements/BaseButton/index.vue'),
  },
  data() {
    return {
      configurations: {
        latest_title: '',
        latest_subtitle: '',
        latest_module: [],
      },
      layouts: [],
      disableForm: false,
      loadingBtn: false,
    };
  },
  methods: {
    convertToArray(value) {
      if (Array.isArray(value)) {
        return value;
      }

      return Object.values(value);
    },
    handleAddModuleClick() {
      let sortOrder = 0;
      const currentModule = this.convertToArray(this.configurations.latest_module);
      const lastItemInCurrentModule = currentModule[currentModule.length - 1];

      if (lastItemInCurrentModule) {
        const { sort_order } = lastItemInCurrentModule;
        sortOrder = Number(sort_order) + 1;
      }

      currentModule.push({
        limit: '24',
        sort_order: sortOrder,
      });

      this.configurations.latest_module = currentModule;
    },
    handleRemoveModuleClick(moduleIndex = 0) {
      const currentModule = this.convertToArray(this.configurations.latest_module);
      const isModuleEmpty = currentModule.length <= 0;

      if (isModuleEmpty) return;

      currentModule.splice(moduleIndex, 1);

      this.configurations.latest_module;
    },
    handleTypeChange(event, moduleIndex = 0) {
      const enumType = {
        CAROUSEL: '0',
        GRID: '1',
      };

      const { value } = event.target;
      const isGrid = value === enumType.GRID;
      const currentModule = this.configurations.latest_module[moduleIndex];

      if (isGrid) {
        return;
      }

      currentModule.limit = '24';
    },
  },
  mounted() {
    if (this.configurations.latest_module) {
      this.configurations.latest_module = this.convertToArray(this.configurations.latest_module).map(item => ({
        ...item,
        limit: item.limit || '24',
      }));
    }
  },
});

initVue(vm);
