import { graphStateEnum } from "./graphStateEnum";
import { sysGraphHttpUtils } from "@/utils/http/sysGraphHttpUtils";
import { logicConfig } from "@/logicConfig";
import moment from 'moment';

export class sysGraphController {
    private static sysGraphHttpUtilsInstance = new sysGraphHttpUtils();
    //key为系统类型编码，值为 系统图类型 > 模板数据 的二级结构数组
    private static _tempTemplateObj = {};
    //三级数组 专业>系统类型>系统实例
    private static zhuanyeArr = [];


    //根据状态编码转状态名称
    static getStateNameByCode(stateCode: string) {
        return stateCode == graphStateEnum.Draft ? '草稿' :
            stateCode == graphStateEnum.Publish ? '上架' :
                stateCode == graphStateEnum.Recyle ? '回收站' : '';
    }

    /**
     * 查询系统图列表
     * @param grpphName 系统图名称
     */
    static async getDiagrams(grpphName: string) {
        //先取得所有的系统图，注：没有分页
        var resultObj = await this.sysGraphHttpUtilsInstance.postRequest('/diagram/getDiagrams', { name: grpphName });
        if (resultObj.result != logicConfig.resultObj.success)
            console.error(resultObj.message);

        //key为系统类型编码，值为系统类型数据
        var _tempSystemTypeObj = {};
        var newDataArr = [];
        var dataArr = (resultObj.data || []).filter(_c => {
            return (_c.extraProps || {}).state != graphStateEnum.Recyle;
        });
        dataArr.sort(function (a, b) {
            return ((b.extraProps || {}).createTime || {}).calendar - ((a.extraProps || {}).createTime || {}).calendar;
        });


        //取得专业>系统类型>系统实例  以和系统图列表中的系统类型编码 对应以获取系统类型名称
        if (this.zhuanyeArr.length == 0) {
            var url2 = '/diagram/major/system/instance';
            var zhuanyeObj = await this.sysGraphHttpUtilsInstance.postRequest(url2, {});
            this.zhuanyeArr = zhuanyeObj.data || [];
        }


        for (let i = 0; i < dataArr.length; i++) {
            let _c = dataArr[i];
            let extraProps = _c.extraProps || {};
            //图状态（Draft: 未发布, WaitCheck: 待审核, Checked: 审核完成, Recyle: 回收站, Publish: 发布）
            let stateName = this.getStateNameByCode(extraProps.state);

            //获取系统类型名称
            let systemTypeName = (_tempSystemTypeObj[_c.system] || {}).aliasName;
            if (!systemTypeName) {
                getSystemTypeByCode(_c.system);
                systemTypeName = (_tempSystemTypeObj[_c.system] || {}).aliasName || '';
            }

            //获取模版名称
            let _templateObj = await this.getTemplateGraphTypeBySysTypeCode(_c.system, _c.templateId);
            let templateName = ((_templateObj || {}).template || {}).name || '';

            //格式化日期时间
            let momentInstance = moment(((_c.extraProps || {}).createTime || {}).calendar);
            let timeStr = momentInstance.format('YYYY[/]MM[/]DD[ ]HH[:]mm');

            newDataArr.push({
                id: _c.id,
                name: _c.name,
                //系统类型名称
                sysType: systemTypeName,
                //系统实例名称
                sysInstance: extraProps.systemInstanceName,
                //模板名称
                sysTemplate: templateName,
                stateName: stateName,
                createTime: timeStr
            });
        }
        return newDataArr;


        function getSystemTypeByCode(systemTypeCode: string) {
            for (let i = 0; i < sysGraphController.zhuanyeArr.length; i++) {
                //专业
                let zhuanye = sysGraphController.zhuanyeArr[i];
                //系统类型数组
                let systemTypeArr = zhuanye.children || [];
                let isFind = false;
                for (let j = 0; j < systemTypeArr.length; j++) {
                    //系统类型
                    let systemType = systemTypeArr[j];
                    if (systemType.code == systemTypeCode) {
                        isFind = true;
                        _tempSystemTypeObj[systemTypeCode] = systemType;
                        break;
                    }
                }
                if (isFind)
                    break;
            }
        };
    }

