import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, ModalController, ToastController, AlertController} from 'ionic-angular';
import {SelectTypePage} from "../select-type/select-type";
import {AppService} from "../../../../../service/http.service";
import {message} from "../../../../../app/main";
import {CreatePage} from "../create/create";
import {DesicrPage} from "../desicr/desicr";

@IonicPage()
@Component({
    selector: 'page-edit',
    templateUrl: 'edit.html',
})
export class EditPage {

    tempId;
    editIndex;
    temp = {
        title: '',
        id: '',
        explai: '',   //问卷说明
        usergroup: null,  //用户组id
        isopen: null,  //是否公开
        isans: null,   //是否匿名
        state: null   //状态
    };
    contentList = [];

    constructor(public navCtrl: NavController, public navParams: NavParams,
                public modalCtrl: ModalController, public appService: AppService,
                public toastCtrl: ToastController, public alertCtrl: AlertController) {
    }

    ionViewDidLoad(){
        this.tempId = this.navParams.get('temp').id;
    }

    ionViewDidEnter() {
        this.getDetail();
        const length = this.navCtrl.length();
        if (length > 5) {
            this.navCtrl.remove(3, length - 4);
        }
    }


    getDetail() {
        //问卷详情
        this.appService.ObserverHttpPostAdd('/wisdomgroup/modules/question/edit/', this.tempId).subscribe((res) => {
            this.temp = res.json().data;
        });
        //问卷题目详情
        this.appService.ObserverHttpGet('/wisdomgroup/modules/question/findQuesByQuestionId', {id: this.tempId})
            .subscribe(
                (res) => {
                    this.contentList = res.json().datalist;
                    for (let i = 0; i < this.contentList.length; i++) {
                        this.contentList[i].quesDesc = JSON.parse(this.contentList[i].quesDesc);
                    }
                }
            )
    }

    //添加题目
    add() {
        this.navCtrl.push('SelectTypePage', {
            temp: this.temp
        })
    }

    //操作
    itemEdit(index) {
        this.editIndex = index;
    }

    goEdit(index) {
        this.navCtrl.push('CreatePage', {
            edit: this.contentList,
            index: index,
            temp: this.temp
        });
    }

    swapArray(arr, index1, index2) {
        arr[index1] = arr.splice(index2, 1, arr[index1])[0];
        return arr;
    }

    //上移
    itemUp(index) {
        if (index != 0) {
            this.swapArray(this.contentList, index, index - 1);
        } else {
            alert('已经处于置底，无法下移');
        }
    }

    //下移
    itemDown(index) {
        if (index + 1 != this.contentList.length) {
            this.swapArray(this.contentList, index, index + 1);
        } else {
            // alert('已经处于置顶，无法上移');
        }
    }

    //删除
    itemDelete(index) {
        const confirm = this.alertCtrl.create({
            title: '确认删除该题目?',
            buttons: [
                {
                    text: '取消',
                    handler: () => {
                        console.log('Disagree clicked');
                    }
                },
                {
                    text: '确认',
                    handler: () => {
                        this.contentList.splice(index, 1);
                        this.editIndex = null;
                    }
                }
            ]
        });
        confirm.present();
    }

    //查看
    look() {
        this.navCtrl.push('DetailPage', {
            temp: this.temp
        });
    }

    //设置
    set() {
        this.navCtrl.push('SetPage', {
            id: this.temp.id
        });
    }

    //保存
    save() {

        const bodyData = {
            title: this.temp.title,   //问卷标题
            explai: this.temp.explai,   //问卷说明
            usergroup: this.temp.usergroup,  //用户组id
            isopen: this.temp.isopen,  //是否公开
            isans: this.temp.isans,   //是否匿名
            state: this.temp.state   //状态
        };
        //更新问卷信息
        this.appService.ObserverHttpForm('/wisdomgroup/modules/question/update/', this.temp.id, bodyData).subscribe((res) => {

        }, (err) => {

        });

        //更新题目信息
        let newArr = [];
        for (let i = 0; i < this.contentList.length; i++) {
            const arr = {
                questionId: this.temp.id,
                isAns: this.contentList[i].isAns,
                quesType: this.contentList[i].quesType,
                title: this.contentList[i].title,
                limit: this.contentList[i].limit,    //问答的字数限制
                quesDesc: this.contentList[i].quesDesc,
                minOps: this.contentList[i].minOps,
                maxOps: this.contentList[i].maxOps,
                index: i  //序号
            };
            newArr.push(arr);
        }
        const data = {
            array: JSON.stringify(newArr),
            id: this.temp.id
        };
        const toast = this.toastCtrl.create(message);
        this.appService.ObserverHttpPost('/wisdomgroup/modules/question/saveQuestion', data)
            .subscribe(
                (res) => {
                    toast.setMessage('编辑成功');
                    toast.present();
                    setTimeout((res) => {
                        this.getDetail();
                    }, 2000)
                }
            )
    }

    //编辑
    editQues(){
        this.navCtrl.push('DesicrPage',{id:this.temp.id});
    }

    //发布
    release(){
        this.appService.alert('确定发布该问卷吗',
            (res) => {
                this.appService.ObserverHttpGetAdd('/wisdomgroup/modules/question/submit/', this.temp.id)
                    .subscribe((res) => {
                        this.appService.popToastView('发布成功','middle',1000);
                        this.navCtrl.pop();
                    })
            }
        )
    }

}
