import axios from 'axios';
import { config } from '../../config';

export default class BackgroundData {
    /* 当前登录用户 */
    LoginUser;
    /* 标题栏数据 */
    TopPoint = [
        {
            pointName: "TotalPower",// 实时总功率
            pointTag: "JSFW.NX_GD_XXX_XX_XX_XXX_XXX_CI0135",
            value: 0
        }, {
            pointName: "DailyPowerGeneration",// 日发电量
            pointTag: "JSFW.NX_GD_XXX_XX_XX_XXX_XXX_CI0088",
            value: 0
        }, {
            pointName: "GridPower",// 上网电量
            pointTag: "JSFW.NX_GD_XXX_XX_XX_XXX_XXX_CI0136",
            value: 0
        }, {
            pointName: "MonthlyPowerGeneration",// 月发电量
            pointTag: "JSFW.NX_GD_XXX_XX_XX_XXX_XXX_CI0146",
            value: 0
        }, {
            pointName: "AnnualPowerGeneration",// 年发电量
            pointTag: "JSFW.NX_GD_XXX_XX_XX_XXX_XXX_CI0037",
            value: 0
        },
    ];
    /* 推荐区数据 */
    Recommends = {
        "DWK": {
            stationName: "大武口光伏电站",
            content: "通讯中断",
            createTime: this.formatDate(new Date("2021-04-15 8:17:59"), 'YY-MM-DD hh:mm'),
            isActive: true,
        },
        "NSSFCJSFW.NX_GD_NSSF_XX_XX_XXX_XXX_CI0263": {
            stationName: "牛首山风电场",
            content: "限电",
            createTime: new Date(),
            isActive: false,
        },
        "QSFCJSFW.NX_GD_QSF_XX_XX_XXX_XXX_CI0263": {
            stationName: "青山风电场",
            content: "限电",
            createTime: new Date(),
            isActive: false,
        },

        "SBQFCJSFW.NX_GD_SBQF_XX_XX_XXX_XXX_CI0263": {
            stationName: "石板泉一期",
            content: "限电",
            createTime: new Date(),
            isActive: false,
        },
        "MHSFCJSFW.NX_GD_MHSF_XX_XX_XXX_XXX_CI0263": {
            stationName: "麻黄山风电场",
            content: "限电",
            createTime: new Date(),
            isActive: false,
        },
        "XSFCJSFW.NX_GD_XSF_XX_XX_XXX_XXX_CI0263": {
            stationName: "香山风电场",
            content: "限电",
            createTime: new Date(),
            isActive: false,
        },
        "SLAGC.NX_GD_QSF_DQ_P1_L1_001_DI0165": {
            stationName: "青山三期",
            content: "限电",
            createTime: new Date(),
            isActive: false,
        },
        "SBQFCJSFW.NX_GD_SBQF_XX_XX_XXX_XXX_CI026X": {
            stationName: "石板泉二三四期",
            content: "限电",
            createTime: new Date(),
            isActive: false,
        },
    };
    /* 隐患数据 */
    HiddenProblems = new Array();
    /* 缺陷数据 */
    Defects = new Array();
    /* 故障数据 */
    Failure = new Array();
    /* 事故数据 */
    Accidents = new Array();

    /* 标记数据 */
    Marks = [];
    MarkIndex = 0;

    constructor() {
        this.refreshTPData = this.refreshTPData.bind(this);
        this.onTPMessage = this.onTPMessage.bind(this);
        this.refreshAlarmData = this.refreshAlarmData.bind(this);
        this.onHiddenProblemsMessage = this.onHiddenProblemsMessage.bind(this);
        this.formatDate = this.formatDate.bind(this);
        this.onDefectsMessage = this.onDefectsMessage.bind(this);
        this.onAccidentsMessage = this.onAccidentsMessage.bind(this);
        this.isContains = this.isContains.bind(this);
        this.refreshRecommendData = this.refreshRecommendData.bind(this);
        this.onRDMessage = this.onRDMessage.bind(this);
        this.windturbineControl = this.windturbineControl.bind(this);
        this.marking = this.marking.bind(this);
        this.removeMarked = this.removeMarked.bind(this);
        this.initWinturbineBaseData=this.initWinturbineBaseData.bind(this);
        

        this.refreshTPData();
        this.refreshAlarmData();
        this.refreshRecommendData();

        this.refreshTPTimer = setInterval(this.refreshTPData, 3000);// 标题栏数据
        this.refreshAlarmTimer = setInterval(this.refreshAlarmData, 10000);// 报警数据
        this.refreshRecommendTimer = setInterval(this.refreshRecommendData, 3000);// 推荐数据
    }

