import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {OverAllService} from '../../overAll/overAll.service';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
    selector: 'smart-website',
    templateUrl: './website.component.html',
    styles: [
            `
            .middle {
                height: 39px;
                line-height: 39px;
            }

            .modal-footer-btn {
                margin: 10px 0;
                text-align: center;
            }

            .trigger-class {
                border: 1px solid #ddd;
                padding: 10px;
                margin: 10px;
            }
        `
    ]
})
export class WebsiteComponent implements OnInit {

    @Output() done = new EventEmitter<any>();
    isVisible = false;
    isOkLoading = false;
    title;
    tabNum = 0;
    indexNo = 1;

    validateForm;
    steps = [];

    constructor(private overAllSer: OverAllService, private message: NzMessageService) {
    }

    ngOnInit() {
        this.initForm();
    }

    initForm() {
        this.tabNum = 0;
        this.steps = [
            {
                name: '',
                url: '',
                status_codes: 200,
                posts: '',
                no: this.indexNo,
                timeout: '15',
                follow_redirects: '1',
                conditionList: [],
                condition: '',
                faultConditionList: [],
                faultCondition: '',
                show: false
            }
        ];
        this.validateForm = {
            name: '',
            delay: '',
            retries: '',
            http_proxy: '',
            ssl_cert_file: '',
            ssl_key_file: '',
            ssl_key_password: '',
            steps: this.steps,
        };
    }

    showAddModal() {
        this.title = '添加网站监测';
        this.isVisible = true;
    }

