import { Http,Util,Errorlog } from '@/utils';
import ControlService from '@/widgets/control-service';
import EMApplyService from '@/service/emapply/emapply-service';
import Main7Model from './main7-form-model';
import EMEquipService from '@/service/emequip/emequip-service';
import EMObjectService from '@/service/emobject/emobject-service';
import PFTeamService from '@/service/pfteam/pfteam-service';
import EMServiceService from '@/service/emservice/emservice-service';
import EMRFODEService from '@/service/emrfode/emrfode-service';
import EMRFOMOService from '@/service/emrfomo/emrfomo-service';
import EMRFOCAService from '@/service/emrfoca/emrfoca-service';
import EMRFOACService from '@/service/emrfoac/emrfoac-service';


/**
 * Main7 部件服务对象
 *
 * @export
 * @class Main7Service
 */
export default class Main7Service extends ControlService {

    /**
     * 外委申请服务对象
     *
     * @type {EMApplyService}
     * @memberof Main7Service
     */
    public appEntityService: EMApplyService = new EMApplyService({ $store: this.getStore() });

    /**
     * 设置从数据模式
     *
     * @type {boolean}
     * @memberof Main7Service
     */
    public setTempMode(){
        this.isTempMode = false;
    }

    /**
     * Creates an instance of Main7Service.
     * 
     * @param {*} [opts={}]
     * @memberof Main7Service
     */
    constructor(opts: any = {}) {
        super(opts);
        this.model = new Main7Model();
    }

    /**
     * 设备档案服务对象
     *
     * @type {EMEquipService}
     * @memberof Main7Service
     */
    public emequipService: EMEquipService = new EMEquipService();

    /**
     * 对象服务对象
     *
     * @type {EMObjectService}
     * @memberof Main7Service
     */
    public emobjectService: EMObjectService = new EMObjectService();

    /**
     * 班组服务对象
     *
     * @type {PFTeamService}
     * @memberof Main7Service
     */
    public pfteamService: PFTeamService = new PFTeamService();

    /**
     * 服务商服务对象
     *
     * @type {EMServiceService}
     * @memberof Main7Service
     */
    public emserviceService: EMServiceService = new EMServiceService();

    /**
     * 现象服务对象
     *
     * @type {EMRFODEService}
     * @memberof Main7Service
     */
    public emrfodeService: EMRFODEService = new EMRFODEService();

    /**
     * 模式服务对象
     *
     * @type {EMRFOMOService}
     * @memberof Main7Service
     */
    public emrfomoService: EMRFOMOService = new EMRFOMOService();

    /**
     * 原因服务对象
     *
     * @type {EMRFOCAService}
     * @memberof Main7Service
     */
    public emrfocaService: EMRFOCAService = new EMRFOCAService();

    /**
     * 方案服务对象
     *
     * @type {EMRFOACService}
     * @memberof Main7Service
     */
    public emrfoacService: EMRFOACService = new EMRFOACService();

    /**
     * 处理数据
     *
     * @private
     * @param {Promise<any>} promise
     * @returns {Promise<any>}
     * @memberof Main7Service
     */
    private doItems(promise: Promise<any>, deKeyField: string, deName: string): Promise<any> {
        return new Promise((resolve, reject) => {
            promise.then((response: any) => {
                if (response && response.status === 200) {
                    const data = response.data;
                    data.forEach((item:any,index:number) =>{
                        item[deName] = item[deKeyField];
                        data[index] = item;
                    });
                    resolve(data);
                } else {
                    reject([])
                }
            }).catch((response: any) => {
                reject([])
            });
        });
    }