    /* 数据刷新 */
    refreshTPData() {
        // http://192.168.10.18:8011/ts
        var val = '';
        for (var v in this.TopPoint) {
            val += this.TopPoint[v].pointTag + ',';
        }
        axios.get(`http://${config.adapterUrl}/ts/latest?keys=${val}`)
            .then(this.onTPMessage)
            .catch(err =>
                console.log(err)
            );
    }

    /* 刷新推荐信息 */
    refreshRecommendData() {
        var val = '';
        for (var v in this.Recommends) {
            val += v + ',';
        }
        axios.get(`http://${config.adapterUrl}/ts/latest?keys=${val}`)
            .then(this.onRDMessage)
            .catch(err =>
                console.log(err)
            );
    }

    /* 刷新报警信息 */
    refreshAlarmData() {
        // http://192.168.10.18:8075/alarm
        // 1、读取一天内的所有open的4级custom报警，作为隐患数据ar
        var enddt = new Date();
        var tm = enddt.getTime();
        enddt = new Date(tm + 900000);
        var startdt = new Date(tm - 86400000);
        axios.get(`http://${config.shardingUrl}/alarm/snap/page?pagenum=1&pagesize=500&category1=custom&rank=4&isopened=1&starttime=${this.formatDate(startdt)}&endtime=${this.formatDate(enddt)}`)
            .then(this.onHiddenProblemsMessage)
            .catch(err =>
                console.log(err)
            );
        // 2、读取一天内所有的open的windturbine报警，以故障结尾的报警填充到故障，其他的填充到缺陷
        axios.get(`http://${config.shardingUrl}/alarm/snap/page?pagenum=1&pagesize=500&category1=windturbine&isopened=1&starttime=${this.formatDate(startdt)}&endtime=${this.formatDate(enddt)}`)
            .then(this.onDefectsMessage)
            .catch(err =>
                console.log(err)
            );
        // 3、读取一天内所有open的升压站（SYZ）报警，包含关键字“跳闸”，“开关”，“刀闸”，“断路器”字符的报警信息填充到事故列表
        axios.get(`http://${config.shardingUrl}/alarm/snap/page?pagenum=1&pagesize=500&category1=SYZ&isopened=1&starttime=${this.formatDate(startdt)}&endtime=${this.formatDate(enddt)}`)
            .then(this.onAccidentsMessage)
            .catch(err =>
                console.log(err)
            );
    }

    /* 获得故障数据 */
    onAccidentsMessage(msg) {
        if (!msg.data) return;
        this.Accidents = new Array();
        for (var v in msg.data.records) {
            var val = msg.data.records[v];
            if (this.isContains(val.alertText, ["跳闸", "开关", "刀闸", "断路器", "合位", "分位"])) {
                // todo 暂时隐藏事故报警
                //this.Accidents.push(val);
            } else {
                if (val.rank == "5") {
                    this.Failure.push(val);
                } else {
                    this.Defects.push(val);
                }
            }
        }
    }

    /* 获得缺陷数据 */
    onDefectsMessage(msg) {
        if (!msg.data) return;
        this.Defects = new Array();
        this.Failure = new Array();
        for (var v in msg.data.records) {
            var val = msg.data.records[v];
            if (val.alertText.indexOf("故障") > 0) {
                this.Failure.push(val);
            } else {
                this.Defects.push(val);
            }
        }
    }

    /* 获得隐患数据 */
    onHiddenProblemsMessage(msg) {
        if (!msg.data) return;
        this.HiddenProblems = msg.data.records;
    }

    /* 获得标题栏数据 */
    onTPMessage(msg) {
        if (!msg.data) return;
        for (var v in this.TopPoint) {
            var val = this.TopPoint[v];
            val.value = msg.data[val.pointTag].doubleValue;
        }
    }