    /**
     * 根据系统类型查询系统图模板和系统图类型，数据结构：系统图类型 ->  系统图模版
     * @param sysTypeCode 系统类型编码
     * @param templateId 模版ID
     * @return {template:{id:'',name:''},graphType:{id:'',name:''}}
     */
    static async getTemplateGraphTypeBySysTypeCode(sysTypeCode: string, templateId: string) {
        var dataArr = this._tempTemplateObj[sysTypeCode];

        if (!dataArr) {
            let url = '/diagram/systemType/template';
            let resultObj = await sysGraphController.sysGraphHttpUtilsInstance.postRequest(url, { system: sysTypeCode });
            dataArr = resultObj.data || [];
        }
        this._tempTemplateObj[sysTypeCode] = dataArr;

        for (let i = 0; i < dataArr.length; i++) {
            //_sysGraphType为系统图类型
            let sysGraphType = dataArr[i];
            //模板数组
            let templateArr = sysGraphType.children || [];
            for (let j = 0; j < templateArr.length; j++) {
                //模板
                let template = templateArr[j];
                if (template.id == templateId) {
                    return {
                        template: { id: template.id, name: template.name },
                        graphType: { id: sysGraphType.id, name: sysGraphType.name }
                    };
                }
            }
        }
        return null;
    }


    /**
     * 根据项目查询该项目下的专业>系统类型>系统实例
     * @param projectId 项目ID
     * @param groupCode 集团编码
     */
    static async getSysInstanceByProject(projectId: string, groupCode: string) {
        var url = '/diagram/major/system/instance?projectId=' + projectId + '&groupCode=' + groupCode;
        var resultObj = await this.sysGraphHttpUtilsInstance.postRequest(url, {});
        if (resultObj.result != logicConfig.resultObj.success)
            console.error(resultObj.message);
        var dataArr = resultObj.data || [];
        this.zhuanyeArr = dataArr;
        var newDataArr = [];

        dataArr.forEach(_c => {
            //_c为专业
            let zhuanye = { value: _c.id, label: _c.label, code: _c.code, children: [] };
            let sysTypeArr = [];
            (_c.children || []).forEach(_c2 => {
                //_c2为系统类型
                let sysType = { value: _c2.id, label: _c2.aliasName, code: _c2.code, children: [] };
                let sysInstanceArr = [];
                (_c2.children || []).forEach(_c3 => {
                    //_c3为系统实例
                    sysInstanceArr.push({ value: _c3.id, label: _c3.name, code: _c3.code });
                });
                sysType.children = sysInstanceArr;
                sysTypeArr.push(sysType);
            });
            zhuanye.children = sysTypeArr;
            newDataArr.push(zhuanye);
        });
        return newDataArr;
    }

    /**
     * 根据系统类型查询系统图模板，数据结构：系统图类型 ->  系统图模版
     * @param sysTypeCode 系统类型编码
     */
    static async getTemplateBySysTypeCode(sysTypeCode: string) {
        var url = '/diagram/systemType/template';
        var resultObj = await this.sysGraphHttpUtilsInstance.postRequest(url, { system: sysTypeCode });
        if (resultObj.result != logicConfig.resultObj.success)
            console.error(resultObj.message);
        var dataArr = resultObj.data || [];
        var newDataArr = [];

        dataArr.forEach(_sysGraphType => {
            //_sysGraphType为系统图类型
            let sysGraphType = { value: _sysGraphType.id, label: _sysGraphType.name, code: _sysGraphType.code, children: [] };
            let templateArr = [];
            (_sysGraphType.children || []).forEach(_template => {
                //_template为模版
                let template = { value: _template.id, label: _template.name, code: _template.code };
                templateArr.push(template);
            });
            sysGraphType.children = templateArr;
            newDataArr.push(sysGraphType);
        });
        return newDataArr;
    }