    /**
     * 获取跨实体数据集合
     *
     * @param {string} serviceName 服务名称
     * @param {string} interfaceName 接口名称
     * @param {*} data
     * @param {boolean} [isloading]
     * @returns {Promise<any[]>}
     * @memberof  Main7Service
     */
    @Errorlog
    public getItems(serviceName: string, interfaceName: string, context: any = {}, data: any, isloading?: boolean): Promise<any[]> {
        data.page = data.page ? data.page : 0;
        data.size = data.size ? data.size : 1000;
        if (Object.is(serviceName, 'EMEquipService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.emequipService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'emequipid', 'emequip');
        }
        if (Object.is(serviceName, 'EMObjectService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.emobjectService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'emobjectid', 'emobject');
        }
        if (Object.is(serviceName, 'PFTeamService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.pfteamService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'pfteamid', 'pfteam');
        }
        if (Object.is(serviceName, 'EMServiceService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.emserviceService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'emserviceid', 'emservice');
        }
        if (Object.is(serviceName, 'EMRFODEService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.emrfodeService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'emrfodeid', 'emrfode');
        }
        if (Object.is(serviceName, 'EMRFOMOService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.emrfomoService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'emrfomoid', 'emrfomo');
        }
        if (Object.is(serviceName, 'EMRFOCAService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.emrfocaService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'emrfocaid', 'emrfoca');
        }
        if (Object.is(serviceName, 'EMRFOACService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.emrfoacService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'emrfoacid', 'emrfoac');
        }

        return Promise.reject([])
    }

    /**
     * 启动工作流
     *
     * @param {string} action
     * @param {*} [context={}]
     * @param {*} [data={}]
     * @param {boolean} [isloading]
     * @param {*} [localdata]
     * @returns {Promise<any>}
     * @memberof Main7Service
     */
    @Errorlog
    public wfstart(action: string,context: any = {},data: any = {}, isloading?: boolean,localdata?:any): Promise<any> {
        data = this.handleWFData(data);
        context = this.handleRequestData(action,context,data).context;
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            const _appEntityService: any = this.appEntityService;
            if (_appEntityService[action] && _appEntityService[action] instanceof Function) {
                result = _appEntityService[action](context,data, isloading,localdata);
            } else {
                result = this.appEntityService.WFStart(context,data, isloading,localdata);
            }
            result.then((response) => {
                this.handleResponse(action, response);
                resolve(response);
            }).catch(response => {
                reject(response);
            });
        });
    }

    /**
     * 提交工作流
     *
     * @param {string} action
     * @param {*} [context={}]
     * @param {*} [data={}]
     * @param {boolean} [isloading]
     * @param {*} [localdata]
     * @returns {Promise<any>}
     * @memberof Main7Service
     */
    @Errorlog
    public wfsubmit(action: string,context: any = {}, data: any = {}, isloading?: boolean,localdata?:any): Promise<any> {
        data = this.handleWFData(data,true);
        context = this.handleRequestData(action,context,data,true).context;
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            const _appEntityService: any = this.appEntityService;
            if (_appEntityService[action] && _appEntityService[action] instanceof Function) {
                result = _appEntityService[action](context,data, isloading,localdata);
            } else {
                result = this.appEntityService.WFSubmit(context,data, isloading,localdata);
            }
            result.then((response) => {
                this.handleResponse(action, response);
                resolve(response);
            }).catch(response => {
                reject(response);
            });
        });
    }


    /**
     * 添加数据
     *
     * @param {string} action
     * @param {*} [context={}]
     * @param {*} [data={}]
     * @param {boolean} [isloading]
     * @returns {Promise<any>}
     * @memberof Main7Service
     */
    @Errorlog
    public add(action: string, context: any = {},data: any = {}, isloading?: boolean): Promise<any> {
        const {data:Data,context:Context} = this.handleRequestData(action,context,data);
        Object.assign(Data,{emapplyid: data.emapplyid, srffrontuf: '1'});
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            const _appEntityService: any = this.appEntityService;
            if (_appEntityService[action] && _appEntityService[action] instanceof Function) {
                result = _appEntityService[action](Context,Data, isloading);
            } else {
                result = this.appEntityService.Create(Context,Data, isloading);
            }
            result.then((response) => {
                this.handleResponse(action, response);
                resolve(response);
            }).catch(response => {
                reject(response);
            });
        });
    }

    /**
     * 删除数据
     *
     * @param {string} action
     * @param {*} [context={}]
     * @param {*} [data={}]
     * @param {boolean} [isloading]
     * @returns {Promise<any>}
     * @memberof Main7Service
     */
    @Errorlog
    public delete(action: string, context: any = {},data: any = {}, isloading?: boolean): Promise<any> {
        const {data:Data,context:Context} = this.handleRequestData(action,context,data);
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            const _appEntityService: any = this.appEntityService;
            if (_appEntityService[action] && _appEntityService[action] instanceof Function) {
                result = _appEntityService[action](Context,Data, isloading);
            } else {
                result = this.appEntityService.Remove(Context,Data, isloading);
            }
            result.then((response) => {
                resolve(response);
            }).catch(response => {
                reject(response);
            });
        });
    }

