import { Http } from '@/utils';
import { Util, Errorlog } from '@/utils';
import ControlService from '@/widgets/control-service';
import Purchase_orderService from '@/service/purchase-order/purchase-order-service';
import EF_MasterModel from './ef-master-form-model';
import Res_supplierService from '@/service/res-supplier/res-supplier-service';
import Purchase_requisitionService from '@/service/purchase-requisition/purchase-requisition-service';
import Res_currencyService from '@/service/res-currency/res-currency-service';
import Res_companyService from '@/service/res-company/res-company-service';
import Stock_picking_typeService from '@/service/stock-picking-type/stock-picking-type-service';
import Account_incotermsService from '@/service/account-incoterms/account-incoterms-service';
import Res_usersService from '@/service/res-users/res-users-service';
import Account_payment_termService from '@/service/account-payment-term/account-payment-term-service';
import Account_fiscal_positionService from '@/service/account-fiscal-position/account-fiscal-position-service';


/**
 * EF_Master 部件服务对象
 *
 * @export
 * @class EF_MasterService
 */
export default class EF_MasterService extends ControlService {

    /**
     * 采购订单服务对象
     *
     * @type {Purchase_orderService}
     * @memberof EF_MasterService
     */
    public appEntityService: Purchase_orderService = new Purchase_orderService({ $store: this.getStore() });

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

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

    /**
     * 供应商服务对象
     *
     * @type {Res_supplierService}
     * @memberof EF_MasterService
     */
    public res_supplierService: Res_supplierService = new Res_supplierService();

    /**
     * 采购申请服务对象
     *
     * @type {Purchase_requisitionService}
     * @memberof EF_MasterService
     */
    public purchase_requisitionService: Purchase_requisitionService = new Purchase_requisitionService();

    /**
     * 币种服务对象
     *
     * @type {Res_currencyService}
     * @memberof EF_MasterService
     */
    public res_currencyService: Res_currencyService = new Res_currencyService();

    /**
     * 公司服务对象
     *
     * @type {Res_companyService}
     * @memberof EF_MasterService
     */
    public res_companyService: Res_companyService = new Res_companyService();

    /**
     * 拣货类型服务对象
     *
     * @type {Stock_picking_typeService}
     * @memberof EF_MasterService
     */
    public stock_picking_typeService: Stock_picking_typeService = new Stock_picking_typeService();

    /**
     * 贸易条款服务对象
     *
     * @type {Account_incotermsService}
     * @memberof EF_MasterService
     */
    public account_incotermsService: Account_incotermsService = new Account_incotermsService();

    /**
     * 用户服务对象
     *
     * @type {Res_usersService}
     * @memberof EF_MasterService
     */
    public res_usersService: Res_usersService = new Res_usersService();

    /**
     * 付款条款服务对象
     *
     * @type {Account_payment_termService}
     * @memberof EF_MasterService
     */
    public account_payment_termService: Account_payment_termService = new Account_payment_termService();

    /**
     * 税科目调整服务对象
     *
     * @type {Account_fiscal_positionService}
     * @memberof EF_MasterService
     */
    public account_fiscal_positionService: Account_fiscal_positionService = new Account_fiscal_positionService();

    /**
     * 远端数据
     *
     * @type {*}
     * @memberof EF_MasterService
     */
    private remoteCopyData:any = {};

    /**
     * 处理数据
     *
     * @private
     * @param {Promise<any>} promise
     * @returns {Promise<any>}
     * @memberof EF_MasterService
     */
    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  EF_MasterService
     */
    @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, 'Res_supplierService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.res_supplierService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'id', 'res_supplier');
        }
        if (Object.is(serviceName, 'Purchase_requisitionService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.purchase_requisitionService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'id', 'purchase_requisition');
        }
        if (Object.is(serviceName, 'Res_companyService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.res_companyService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'id', 'res_company');
        }
        if (Object.is(serviceName, 'Stock_picking_typeService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.stock_picking_typeService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'id', 'stock_picking_type');
        }
        if (Object.is(serviceName, 'Account_incotermsService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.account_incotermsService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'id', 'account_incoterms');
        }
        if (Object.is(serviceName, 'Res_usersService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.res_usersService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'id', 'res_users');
        }
        if (Object.is(serviceName, 'Account_payment_termService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.account_payment_termService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'id', 'account_payment_term');
        }
        if (Object.is(serviceName, 'Account_fiscal_positionService') && Object.is(interfaceName, 'FetchDefault')) {
            return this.doItems(this.account_fiscal_positionService.FetchDefault(JSON.parse(JSON.stringify(context)),data, isloading), 'id', 'account_fiscal_position');
        }

        return Promise.reject([])
    }

    /**
     * 启动工作流
     *
     * @param {string} action
     * @param {*} [context={}]
     * @param {*} [data={}]
     * @param {boolean} [isloading]
     * @param {*} [localdata]
     * @returns {Promise<any>}
     * @memberof EF_MasterService
     */
    @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 EF_MasterService
     */
    @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 EF_MasterService
     */
    @Errorlog
    public add(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.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 EF_MasterService
     */
    @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 EF_MasterService
     */
    @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 EF_MasterService
     */
    @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.setRemoteCopyData(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 EF_MasterService
     */
    @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.id = PrimaryKey;
        Data.purchase_order = 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) => {
                this.setRemoteCopyData(response);
                response.data.id = 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 EF_MasterService
     */
    @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 EF_MasterService
     */
    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};
    }

    /**
     * 通过属性名称获取表单项名称
     * 
     * @param name 实体属性名称 
     * @memberof EF_MasterService
     */
    public getItemNameByDeName(name:string) :string{
        let itemName = name;
        let mode: any = this.getMode();
        if (!mode && mode.getDataItems instanceof Function) {
            return name;
        }
        let formItemItems: any[] = mode.getDataItems();
        formItemItems.forEach((item:any)=>{
            if(item.prop === name){
                itemName = item.name;
            }
        });
        return itemName.trim();
    }

    /**
     * 设置远端数据
     * 
     * @param result 远端请求结果 
     * @memberof EF_MasterService
     */
    public setRemoteCopyData(result:any){
        if (result && result.status === 200) {
            this.remoteCopyData = Util.deepCopy(result.data);
        }
    }

    /**
     * 获取远端数据
     * 
     * @memberof EF_MasterService
     */
    public getRemoteCopyData(){
        return this.remoteCopyData;
    }

}