<div class="modal-ext-wr" style="display: none;">
  <div class="modal-ext-txt"><p>Вы вышли с режима редактирования<br/>сохранить изменения?</p></div>
  <div class="modal-ext-btn">
    <div>
      <span class="save_">сохранить</span>
      <span class="dont_save_">нет</span>
    </div>
  </div>
</div>

<div class="app-groups-wr" id="app">
  
  <table class="table table-striped table-bordered">
    <thead>
      <tr>
        <th class="header-adm"><span>Название</span></th>
        <th class="header-adm"><a v-on:click.prevent="changeSort()" href="#" data-sort="sort"><b>Сортировка</b></a></th>
      </tr>
    </thead>
    <tbody>
      
      <template v-for="item in items">
        
        <tr :key=item.id>
          <td v-bind:class="item.id == activeGroup ? 'title-adm active' : 'title-adm'">
            <a v-on:click="editGroup(item.id)" href="#" class="groups-title-wr">
              <span v-bind:class="item.id == activeGroup ? 'fa fa-chevron-up' : 'fa fa-chevron-down'"></span>
              {{item.language.title}}
            </a>
            <div class="buttons-tools-wr buttons-tools-wr-group">
              
              <a v-bind:href="url + '/update?id=' + item.id" title="Update" aria-label="Update" data-pjax="0">
                <span class="my-ico-tools my-pencil"></span>
              </a>
              <a v-bind:href="url + '/delete?id=' + item.id" title="Delete" aria-label="Delete" data-pjax="0" data-confirm="Вы уверены, что хотите удалить этот элемент?" data-method="post">
                <span class="my-ico-tools my-trash"></span>
              </a>
            </div>
          </td>
          <td class="position-adm">
            <div class="pos-adm-wr">
              <span v-on:click="sortDown(item)" class="pos-minus-adm"></span>
              <input v-model="item.sort" type="text" title="">
              <span v-on:click="sortUp(item)" class="pos-pluse-adm"></span>
            </div>
            <div v-on:click="sortSave(item)" class="pos-adm-ok">
              <div>ok</div>
            </div>
          </td>
        </tr>
        
        <template v-if="item.id === activeGroup">
          
          <tr :key="0">
            <td colspan="2" class="hidden-td-groups">
              <div class="hidden-grops">
                <ul class="list-edit-groups">
                  <li v-if="option.id != updateOption.optionId" v-for="option in options">
                    
                    <div class="pos-adm-wr-num">
                      <div class="pos-adm-wr">
                        <span v-on:click="sortDown(option)" class="pos-minus-adm"></span>
                        <input v-model="option.sort" type="text" title="">
                        <span v-on:click="sortUp(option)" class="pos-pluse-adm "></span>
                      </div>
                      <div v-on:click="sortSaveOption(option, item.id)" class="pos-adm-ok">
                        <div>ok</div>
                      </div>
                    </div>
                    
                    <div class="buttons-tool-groups">
                      <span v-on:click="editOption(option.id)" class="my-ico-tools my-pencil"></span>
                      <span v-on:click="deleteOption(option.id)" class="my-ico-tools my-trash"></span>
                    </div>
                    
                    <span class="name">{{option.value}}</span>
                  
                    <template v-if="item.type === 1">
                      <div class="name adm-color-wr"><div><b :style="'background: ' + option.extra"></b>{{option.extra}}</div></div>
                    </template>
  
                    <template v-if="item.type === 2">
                      <div>
                        <img v-bind:src="'/storage/options/thumb/' + option.extra" alt="" />
                      </div>
                    </template>
                    
                  </li>
                  <li v-else class="active-groups-li">
                    
                    <div class="pos-adm-wr-num">
                      <div class="pos-adm-wr">
                        <span v-on:click="sortDown(option)" class="pos-minus-adm"></span>
                        <input v-model="option.sort" type="text" title="">
                        <span v-on:click="sortUp(option)" class="pos-pluse-adm"></span>
                      </div>
                      <div v-on:click="sortSaveOption(option, item.id)" class="pos-adm-ok">
                        <div>ok</div>
                      </div>
                    </div>
                    
                    <div class="td-inputs-wrapp-wrapp td-inputs-wrapp-wrapp-collors">
                      <template v-for="language in languages">
                        
                        <template>
                          
                          <div class="td-inputs-wrapp">
                            <span>{{language.url}}</span>
                            <label>Значение</label>
                            <input class="form-control" title="" v-model="updateOption.data[language.id].value" type="text">
                          </div>
                        </template>
                        <template>
                          <div class="td-inputs-wrapp">
                            <span>{{language.url}}</span>
                            <label>Ссылка</label>
                            <input class="form-control" title="" v-model="updateOption.data[language.id].alias" type="text">
                          </div>
                        </template>
                        
                      </template>
                      
                      <template v-if="item.type === 1">
                        <div class="td-inputs-wrapp">
                          <label>Цвет</label>
                          <colorpicker :color="updateOption.extra" v-model="updateOption.extra" />
                        </div>
                      </template>
  
                      <template v-if="item.type === 2">
                        <label>File
                          <input type="file" id="option-file" ref="file" v-on:change="handleFileUpload(updateOption, 'option-file')"/>
                        </label>
                      </template>
                      
                    </div>
                    
                    <div class="buttons-wrapp-save-exit-group colors-buttons_">
                      <span class="btn btn-success" v-on:click="updateOptionData()">Сохранить</span>
                      <span class="fa fa-sign-out btn_exit" v-on:click="exitOptionEdit()"></span>
                    </div>
                  </li>
                </ul>
                
                
                <template v-if="showCreate">
                  
                  <div class="td-inputs-wrapp-wrapp td-inputs-wrapp-wrapp-add">
                    <template v-for="language in languages">
                      <template>
                        <div class="td-inputs-wrapp">
                          <span>{{language.url}}</span>
                          <label>Значение</label>
                          <input title="" v-model="newOption.data[language.id].value" type="text">
                        </div>
                      </template>
                      <template>
                        <div class="td-inputs-wrapp">
                          <span>{{language.url}}</span>
                          <label>Ссылка</label>
                          <input title="" v-model="newOption.data[language.id].alias" type="text">
                        </div>
                      </template>
                    </template>
                    
                    <template v-if="item.type === 1">
                      <div class="td-inputs-wrapp">
                        <label>Цвет</label>
                      <colorpicker :color="newOption.extra" v-model="newOption.extra" />
                      </div>
                    </template>
  
                    <template v-if="item.type === 2">
                      <label>File
                        <input type="file" id="file" ref="file" v-on:change="handleFileUpload(newOption, 'file')"/>
                      </label>
                    </template>
                    
                    <div class="buttons-wrapp-save-exit-group">
                      <span class="btn btn-success" v-on:click="saveOption()">Сохранить</span>
                      <span class="btn_hide" v-on:click="showCreate = false"></span>
                    </div>
                  </div>
                
                </template>
                
                <template v-else>
                  <div class="style" style="margin-left: 33px;">
                    <div v-on:click="showCreate = true" class="add-new-group-wr">
                      <span class="add-new-group fa fa-plus"></span>добавить характеристику
                    </div>
                  </div>
                </template>
                
              </div>
            </td>
          </tr>
        
        </template>
      
      </template>
    
    
    </tbody>
  </table>