    /**
     * 修改数据
     *
     * @param {string} action
     * @param {*} [context={}]
     * @param {*} [data={}]
     * @param {boolean} [isloading]
     * @returns {Promise<any>}
     * @memberof Main7Service
     */
    @Errorlog
    public update(action: string, context: any = {},data: any = {}, isloading?: boolean): Promise<any> {
        const {data:Data,context:Context} = this.handleRequestData(action,context,data);
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            const _appEntityService: any = this.appEntityService;
            if (_appEntityService[action] && _appEntityService[action] instanceof Function) {
                result = _appEntityService[action](Context,Data, isloading);
            } else {
                result = this.appEntityService.Update(Context,Data, isloading);
            }
            result.then((response) => {
                this.handleResponse(action, response);
                resolve(response);
            }).catch(response => {
                reject(response);
            });
        });
    }

    /**
     * 查询数据
     *
     * @param {string} action
     * @param {*} [context={}]
     * @param {*} [data={}]
     * @param {boolean} [isloading]
     * @returns {Promise<any>}
     * @memberof Main7Service
     */
    @Errorlog
    public get(action: string,context: any = {},data: any = {}, isloading?: boolean): Promise<any> {
        const {data:Data,context:Context} = this.handleRequestData(action,context,data);
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            const _appEntityService: any = this.appEntityService;
            if (_appEntityService[action] && _appEntityService[action] instanceof Function) {
                result = _appEntityService[action](Context,Data, isloading);
            } else {
                result = this.appEntityService.Get(Context,Data, isloading);
            }
            result.then((response) => {
                this.handleResponse(action, response);
                resolve(response);
            }).catch(response => {
                reject(response);
            });
        });
    }

    /**
     * 加载草稿
     *
     * @param {string} action
     * @param {*} [context={}]
     * @param {*} [data={}]
     * @param {boolean} [isloading]
     * @returns {Promise<any>}
     * @memberof Main7Service
     */
    @Errorlog
    public loadDraft(action: string,context: any = {}, data: any = {}, isloading?: boolean): Promise<any> {
        const {data:Data,context:Context} = this.handleRequestData(action,context,data);
        //仿真主键数据
        const PrimaryKey = Util.createUUID();
        Data.emapplyid = PrimaryKey;
        Data.emapply = PrimaryKey;
        return new Promise((resolve: any, reject: any) => {
            let result: Promise<any>;
            const _appEntityService: any = this.appEntityService;
            if (_appEntityService[action] && _appEntityService[action] instanceof Function) {
                result = _appEntityService[action](Context,Data, isloading);
            } else {
                result = this.appEntityService.GetDraft(Context,Data, isloading);
            }
            result.then((response) => {
                response.data.emapplyid = PrimaryKey;
                this.handleResponse(action, response, true);
                resolve(response);
            }).catch(response => {
                reject(response);
            });
        });
    }

     /**
     * 前台逻辑
     * @param {string} action
     * @param {*} [context={}]
     * @param {*} [data={}]
     * @param {boolean} [isloading]
     * @returns {Promise<any>}
     * @memberof Main7Service
     */
    @Errorlog
    public frontLogic(action:string,context: any = {},data: any = {}, isloading?: boolean): Promise<any> {
        const {data:Data,context:Context} = this.handleRequestData(action,context,data);
        return new Promise((resolve: any, reject: any)=>{
            let result: Promise<any>;
            const _appEntityService: any = this.appEntityService;
            if (_appEntityService[action] && _appEntityService[action] instanceof Function) {
                result = _appEntityService[action](Context,Data, isloading);
            } else {
                return Promise.reject({ status: 500, data: { title: '失败', message: '系统异常' } });
            }
            result.then((response) => {
                this.handleResponse(action, response,true);
                resolve(response);
            }).catch(response => {
                reject(response);
            });
        })
    }

    /**
     * 处理请求数据
     * 
     * @param action 行为 
     * @param data 数据
     * @memberof Main7Service
     */
    public handleRequestData(action: string,context:any, data: any = {},isMerge:boolean = false){
        let mode: any = this.getMode();
        if (!mode && mode.getDataItems instanceof Function) {
            return data;
        }
        let formItemItems: any[] = mode.getDataItems();
        let requestData:any = {};
        if(isMerge && (data && data.viewparams)){
            Object.assign(requestData,data.viewparams);
        }
        formItemItems.forEach((item:any) =>{
            if(item && item.dataType && Object.is(item.dataType,'FONTKEY')){
                if(item && item.prop){
                    requestData[item.prop] = context[item.name];
                }
            }else{
                if(item && item.prop){
                    requestData[item.prop] = data[item.name];
                }
            }
        });
        let tempContext:any = JSON.parse(JSON.stringify(context));
        if(tempContext && tempContext.srfsessionid){
            tempContext.srfsessionkey = tempContext.srfsessionid;
            delete tempContext.srfsessionid;
        }
        return {context:tempContext,data:requestData};
    }

}