    /* 获得推荐信息数据 */
    onRDMessage(msg) {
        if (!msg.data) return;
        for (var v in msg.data) {
            var isact = false;
            if (!msg.data[v].doubleValue) {
                isact = msg.data[v].booleanValue
            } else {
                isact = msg.data[v].doubleValue != 0;
            }
            if (isact && !this.Recommends[v].isActive) {
                this.Recommends[v].createTime = this.formatDate(new Date(), 'YY-MM-DD hh:mm');
            }
            this.Recommends[v].isActive = isact;
        }
    }

    /* 格式化时间 */
    formatDate(time, format = 'YY-MM-DD hh:mm:ss') {
        var date = new Date(time);

        var year = date.getFullYear(),
            month = date.getMonth() + 1,//月份是从0开始的
            day = date.getDate(),
            hour = date.getHours(),
            min = date.getMinutes(),
            sec = date.getSeconds();
        var preArr = Array.apply(null, Array(10)).map(function (elem, index) {
            return '0' + index;
        });

        var newTime = format.replace(/YY/g, year)
            .replace(/MM/g, preArr[month] || month)
            .replace(/DD/g, preArr[day] || day)
            .replace(/hh/g, preArr[hour] || hour)
            .replace(/mm/g, preArr[min] || min)
            .replace(/ss/g, preArr[sec] || sec);

        return newTime;
    }

    /* 判断一个字符串中是否包含第二个字符串列表中的字符 */
    isContains(str, strs) {
        for (var v in strs) {
            if (str.indexOf(strs[v]) > 0) {
                return true;
            }
        }
        return false;
    }
    
    /* 登录 */
    login(uname, psd, action) {
        axios.get(`http://${config.calcUrl}/api/user/login?userName=${uname}&psd=${psd}`)
            .then(action)
            .catch(err => action("登录出现错误：" + err.message));
    }

    /* 风机控制 */
    windturbineControl(windturbines, isLockOrUnlock,success,error) {
        var pairs = {};
        for (var ind in windturbines) {
            var wb = windturbines[ind];
            var ct = {
                windturbineId: wb.windturbineId,
                stationId: wb.stationId,
                projectId: wb.projectId,
                modelId: wb.modelId,
                controlType: wb.controlType,
                lockType: wb.lockType,
                userName: this.LoginUser.userName,
                userId: this.LoginUser.id,
            };
            pairs[ct.windturbineId] = ct;
        }
        axios.post(`http://${config.calcUrl}/api/control/send?isLockOrUnlock=${isLockOrUnlock}`, pairs)
            .then(msg => {
                success(msg);
            })
            .catch(err => {
                error(err);
            });
        console.log(isLockOrUnlock);
    }

    /* 系统控制风机，自动下发命令 */
    windturbineControlSystem(windturbines) {
        var pairs = {};
        for (var ind in windturbines) {
            var wb = windturbines[ind];
            var ct = {
                windturbineId: wb.windturbineId,
                stationId: wb.stationId,
                projectId: wb.projectId,
                modelId: wb.modelId,
                controlType: wb.controlType,
                lockType: wb.lockType,
                userName: 'system',
                userId: 0,
            };
            pairs[ct.windturbineId] = ct;
        }
        axios.post(`http://${config.calcUrl}/api/control/send?isLockOrUnlock=false`, pairs)
            .then(msg => {
                console.log(msg);
            })
            .catch(err => {
                this.showdialog("错误", "风机控制出现错误", err.message);
                console.log(err);
            });
    }

    /* 标记 */
    marking(windturbines) {
        for (var v in windturbines) {
            ++this.MarkIndex;
            this.Marks.push({ title: windturbines[v].windturbineId, id: this.MarkIndex });
        }
    }

    /* 移除标记 */
    removeMarked(mk) {
        var indx = -1;
        for (var id in this.Marks) {
            if (this.Marks[id].id == mk.id) {
                indx = id;
                break;
            }
        }
        if (indx < 0) return;
        this.Marks.splice(indx, 1);
    }

    /* 获取风机详情页面数据 */
    initWinturbineBaseData(info,action){
        axios.get(`http://${config.adapterUrl}/ts/latest?thingType=windturbine&thingId=${info.windturbineId}&uniformCodes=${info.codes}`)
        .then(msg=>{
            action(msg.data);
        })
        .catch(err=>{
            console.log(err);
        });
    }

    /* 单例 */
    static getInstance() {
        if (!BackgroundData.instance) {
            BackgroundData.instance = new BackgroundData();
        }
        return BackgroundData.instance;
    }
}