    /**
     * 新增系统图
     * @param _paramObj {name:'系统图名称',type:'系统图类型编码',templateId:'引用的模板id',system:'所属的系统类型编码',projectId:'项目id',systemId:'对应的系统实例id',groupCode:'集团编码',}
     */
    static async createSysGraph(_paramObj: any) {
        var url = '/diagram/newDiagram?groupCode=' + _paramObj.groupCode + '&projectId=' + _paramObj.projectId;
        var resultObj = await this.sysGraphHttpUtilsInstance.postRequest(url, _paramObj);
        if (resultObj.result != logicConfig.resultObj.success) {
            resultObj.message = '新建系统图失败：' + resultObj.message;
            return resultObj;
        }

        var dataObj = resultObj.data || {};
        if (!dataObj.id)
            return { result: logicConfig.resultObj.failure, message: '缺少系统图ID' };

        //新增成功后，要加载数据
        // var loadDataUrl = '/diagram/loadData?groupCode=' + _paramObj.groupCode + '&projectId=' + _paramObj.projectId;
        // var loadResultObj = await this.sysGraphHttpUtilsInstance.postRequest(loadDataUrl, { id: dataObj.id });
        var loadResultObj = await this.loadData({ id: dataObj.id, projectId: _paramObj.projectId, groupCode: _paramObj.groupCode });
        if (loadResultObj.result != logicConfig.resultObj.success) {
            loadResultObj.message = '加载模板数据失败：' + loadResultObj.message;
            return loadResultObj;
        }
        loadResultObj.data = await this.parseSystemGraphInfo(loadResultObj.data, _paramObj.groupCode, _paramObj.projectId);

        // //加载数据成功后保存数据
        // var saveResultObj = await this.saveSysGraph(loadResultObj.data, _paramObj.projectId, _paramObj.groupCode);
        // if (saveResultObj.result != logicConfig.resultObj.success) {
        //     saveResultObj.message = '保存系统图数据失败：' + saveResultObj.message;
        //     return saveResultObj;
        // }
        //因为保存数据成功返回的data里的数据不全，所以返回加载数据成功后的数据给页面
        return loadResultObj;
    }

    /**
     * 加载数据
     * @param _paramObj {projectId:'项目id',groupCode:'集团编码',id:'系统图ID'}
     */
    static async loadData(_paramObj: any) {
        var loadDataUrl = '/diagram/loadData?groupCode=' + _paramObj.groupCode + '&projectId=' + _paramObj.projectId;
        var loadResultObj = await this.sysGraphHttpUtilsInstance.postRequest(loadDataUrl, { id: _paramObj.id });
        return loadResultObj;
    }

    /**
     * 解析系统图数据
     * @param dataObj 
     */
    static async parseSystemGraphInfo(dataObj: any, groupCode: string, projectId: string) {
        //取得专业>系统类型>系统实例  以和系统图列表中的系统类型编码 对应以获取系统实例名称
        if (this.zhuanyeArr.length == 0) {
            var url2 = '/diagram/major/system/instance?groupCode=' + groupCode + '&projectId=' + projectId;
            var zhuanyeObj = await this.sysGraphHttpUtilsInstance.postRequest(url2, {});
            this.zhuanyeArr = zhuanyeObj.data || [];
        }

        //获取系统实例名称
        var _systemInstance = getSystemInstanceByCode(dataObj.systemId);
        dataObj.systemInstanceName = _systemInstance.name || '';


        //获取系统图类型和系统图模版
        var _temoObj = await this.getTemplateGraphTypeBySysTypeCode(dataObj.system, dataObj.templateId);
        dataObj.graphTypeName = ((_temoObj || {}).graphType || {}).name;
        dataObj.templateName = ((_temoObj || {}).template || {}).name;

        //状态名称
        dataObj.stateName = this.getStateNameByCode((dataObj.extraProps || {}).state);


        return dataObj;

        //获取系统实例信息
        function getSystemInstanceByCode(systemInstanceId: string) {
            for (let i = 0; i < sysGraphController.zhuanyeArr.length; i++) {
                //专业
                let zhuanye = sysGraphController.zhuanyeArr[i];
                //系统类型数组
                let systemTypeArr = zhuanye.children || [];
                let isFind = false;
                for (let j = 0; j < systemTypeArr.length; j++) {
                    //系统类型
                    let systemType = systemTypeArr[j];
                    //系统实例数组
                    let systemInstanceArr = systemType.children || [];
                    for (let k = 0; k < systemInstanceArr.length; k++) {
                        //系统实例
                        let systemInstance = systemInstanceArr[k];
                        if (systemInstance.id == systemInstanceId)
                            return systemInstance;
                    }
                }
                if (isFind)
                    break;
            }
        };
    };