</div>

<script>

    var Chrome = VueColor.Chrome;
    Vue.component('colorpicker', {
        components: {
            'chrome-picker': Chrome,
        },
        template: '<div class="input-group color-picker" ref="colorpicker">\n'
                  + '\t<input type="text" class="form-control" v-model="colorValue" @focus="showPicker()" @input="updateFromInput" />\n'
                  + '\t<span class="input-group-addon color-picker-container">\n'
                  + '\t\t<span class="current-color" :style="\'background-color: \' + colorValue" @click="togglePicker()"></span>\n'
                  + '\t\t<chrome-picker :value="colors" @input="updateFromPicker" v-if="displayPicker" />\n' + '\t</span>\n' + '</div>',
        props: [ 'color' ],
        data() {
            return {
                colors: {
                    hex: '#000000',
                },
                colorValue: '',
                displayPicker: false,
            }
        },
        mounted() {
            this.setColor(this.color || '#000000');
        },
        methods: {
            setColor(color) {
                this.updateColors(color);
                this.colorValue = color;
            },
            updateColors(color) {
                if (color.slice(0, 1) == '#') {
                    this.colors = {
                        hex: color
                    };
                } else if (color.slice(0, 4) == 'rgba') {
                    var rgba = color.replace(/^rgba?\(|\s+|\)$/g, '')
                                    .split(','),
                        hex = '#' + ((1 << 24) + (parseInt(rgba[ 0 ]) << 16) + (parseInt(rgba[ 1 ]) << 8) + parseInt(rgba[ 2 ])).toString(16)
                                                                                                                                .slice(1);
                    this.colors = {
                        hex: hex,
                        a: rgba[ 3 ],
                    }
                }
            },
            showPicker() {
                document.addEventListener('click', this.documentClick);
                this.displayPicker = true;
            },
            hidePicker() {
                document.removeEventListener('click', this.documentClick);
                this.displayPicker = false;
            },
            togglePicker() {
                this.displayPicker ? this.hidePicker() : this.showPicker();
            },
            updateFromInput() {
                this.updateColors(this.colorValue);
            },
            updateFromPicker(color) {
                this.colors = color;
                if (color.rgba.a == 1) {
                    this.colorValue = color.hex;
                } else {
                    this.colorValue = 'rgba(' + color.rgba.r + ', ' + color.rgba.g + ', ' + color.rgba.b + ', ' + color.rgba.a + ')';
                }
            },
            documentClick(e) {
                var el = this.$refs.colorpicker, target = e.target;
                if (el !== target && !el.contains(target)) {
                    this.hidePicker()
                }
            }
        },
        watch: {
            colorValue(val) {
                if (val) {
                    this.updateColors(val);
                    this.$emit('input', val);
                }
            }
        },
    });

    var url = '/admin/filter/group';

    var app = new Vue({
        el: '#app',

        data: {
            url: url,
            file : '',
            languages: null,
            items: null,
            activeGroup: null,
            options: [],
            newOption: null,
            updateOption: {},
            showCreate: false,
            openModalEvent: null,
            sort: 'asc'
        },
        created: function() {
            this.fetchData();
            document.addEventListener('save-groups', this.saveOption);
            this.openModalEvent = new Event('open-groups-modal');
        },
        methods: {
            fetchData: function() {
                var self = this;

                axios.post(url + '/index?sort=' + self.sort)
                     .then(function(response) {
                         self.items = response.data;
                     });

                axios.post(url + '/languages')
                     .then(function(response) {
                         self.languages = response.data;
                     });
            },
            sortUp: function(item) {
                item.sort++;
            },
            sortDown: function(item) {
                if (item.sort > 1) {
                    item.sort--;
                }
            },
            sortSave: function(item) {
                var self = this;
                axios.get(url + '/sort?id=' + item.id + '&sort=' + item.sort)
                     .then(function() {
                         self.fetchData();
                     });
            },
            sortSaveOption: function(item, groupId) {
                var self = this;
                axios.get(url + '/sort-option?id=' + item.id + '&sort=' + item.sort + '&groupId=' + groupId)
                     .then(function(response) {
                         self.exitOptionEdit();
                         self.options = response.data;
                     });
            },
            editGroup: function(id) {
                if (this.newOption !== null) {
                    document.dispatchEvent(this.openModalEvent);
                }
                if (this.activeGroup === id) {
                    this.activeGroup = null;
                } else {

                    var self = this;
                    axios.get(url + '/options?id=' + id)
                         .then(function(response) {
                             console.log(response.data);

                             self.showCreate = false;
                             self.activeGroup = id;
                             self.newOption = {};
                             self.newOption[ 'data' ] = {};

                             for (langUrl in self.languages) {
                                 self.newOption.data[ self.languages[ langUrl ].id ] = {
                                     'value': null,
                                     'alias': null,
                                     'language_id': self.languages[ langUrl ].id
                                 }
                             }

                             self.newOption[ 'sort' ] = null;
                             self.newOption[ 'groupId' ] = id;
                             self.newOption[ 'extra' ] = null;
                             
                             self.options = response.data;
                         });
                }
            },
            saveOption: function() {
                console.log(this.newOption);
                var groupId = this.newOption.groupId;
                var self = this;
                
                var formData = new FormData();

                if (this.file !== '') {
                    formData.append('file', this.file);
                }
                
                formData.append('data', JSON.stringify(this.newOption));
                
                axios.post(url + '/create-option', formData,  {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                     .then(function(response) {
                         console.log(response.data);
                         axios.get(url + '/options?id=' + groupId)
                              .then(function(response) {
                                  console.log(response.data);
                                  self.options = response.data;
                              });
                     });
            },
            updateOptionData: function() {
                console.log(this.updateOption);
                var groupId = this.activeGroup;
                var self = this;

                var formData = new FormData();

                if (this.file !== '') {
                    formData.append('file', this.file);
                }

                formData.append('data', JSON.stringify(this.updateOption));
                
                axios.post(url + '/update-option', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                     .then(function(response) {
                         console.log(response.data);
                         axios.get(url + '/options?id=' + groupId)
                              .then(function(response) {
                                  console.log(response.data);
                                  self.options = response.data;
                                  self.updateOption = {};
                              });
                     });
            },
            editOption: function(id) {
                var self = this;
                axios.get(url + '/option?id=' + id)
                     .then(function(response) {
                         self.updateOption = response.data;
                     })
            },
            deleteOption: function(id) {
                var groupId = this.activeGroup;
                var self = this;
                axios.post(url + '/delete-option?id=' + id)
                     .then(function(response) {
                         console.log(response.data);
                         axios.get(url + '/options?id=' + groupId)
                              .then(function(response) {
                                  console.log(response.data);
                                  self.options = response.data;
                              });
                     });
            },
            exitOptionEdit: function() {
                this.updateOption = {};
            },
            changeSort: function() {
                if (this.sort === 'asc') {
                    this.sort = 'desc';
                    this.fetchData();
                } else if (this.sort === 'desc') {
                    this.sort = 'asc';
                    this.fetchData();
                }
            },
            handleFileUpload: function(option, inputId) {
                option.extra = 'save_file';
                this.file = document.getElementById(inputId).files[0];
            },
        }
    });
</script>