// import axios from 'axios';
import api from "api/index";
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: false,
            stationID: 'DWK_AGC',
            values:'DWK'
        },
        "NSSFCJSFW.NX_GD_NSSF_XX_XX_XXX_XXX_CI0263": {
            stationName: "牛首山风电场",
            id: 'NSS_BT',
            content: "限电",
            createTime: new Date(),
            isActive: false,
            stationID: 'NSS_AGC',
            values:'NSSFCJSFW.NX_GD_NSSF_XX_XX_XXX_XXX_CI0263'
        },
        "QSFCJSFW.NX_GD_QSF_XX_XX_XXX_XXX_CI0263": {
            stationName: "青山风电场",
            content: "限电",
            createTime: new Date(),
            isActive: false,
            stationID: 'QS_AGC',
            id: 'QS_BT',
            values:'QSFCJSFW.NX_GD_QSF_XX_XX_XXX_XXX_CI0263'
        },

        "SBQFCJSFW.NX_GD_SBQF_XX_XX_XXX_XXX_CI0263": {
            stationName: "星能第六风电场",
            content: "限电",
            createTime: new Date(),
            isActive: false,
            stationID: 'XNL_AGC',
            id: 'XN6_BT',
            values:'SBQFCJSFW.NX_GD_SBQF_XX_XX_XXX_XXX_CI0263'
        },
        "MHSFCJSFW.NX_GD_MHSF_XX_XX_XXX_XXX_CI0263": {
            stationName: "麻黄山风电场",
            id: 'MHS_BT',
            content: "限电",
            createTime: new Date(),
            isActive: false,
            stationID: 'MHS_AGC',
            values:'MHSFCJSFW.NX_GD_MHSF_XX_XX_XXX_XXX_CI0263'
        },
        "XSFCJSFW.NX_GD_XSF_XX_XX_XXX_XXX_CI0263": {
            stationName: "香山风电场",
            content: "限电",
            createTime: new Date(),
            isActive: false,
            stationID: 'XS_AGC',
            id: 'XS_BT',
            values:'XSFCJSFW.NX_GD_XSF_XX_XX_XXX_XXX_CI0263'
        },
        "SBQFCJSFW.NX_GD_SBQF_XX_XX_XXX_XXX_CI026X": {
            stationName: "牛首山第五风电场",
            content: "限电",
            createTime: new Date(),
            isActive: false,
            stationID: 'NW_AGC',
            id: 'N5_BT',
            values:'SBQFCJSFW.NX_GD_SBQF_XX_XX_XXX_XXX_CI026X'
        },
        "SLAGC.NX_GD_QSF_DQ_P1_L1_001_DI0165": {
            stationName: "宋堡第六风电场",
            content: "限电",
            createTime: new Date(),
            isActive: false,
            stationID: 'QS3_AGC',
            id: 'SL_BT',
            values:'SLAGC.NX_GD_QSF_DQ_P1_L1_001_DI0165'
        },
    };
    /* 隐患数据 */
    HiddenProblems = new Array();
    /* 缺陷数据 */
    Defects = new Array();
    /* 故障数据 */
    Failure = new Array();
    /* 事故数据 */
    Accidents = new Array();

    /* 标记数据 */
    Marks = [];
    /* 校验区数据 */
    checkouts = [];
    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
        let val = '';
        for (let v in this.TopPoint) {
            val += this.TopPoint[v].pointTag + ',';
        }
        api.refreshData(val).then(this.onTPMessage)
        // axios.get(process.env.VUE_APP_ADAPTERURL+`/ts/latest?keys=${val}`)
        //     .then(this.onTPMessage)
        //     .catch(err =>
        //         console.log(err)
        //     );
    }

    /* 刷新推荐信息 */
    refreshRecommendData() {
        let val = '';
        for (let v in this.Recommends) {
            val += v + ',';
        }
        api.refreshData(val).then(this.onRDMessage)
        // axios.get(process.env.VUE_APP_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
        let enddt = new Date();
        let tm = enddt.getTime();
        enddt = new Date(tm + 900000);
        let startdt = new Date(tm - 86400000);
        api.getSnap({
            pagenum:'1',
            pagesize:'500',
            category1:'custom',
            isopened:'1',
            starttime:this.formatDate(startdt),
            endtime:this.formatDate(enddt),
        }).then(this.onHiddenProblemsMessage)
        api.getSnap({
            pagenum:'1',
            pagesize:'500',
            category1:'windturbine',
            isopened:'1',
            starttime:this.formatDate(startdt),
            endtime:this.formatDate(enddt),
        }).then(this.onHiddenProblemsMessage)
        api.getSnap({
            pagenum:'1',
            pagesize:'500',
            category1:'SYZ',
            isopened:'1',
            starttime:this.formatDate(startdt),
            endtime:this.formatDate(enddt),
        }).then(this.onHiddenProblemsMessage)
    }

    /* 获得故障数据 */
    onAccidentsMessage(msg) {
        if (!msg.data) return;
        this.Accidents = new Array();
        for (let v in msg.data.records) {
            let 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 (let v in msg.data.records) {
            let 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 (let v in this.TopPoint) {
            let val = this.TopPoint[v];
            val.value = msg.data[val.pointTag].doubleValue;
        }
    }

    /* 获得推荐信息数据 */
    onRDMessage(msg) {
        if (!msg.data) return;
        for (let v in msg.data) {
            let 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') {
        let date = new Date(time);

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

        let 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 (let v in strs) {
            if (str.indexOf(strs[v]) > 0) {
                return true;
            }
        }
        return false;
    }

    /* 登录 */
    // login(uname, psd, action) {
    //     axios.get(process.env.VUE_APP_API+`/api/user/login?userName=${uname}&psd=${psd}`)
    //         .then(action)
    //         .catch(err => action("登录出现错误：" + err.message));
    // }

    /* 风机控制 */
    windturbineControl(windturbines, isLockOrUnlock, automatic, test ,success, error) {
        let pairs = {};
        for (let ind in windturbines) {
            let wb = windturbines[ind];
            let ct = {
                windturbineId: wb.windturbineId,
                stationId: wb.stationId,
                projectId: wb.projectId,
                modelId: wb.modelId,
                controlType: wb.controlType,
                lockType: wb.lockType,
                userName: automatic?'system_'+this.LoginUser.name:this.LoginUser.name,
                userId: this.LoginUser.id,
            };
            pairs[ct.windturbineId] = ct;
        }
        api.windturbControl(pairs).then(res =>{
            success(res);
        })
        // axios.post(process.env.VUE_APP_API+`/api/control/send?isLockOrUnlock=${isLockOrUnlock}`, pairs)
        //     .then(msg => {
        //         success(msg);
        //     })
        //     .catch(err => {
        //         error(err);
        //     });
        console.log(isLockOrUnlock);
    }

    /* 系统控制风机，自动下发命令 */
    windturbineControlSystem(windturbines) {
        let pairs = {};
        for (let ind in windturbines) {
            let wb = windturbines[ind];
            let 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;
        }
        let isLockOrUnlock = false
        api.windturbControl(pairs).then(res =>{
            success(res);
        })
        // axios.post(process.env.VUE_APP_API+`/api/control/send?isLockOrUnlock=false`, pairs)
        //     .then(msg => {
        //         console.log(msg);
        //     })
        //     .catch(err => {
        //         this.showdialog("错误", "风机控制出现错误", err.message);
        //         console.log(err);
        //     });
    }

    /* 标记 */
    marking(windturbines) {
        for (let v in windturbines) {
            ++this.MarkIndex;
            this.Marks.push({ title: windturbines[v].windturbineId, id: this.MarkIndex });
        }
    }
    updateMarks(windturbine, value) {
        this.Marks.forEach(item => {
            if (windturbine.windturbineId === item.title) {
                item.value = value
            }
        })
    }
    /* 校验区数据 */
    checkout(windturbines) {
        windturbines.forEach(item => {
            item.checkTime = (new Date()).getTime()
            if (!this.checkouts.filter(items => items.windturbineId === item.windturbineId)[0]) {
                this.checkouts.push(item)
            }
        })
    }
    removeCheckouts(mk) {
        let indx = -1;
        for (let id in this.checkouts) {
            if (this.checkouts[id].windturbineId == mk.windturbineId) {
                indx = id;
                break;
            }
        }
        if (indx < 0) return;
        this.checkouts.splice(indx, 1);
    }

    /* 移除标记 */
    removeMarked(mk) {
        let indx = -1;
        for (let 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) {
        api.nitWinturbineBaseData({
            thingType: 'windturbine',
            thingId: info.windturbineId,
            uniformCodes: info.codes,
        }).then(res =>{
            action(res.data);
        }).catch(err => {
            console.log(err);
        });
        // axios.get(process.env.VUE_APP_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;
    }
}