    /**
     * 重置数据
     * @param _paramObj {projectId:'项目id',groupCode:'集团编码',id:'系统图ID'}
     */
    static async resetData(_paramObj: any) {
        var loadDataUrl = '/diagram/reset?groupCode=' + _paramObj.groupCode + '&projectId=' + _paramObj.projectId;
        var loadResultObj = await this.sysGraphHttpUtilsInstance.postRequest(loadDataUrl, { id: _paramObj.id });
        loadResultObj.data = await this.parseSystemGraphInfo(loadResultObj.data, _paramObj.groupCode, _paramObj.projectId);
        return loadResultObj;
    }



    /**
     * 保存系统图数据
     * @param _paramObj 参见后台loadData接口的返回
     * @param projectId 项目ID
     * @param groupCode 群组编码
     */
    static async saveSysGraph(_paramObj: any, projectId: string, groupCode: string) {
        var saveUrl = '/diagram/newDiagram?groupCode=' + groupCode + '&projectId=' + projectId;
        var saveResultObj = await this.sysGraphHttpUtilsInstance.postRequest(saveUrl, _paramObj);
        return saveResultObj;
    }

    /**
     * 根据系统图ID查询系统图信息
     * @param id 系统图ID
     */
    static async getDiagramById(id: string, groupCode: string, projectId: string) {
        var url = '/diagram/getDiagram?diagramId=' + id + '&groupCode=' + groupCode + '&projectId=' + projectId;
        var resultObj = await this.sysGraphHttpUtilsInstance.getRequest(url, {});
        if (resultObj.result != logicConfig.resultObj.success) {
            console.error(resultObj.message);
            return resultObj;
        }


        //#region -------------------------------------------------------------------------------测试
        // var tempData=

        //   resultObj.data.lines=tempData.lines;
        //   resultObj.data.template=tempData.template;

        //#regionend -------------------------------------------------------------------------------测试结束

        resultObj.data = await this.parseSystemGraphInfo(resultObj.data, groupCode, projectId);
        return resultObj;
    }


    /**
    * 更新系统图状态
    * @param _paramObj  {id:'系统图ID',state:'系统图状态'}
    */
    static async updateSysGraphState(_paramObj: any) {
        var url = '/diagram/update/state';
        var resultObj = await this.sysGraphHttpUtilsInstance.postRequest(url, _paramObj);
        return resultObj;
    }

    /**
    * 删除系统图
    * @param id 系统图ID
    */
    static async delSysGraph(id: string) {
        var resultObj = await this.updateSysGraphState({ id: id, state: graphStateEnum.Recyle });
        return resultObj;
    }

    /**
    * 上架系统图
    * @param id 系统图ID
    */
    static async publishSysGraph(id: string) {
        var resultObj = await this.updateSysGraphState({ id: id, state: graphStateEnum.Publish });
        return resultObj;
    }

    /**
    * 下架系统图
    * @param id 系统图ID
    */
    static async draftGraph(id: string) {
        var resultObj = await this.updateSysGraphState({ id: id, state: graphStateEnum.Draft });
        return resultObj;
    }

    /**
     * 打开系统图新增、预览、编辑页面
     * @param state 打开新页面时的状态，0 预览； 1 编辑；  2 新建
     * @param diagramId 系统图ID
     * @param groupCode 集团编码
     * @param projectId 项目ID
     * @param projectName 项目名称
     * @param baseUrl 根路径
     * @param isOpenTarget 是否打开新页面
     */
    static openGraphPage(state: number, diagramId: string, groupCode: string, projectId: string, projectName: string, baseUrl: string, isOpenTarget: boolean) {
        var url = "/" +
            baseUrl +
            logicConfig.routerNameConfig.systemGraphEditName +
            "?ost=" +
            state +
            "&did=" +
            (diagramId || "") +
            '&gc=' + (groupCode || '') +
            '&pri=' + (projectId || '') +
            '&prn=' + encodeURIComponent(projectName || '');
        isOpenTarget === true ? window.open(url) : window.location.href = url;
    }

    /**
    * 保存系统图名称
    * @_paramObj {id:'系统图ID',name:'系统图名称'}
    */
    static async saveGraphName(_paramObj: any) {
        var url = '/diagram/update/name';
        var resultObj = await this.sysGraphHttpUtilsInstance.postRequest(url, _paramObj);
        return resultObj;
    }

}