import {Component, OnInit} from '@angular/core';
import {SystemService} from '../system/system.service';
import {LocalStorageService} from 'ngx-webstorage';
import {NzMessageService} from 'ng-zorro-antd';
import {UtilService} from '../shared/common/util.service';

@Component({
    selector: 'smart-mine',
    templateUrl: './mine.component.html',
    styles: []
})
export class MineComponent implements OnInit {

    editCache = [];
    dataSet = [];

    constructor(private systemSer: SystemService, private localStorage: LocalStorageService,
                private message: NzMessageService, private util: UtilService) {
    }

    ngOnInit() {
        this.getList();
    }

    getList() {
        this.systemSer.getMenuBySeparation().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.dataSet = res.data;
                    this.updateEditCache(null);
                }
            }
        );
    }

    updateEditCache(num: number): void {
        for (let i = 0; i < this.dataSet.length; i++) {
            this.dataSet[i].key = i.toString();
        }
        this.dataSet.forEach((item, index) => {
            item.key = index;
            if (!this.editCache[item.key]) {
                this.editCache[item.key] = {
                    edit: false,
                    data: item
                };
            }
            if (item.key == num) {
                this.editCache[item.key].edit = true;
            }
        });
    }

    add() {
        this.dataSet.forEach((e, index) => e.key = index + 1);
        const item = {
            name: '',
            parentId: '',
            code: '',
            url: '',
            imageUrl: '',
            showOrder: '',
            key: 0
        };
        this.dataSet = [item, ...this.dataSet];
        this.editCache = [{data: item, edit: true}, ...this.editCache];
    }

    startEdit(key: string): void {
        this.editCache[key].edit = true;
    }

    cancelEdit(key: string): void {
        this.editCache[key].edit = false;
    }

    saveEdit(key: string): void {
        const index = this.dataSet.findIndex(item => item.key === key);
        this.dataSet[index] = this.editCache[key].data;
        this.editCache[key].edit = false;
        console.log(this.dataSet[index]);
        this.systemSer.createMenu(this.dataSet[index]).subscribe(
            (res) => {
                this.message.success('保存成功');
            }
        );
    }

    deleteItem(id: string) {
        this.systemSer.deleteMenu(id).subscribe(
            (res) => {
                this.message.success('删除成功');
                this.getList();
            }
        );
    }

}
