import { Environment } from '@/environments/environment';
import { UIActionTool,Util } from '@/utils';
import UIService from '../ui-service';
import { Subject } from 'rxjs';
import IMService from '@/service/im/im-service';

/**
 * 重要事项UI服务对象基类
 *
 * @export
 * @class IMUIServiceBase
 */
export default class IMUIServiceBase extends UIService {

    /**
     * 是否支持工作流
     * 
     * @memberof  IMUIServiceBase
     */
    protected isEnableWorkflow:boolean = false;

    /**
     * 当前UI服务对应的数据服务对象
     * 
     * @memberof  IMUIServiceBase
     */
    protected dataService:IMService = new IMService();

    /**
     * 所有关联视图
     * 
     * @memberof  IMUIServiceBase
     */ 
    protected allViewMap: Map<string, Object> = new Map();

    /**
     * 状态值
     * 
     * @memberof  IMUIServiceBase
     */ 
    protected stateValue: number = 0;

    /**
     * 状态属性
     * 
     * @memberof  IMUIServiceBase
     */ 
    protected stateField: string = "";

    /**
     * 主状态属性集合
     * 
     * @memberof  IMUIServiceBase
     */  
    protected mainStateFields:Array<any> = ['imwfstate','wfstep'];

    /**
     * 主状态集合Map
     * 
     * @memberof  IMUIServiceBase
     */  
    protected allDeMainStateMap:Map<string,string> = new Map();

    /**
     * Creates an instance of  IMUIServiceBase.
     * 
     * @param {*} [opts={}]
     * @memberof  IMUIServiceBase
     */
    constructor(opts: any = {}) {
        super(opts);
        this.initViewMap();
        this.initDeMainStateMap();
    }