    showEditModal(id) {
        this.title = '编辑网站监测';
        this.isVisible = true;
        this.overAllSer.findWeb(id).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    res.data.steps.forEach(e => {
                        e.follow_redirects += '';
                    });
                    this.validateForm = res.data;
                    this.steps = res.data.steps;
                    this.viewtrigger();
                }
            }
        );
    }

    //回显阈值
    viewtrigger() {
        this.steps.forEach(e => {
            if (e.condition) {
                e.condition = ' and ' + e.condition;
                let strCon = e.condition.split(' ');
                let arrCon = [];
                let andArrCon = [];
                strCon.forEach((value) => {
                    if (value.length > 0) {
                        if (value == 'and' || value == 'or') {
                            andArrCon.push(value);
                        } else {
                            const index = value.indexOf('}');
                            if (value.indexOf('0.0.0.0:web.test.time') > -1) {   //响应时间
                                const obj1 = {
                                    time: '0',
                                    equal: value[index + 1],
                                    value: value.substr(index + 2, value.length),
                                };
                                arrCon.push(obj1);
                            }
                            if (value.indexOf('0.0.0.0:web.test.rspcode') > -1) {   //响应代码
                                const obj2 = {
                                    time: '1',
                                    equal: value[index + 1],
                                    value: value.substr(index + 2, value.length),
                                };
                                arrCon.push(obj2);
                            }
                        }
                    }
                });
                arrCon.forEach((value, index) => {
                    value.and = ' ' + andArrCon[index] + ' ';
                });
                e.conditionList = arrCon;
            }else{
                e.condition = '';
                e.conditionList = [];
            }
            if (e.faultCondition) {
                e.faultCondition = ' and ' +e.faultCondition;
                let strFau = e.faultCondition.split(' ');
                let arrFau = [];
                let andArrFau = [];
                strFau.forEach((value) => {
                    if (value.length > 0) {
                        if (value == 'and' || value == 'or') {
                            andArrFau.push(value);
                        } else {
                            const index = value.indexOf('}');
                            if (value.indexOf('0.0.0.0:web.test.time') > -1) {   //响应时间
                                const obj1 = {
                                    time: '0',
                                    equal: value[index + 1],
                                    value: value.substr(index + 2, value.length),
                                };
                                arrFau.push(obj1);
                            }
                            if (value.indexOf('0.0.0.0:web.test.rspcode') > -1) {   //响应代码
                                const obj2 = {
                                    time: '1',
                                    equal: value[index + 1],
                                    value: value.substr(index + 2, value.length),
                                };
                                arrFau.push(obj2);
                            }
                        }
                    }
                });
                arrFau.forEach((value, index) => {
                    value.and = ' ' + andArrFau[index] + ' ';
                });
                e.faultConditionList = arrFau;
            }else{
                e.faultCondition = '';
                e.faultConditionList = [];
            }
        });
    }

    handleOk() {
        if (!this.validateForm.name) {
            this.message.error('请输入网站名称');
            return false;
        }
        if (!this.validateForm.delay) {
            this.message.error('请输入更新间隔');
            return false;
        }
        this.isOkLoading = true;

        this.getCondition();

        if (this.title == '添加网站监测') {
            this.create();
        } else {
            this.update();
        }
    }

    //创建
    create() {
        this.overAllSer.createWebscenario(this.validateForm).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('添加成功');
                    this.isVisible = false;
                    this.done.emit();
                    this.initForm();
                }
                this.isOkLoading = false;
            }
        );
    }

    //更新
    update() {
        this.overAllSer.updateWebscenario(this.validateForm).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('保存成功');
                    this.isVisible = false;
                    this.done.emit();
                    this.initForm();
                }
                this.isOkLoading = false;
            }
        );
    }

    handleCancel() {
        this.initForm();
        this.isVisible = false;
        this.isOkLoading = false;
    }

    tabsChange(index) {
        this.tabNum = index;
    }

    // 合成阈值
    getCondition() {
        this.validateForm.steps.forEach(e => {   //步骤列表
            if(e.conditionList){
                e.condition = '';
                e.conditionList.forEach(e1 => {    //危险阈值列表
                    if (e1.time == '0') {   //响应时间
                        e.condition += e1.and + '{0.0.0.0:web.test.time[' + this.validateForm.name + ',' + e.name + ',resp].last()}' + e1.equal + e1.value;
                    }
                    if (e1.time == '1') {   //响应代码
                        e.condition += e1.and + '{0.0.0.0:web.test.rspcode[' + this.validateForm.name + ',' + e.name + '].last()}' + e1.equal + e1.value;
                    }
                });
            }
            if(e.faultConditionList){
                e.faultCondition = '';
                e.faultConditionList.forEach(e2 => {    //故障阈值列表
                    if (e2.time == '0') {   //响应时间
                        e.faultCondition += e2.and + '{0.0.0.0:web.test.time[' + this.validateForm.name + ',' + e.name + ',resp].last()}' + e2.equal + e2.value;
                    }
                    if (e2.time == '1') {   //响应代码
                        e.faultCondition += e2.and + '{0.0.0.0:web.test.rspcode[' + this.validateForm.name + ',' + e.name + '].last()}' + e2.equal + e2.value;
                    }
                });
            }
        });
    }

    //添加步骤
    addStep() {
        this.indexNo += 1;
        const data =
            {
                name: '',
                url: '',
                status_codes: 200,
                posts: '',
                no: this.indexNo,
                timeout: '15',
                follow_redirects: '1',
                condition: '',
                conditionList: [],
                faultCondition: '',
                faultConditionList: [],
                show: false,
            };
        this.steps.push(data);
    }

    showCon(i) {
        this.steps[i].show = true;
    }

    closeCon(i, bool) {
        if (!bool) {
            this.steps[i].conditionList = [];
            this.steps[i].faultConditionList = [];
        }
        this.steps[i].show = false;
    }

    //删除步骤
    deleteStep(index) {
        this.steps.splice(index, 1);
    }

    /**
     * 故障阈值添加
     * @param i  步骤下标
     */
    addFault(i) {
        const demo = {
            time: '0',
            and: ' and ',
            equal: '=',
            value: '',
        };
        this.steps[i].faultConditionList.push(demo);
    }

    /**
     * 危险阈值增加
     * @param i 步骤下标
     */
    addcondition(i) {
        const demo = {
            time: '0',
            and: ' and ',
            equal: '=',
            value: '',
        };
        this.steps[i].conditionList.push(demo);
    }

    /**
     * 删除故障阈值
     * @param i  步骤下标
     * @param index  故障下标
     */
    deleteFault(i, index) {
        this.steps[i].faultConditionList.splice(index, 1);
    }

    /**
     * 删除危险阈值
     * @param i  步骤下标
     * @param index  故障下标
     */
    deleteCondition(i, index) {
        this.steps[i].conditionList.splice(index, 1);
    }
}