    /**
     * 初始化视图Map
     * 
     * @memberof  IMUIServiceBase
     */  
    public initViewMap(){
        this.allViewMap.set('EDITVIEW:MSTAG:10',{viewname:'ms_10editview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:30',{viewname:'ms_30editview',srfappde:'ims'});
        this.allViewMap.set(':',{viewname:'printeditview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20',{viewname:'ms_20editview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:',{viewname:'editview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20__40',{viewname:'ms_20_40editview',srfappde:'ims'});
        this.allViewMap.set('MDATAVIEW:',{viewname:'gridview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20__80',{viewname:'ms_20_80editview',srfappde:'ims'});
        this.allViewMap.set('REDIRECTVIEW:',{viewname:'redirectview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20__50',{viewname:'ms_20_50editview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20__60',{viewname:'ms_20_60editview',srfappde:'ims'});
        this.allViewMap.set(':',{viewname:'wfproxystartview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20__20',{viewname:'ms_20_20editview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20__30',{viewname:'ms_20_30editview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20__10',{viewname:'ms_20_10editview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20__90',{viewname:'ms_20_90editview',srfappde:'ims'});
        this.allViewMap.set('EDITVIEW:MSTAG:20__70',{viewname:'ms_20_70editview',srfappde:'ims'});
    }

    /**
     * 初始化主状态集合
     * 
     * @memberof  IMUIServiceBase
     */  
    public initDeMainStateMap(){
        this.allDeMainStateMap.set('20__20','20__20');
        this.allDeMainStateMap.set('10','10');
        this.allDeMainStateMap.set('20__70','20__70');
        this.allDeMainStateMap.set('20__80','20__80');
        this.allDeMainStateMap.set('20__10','20__10');
        this.allDeMainStateMap.set('40','40');
        this.allDeMainStateMap.set('20__40','20__40');
        this.allDeMainStateMap.set('20','20');
        this.allDeMainStateMap.set('20__30','20__30');
        this.allDeMainStateMap.set('20__90','20__90');
        this.allDeMainStateMap.set('30','30');
        this.allDeMainStateMap.set('20__60','20__60');
        this.allDeMainStateMap.set('20__50','20__50');
    }

    /**
     * 开始流程
     *
     * @param {any[]} args 当前数据
     * @param {any} context 行为附加上下文
     * @param {*} [params] 附加参数
     * @param {*} [$event] 事件源
     * @param {*} [xData]  执行行为所需当前部件
     * @param {*} [actionContext]  执行行为上下文
     * @param {*} [srfParentDeName] 父实体名称
     * @returns {Promise<any>}
     * @memberof IMUIService
     */
    public async IM_WFStartWizard(args: any[],context: any ={}, params?: any, $event?: any, xData?: any,actionContext?: any,srfParentDeName?:string){
        let data: any = {};
        const _this: any = actionContext;
        const _args: any[] = Util.deepCopy(args);
        const actionTarget: string | null = 'SINGLEKEY';
        context = UIActionTool.handleContextParam(actionTarget,_args,context);
        data = UIActionTool.handleActionParam(actionTarget,_args,params);
        //转化表单界面数据
        const resultData:any = xData.service.handleRequestData('',actionContext.context,_args[0]);
        Object.assign(context,resultData.context,context);
        Object.assign(data,resultData.data,{viewparams:actionContext.viewparams});
        let parentObj:any = {srfparentdename:srfParentDeName?srfParentDeName:null,srfparentkey:srfParentDeName?context[srfParentDeName.toLowerCase()]:null};
        Object.assign(data,parentObj);
        Object.assign(context,parentObj);
        let deResParameters: any[] = [];
        const parameters: any[] = [
            { pathName: 'ims', parameterName: 'im' },
        ];
        const openPopupModal = (view: any, data: any) => {
            let container: Subject<any> = actionContext.$appmodal.openModal(view, context, data);
            container.subscribe((result: any) => {
                if (!result || !Object.is(result.ret, 'OK')) {
                    return;
                }
                actionContext.closeView();
                if(window.opener){
                    window.opener.postMessage({status:'OK',identification:'WF'},Environment.uniteAddress);
                    window.close();
                }
            });
        }
        const view: any = {
            viewname: 'imwfproxy-start-view', 
            height: 0, 
            width: 0,  
            title: '重要事项工作流启动视图', 
        };
        openPopupModal(view, data);
    }
    /**
     * 打印预览
     *
     * @param {any[]} args 当前数据
     * @param {any} context 行为附加上下文
     * @param {*} [params] 附加参数
     * @param {*} [$event] 事件源
     * @param {*} [xData]  执行行为所需当前部件
     * @param {*} [actionContext]  执行行为上下文
     * @param {*} [srfParentDeName] 父实体名称
     * @returns {Promise<any>}
     */
    public async IM_PrintPreview(args: any[], context:any = {} ,params?: any, $event?: any, xData?: any,actionContext?:any,srfParentDeName?:string) {
        let data: any = {};
        const _args: any[] = Util.deepCopy(args);
        const _this: any = actionContext;
        const actionTarget: string | null = 'SINGLEKEY';
        Object.assign(context, { im: '%im%' });
        Object.assign(params, { imid: '%im%' });
        Object.assign(params, { imname: '%imname%' });
        context = UIActionTool.handleContextParam(actionTarget,_args,context);
        data = UIActionTool.handleActionParam(actionTarget,_args,params);
        context = Object.assign({},actionContext.context,context);
        let parentObj:any = {srfparentdename:srfParentDeName?srfParentDeName:null,srfparentkey:srfParentDeName?context[srfParentDeName.toLowerCase()]:null};
        Object.assign(data,parentObj);
        Object.assign(context,parentObj);
        let deResParameters: any[] = [];
        const parameters: any[] = [
            { pathName: 'ims', parameterName: 'im' },
        ];
            const openPopupModal = (view: any, data: any) => {
                let container: Subject<any> = actionContext.$appmodal.openModal(view, context, data);
                container.subscribe((result: any) => {
                    if (!result || !Object.is(result.ret, 'OK')) {
                        return;
                    }
                    const _this: any = actionContext;
                    if(window.opener){
                        window.opener.postMessage({status:'OK',identification:'WF'},Environment.uniteAddress);
                        window.close();
                    }
                    return result.datas;
                });
            }
            const view: any = {
                viewname: 'imprint-edit-view', 
                height: 0, 
                width: 0,  
                title: '重要事项编辑视图', 
            };
            openPopupModal(view, data);
    }


    /**
     * 获取指定数据的重定向页面
     * 
     * @param srfkey 数据主键
     * @param isEnableWorkflow  重定向视图是否需要处理流程中的数据
     * @memberof  IMUIServiceBase
     */
    public async getRDAppView(srfkey:string,isEnableWorkflow:boolean){
        this.isEnableWorkflow = isEnableWorkflow;
        // 进行数据查询
        let result:any = await this.dataService.Get({im:srfkey});
        const curData:any = result.data;
        //判断当前数据模式,默认为true，todo
        const iRealDEModel:boolean = true;

        let bDataInWF:boolean = false;
		let bWFMode:any = false;
		// 计算数据模式
		if (this.isEnableWorkflow) {
			bDataInWF = await this.dataService.testDataInWF({stateValue:this.stateValue,stateField:this.stateField},curData);
			if (bDataInWF) {
				bDataInWF = true;
				bWFMode = await this.dataService.testUserExistWorklist(null,curData);
			}
        }
        let strPDTViewParam:string = await this.getDESDDEViewPDTParam(curData, bDataInWF, bWFMode);
        //若不是当前数据模式，处理strPDTViewParam，todo

        //查找视图

        //返回视图
        return this.allViewMap.get(strPDTViewParam);
    }

    /**
	 * 获取实际的数据类型
     * 
     * @memberof  IMUIServiceBase
	 */
	protected getRealDEType(entity:any){

    }

    /**
     * 获取实体单数据实体视图预定义参数
     * 
     * @param curData 当前数据
     * @param bDataInWF 是否有数据在工作流中
     * @param bWFMode   是否工作流模式
     * @memberof  IMUIServiceBase
     */
    protected async getDESDDEViewPDTParam(curData:any, bDataInWF:boolean, bWFMode:boolean){
        let strPDTParam:string = '';
		if (bDataInWF) {
			// 判断数据是否在流程中
        }
        //多表单，todo
        const isEnableMultiForm:boolean = false;
        const multiFormDEField:string|null =null;

        if (isEnableMultiForm && multiFormDEField) {
			const objFormValue:string = curData[multiFormDEField];
			if(!Environment.isAppMode){
				return 'MOBEDITVIEW'+objFormValue;
			}
			return 'EDITVIEW'+objFormValue;
        }
		if(!Environment.isAppMode){
            if(this.getDEMainStateTag(curData)){
                return `MOBEDITVIEW:MSTAG:${ await this.getDEMainStateTag(curData)}`;
            }
			return 'MOBEDITVIEW:';
        }
        if(this.getDEMainStateTag(curData)){
            return `EDITVIEW:MSTAG:${ await this.getDEMainStateTag(curData)}`;
        }
		return 'EDITVIEW:';
    }

    /**
     * 获取数据对象的主状态标识
     * 
     * @param curData 当前数据
     * @memberof  IMUIServiceBase
     */  
    protected async getDEMainStateTag(curData:any){
        if(this.mainStateFields.length === 0) return null;

        this.mainStateFields.forEach((singleMainField:any) =>{
            if(!(singleMainField in curData)){
                console.error(`当前数据对象不包含属性singleMainField，可能会发生错误`);
            }
        })

        let strTag:String = "";
        for (let i = 0; i <= 1; i++) {
            let strTag:string = (curData[this.mainStateFields[0]])?(i == 0) ? curData[this.mainStateFields[0]] : "":"";
            if (this.mainStateFields.length >= 2) {
                for (let j = 0; j <= 1; j++) {
                    let strTag2:string = (curData[this.mainStateFields[1]])?`${strTag}__${(j == 0) ? curData[this.mainStateFields[1]] : ""}`:strTag;
                    if (this.mainStateFields.length >= 3) {
                        for (let k = 0; k <= 1; k++) {
                            let strTag3:string = (curData[this.mainStateFields[2]])?`${strTag2}__${(k == 0) ? curData[this.mainStateFields[2]] : ""}`:strTag2;
                            // 判断是否存在
                            return this.allDeMainStateMap.get(strTag3);
                        }
                    }else{
                        return this.allDeMainStateMap.get(strTag2);
                    }
                }
            }else{
                return this.allDeMainStateMap.get(strTag);
            }
        }
        return null;
    }

}