import { Component, OnInit, ViewChild, AfterViewInit,OnDestroy,Input,Output,EventEmitter,ViewContainerRef} from '@angular/core';
import { Subject,Subscription } from 'rxjs';
import { FormButtonModel, FormPageModel, FormItemModel, FromDRUIPartModel, FormPartModel, FormGroupPanelModel, FormRowItemModel, FormTabPageModel, FormTabPanelModel, FormUserControlModel } from '@global/model/form-detail';
import { Http } from '@global/service/Http';
import { AppNotification } from '@global/service/Notification';
import { NavController, ModalController } from '@ionic/angular';
import { App } from '@global/service/App';
import { ComUtil } from '@global/util/ComUtil';
import { AppEnvironment } from 'src/environments/AppEnvironment';


@Component({
  selector: 'ctrl-mob-form-form',
  templateUrl: './mob-form-form.html',
  styleUrls: ['./mob-form-form.scss']
})
export class EditForm implements OnInit,OnDestroy {

    /**
     * 名称
     *
     * @type {string}
     * @memberof EditForm
     */
    @Input() public name: string;

    /**
     * 视图通讯对象
     *
     * @type {Subject<ViewState>}
     * @memberof EditForm
     */
    @Input() public viewState: Subject<ViewState>;


    /**
     * 是否为内嵌视图
     *
     * @type {boolean}
     * @memberof EditForm
     */
    @Input() public isembeddedView: boolean;

    /**
     * 是否为模态模式
     *
     * @type {boolean}
     * @memberof EditForm
     */
    @Input() public isModalMode: boolean;

    /**
     * 当前部件激活数据
     *
     * @public
     * @type {void}
     * @memberof EditForm
     */
    public $activeData: Array<any> = [];

    constructor(private $http: Http, private $notification: AppNotification,private $navCtrl:NavController,private $app:App,private $modalCtrl: ModalController) {

    }


    /**
     * 返回
     *
     * @memberof EditForm
     */
    public backView() {
        if (this.isModalMode) {
            let res: any;
            if (this.$activeData && this.$activeData.length > 0) {
                res = { ret: 'OK', result: this.$activeData };
            } else {
                res = { ret: 'NO', result: [] };
            }
            this.$modalCtrl.dismiss(res, 'close');
        } else {
            this.$navCtrl.back();
        }
    }

    /**
     * Api地址
     *
     * @type {string}
     * @memberof EditForm
     */
    public url: string = 'mob/demo/df/mobformeditform/';

    /**
     * 忽略表单项值变化
     *
     * @type {boolean}
     * @memberof EditForm
     */
    public ignorefieldvaluechange: boolean = false;

    /**
     * 视图状态事件
     *
     * @protected
     * @type {(Subscription | undefined)}
     * @memberof  EditForm
     */
    protected viewStateEvent: Subscription | undefined;

    /**
     * 关联视图Map
     *
     * @type {Map}
     * @memberof EditForm
     */
    public refViewMap =new Map();

    /**
     * 表单状态
     *
     * @type {Subject<any>}
     * @memberof EditForm
     */
    public formState: Subject<any> = new Subject();

    @Input() public updateAction?: string;
    @Input() public removeAction?: string;
    @Input() public loaddraftAction?: string;
    @Input() public loadAction?: string;
    @Input() public createAction?: string;
    @Input() public wfstartAction?: string;
    @Input() public wfsubmitAction?: string;
    @Input() public loaddraftformAction?: string;

    @Output() saveemit = new EventEmitter();
    @Output() removeemit = new EventEmitter();
    @Output() loademit = new EventEmitter();
    @Output() wfstartemit =new EventEmitter();
    @Output() wfsubmitemit =new EventEmitter();

    ngOnInit(): void {
        this.initFormDetailsModel();
        this.initData();
        this.initRefView();
        if (this.viewState) {
        this.viewStateEvent=this.viewState.subscribe(({ tag, action, data }) => {
        if (!Object.is(tag, this.name)) {
            return;
        }
        if (Object.is('autoload', action)) {
            this.autoLoad(data);
        }
        if (Object.is('load', action)) {
            this.load(data);
        }
        if (Object.is('loaddraft', action)) {
            this.loadDraft(data);
        }
        if (Object.is('save', action)) {
            this.save(data);
        }
        if (Object.is('remove', action)) {
            this.remove(data);
        }
        if (Object.is('submit', action)) {
            this.submitWorkFlow(data,'wfsubmit');
        }
    });
    }
    }

    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof EditForm
     */
    public getDatas(): any[] {
        return [this.data];
    }

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof EditForm
     */
    public getData(): any {
        return this.data;
    }

    /**
     * 属性值规则
     *
     * @type {*}
     * @memberof EditForm
     */
    public rules: any = {
        nd: [
            { required: false, type: 'string', message: '年度值不能为空!', trigger: 'change' }
        ],
        jfrq: [
            { required: false, type: 'string', message: '计费日期值不能为空!', trigger: 'change' }
        ],
        sqds: [
            { required: false, type: 'number', message: '上期底数值不能为空!', trigger: 'change' }
        ],
        bqs: [
            { required: false, type: 'number', message: '本期数值不能为空!', trigger: 'change' }
        ],
        ydl: [
            { required: false, type: 'number', message: '用电量值不能为空!', trigger: 'change' }
        ],
        ydfy: [
            { required: false, type: 'number', message: '用电费用值不能为空!', trigger: 'change' }
        ],
        sfdj: [
            { required: false, type: 'string', message: '收费单据值不能为空!', trigger: 'change' }
        ],
    }


    /**
     * 当前分页激活值
     *
     */
    public $activeFormPage:string = 'formpage1';

    /**
     * 表单数据处理对象
     *
     * @type {*}
     * @memberof EditForm
     */
    public $data: any = {
            srfupdatedate:null,
            srforikey:null,
            srfkey:null,
            srfmajortext:null,
            srftempmode:null,
            srfuf:null,
            srfdeid:null,
            srfsourcekey:null,
            nd:null,
            jfrq:null,
            sqds:null,
            bqs:null,
            ydl:null,
            ydfy:null,
            sfdj:null,
            dfid:null,
            ismodify:false
    };

    /**
     * 表单数据对象
     *
     * @type {*}
     * @memberof EditForm
     */
    public data: any = {};

    public initData(){
        Object.defineProperty(this.data, 'srfupdatedate', {
            get: () =>{
              return this.$data.srfupdatedate;
            },
            set: (val) =>{
                this.$data.srfupdatedate = val;
                this.$data.ismodify =true;
                this.formLogic({name:'srfupdatedate',newVal:this.$data.srfupdatedate,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'srforikey', {
            get: () =>{
              return this.$data.srforikey;
            },
            set: (val) =>{
                this.$data.srforikey = val;
                this.$data.ismodify =true;
                this.formLogic({name:'srforikey',newVal:this.$data.srforikey,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'srfkey', {
            get: () =>{
              return this.$data.srfkey;
            },
            set: (val) =>{
                this.$data.srfkey = val;
                this.$data.ismodify =true;
                this.formLogic({name:'srfkey',newVal:this.$data.srfkey,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'srfmajortext', {
            get: () =>{
              return this.$data.srfmajortext;
            },
            set: (val) =>{
                this.$data.srfmajortext = val;
                this.$data.ismodify =true;
                this.formLogic({name:'srfmajortext',newVal:this.$data.srfmajortext,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'srftempmode', {
            get: () =>{
              return this.$data.srftempmode;
            },
            set: (val) =>{
                this.$data.srftempmode = val;
                this.$data.ismodify =true;
                this.formLogic({name:'srftempmode',newVal:this.$data.srftempmode,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'srfuf', {
            get: () =>{
              return this.$data.srfuf;
            },
            set: (val) =>{
                this.$data.srfuf = val;
                this.$data.ismodify =true;
                this.formLogic({name:'srfuf',newVal:this.$data.srfuf,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'srfdeid', {
            get: () =>{
              return this.$data.srfdeid;
            },
            set: (val) =>{
                this.$data.srfdeid = val;
                this.$data.ismodify =true;
                this.formLogic({name:'srfdeid',newVal:this.$data.srfdeid,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'srfsourcekey', {
            get: () =>{
              return this.$data.srfsourcekey;
            },
            set: (val) =>{
                this.$data.srfsourcekey = val;
                this.$data.ismodify =true;
                this.formLogic({name:'srfsourcekey',newVal:this.$data.srfsourcekey,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'nd', {
            get: () =>{
              return this.$data.nd;
            },
            set: (val) =>{
                this.$data.nd = val;
                this.$data.ismodify =true;
                this.formLogic({name:'nd',newVal:this.$data.nd,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'jfrq', {
            get: () =>{
              return this.$data.jfrq;
            },
            set: (val) =>{
                this.$data.jfrq = val;
                this.$data.ismodify =true;
                this.formLogic({name:'jfrq',newVal:this.$data.jfrq,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'sqds', {
            get: () =>{
              return this.$data.sqds;
            },
            set: (val) =>{
                this.$data.sqds = val;
                this.$data.ismodify =true;
                this.formLogic({name:'sqds',newVal:this.$data.sqds,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'bqs', {
            get: () =>{
              return this.$data.bqs;
            },
            set: (val) =>{
                this.$data.bqs = val;
                this.$data.ismodify =true;
                this.formLogic({name:'bqs',newVal:this.$data.bqs,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'ydl', {
            get: () =>{
              return this.$data.ydl;
            },
            set: (val) =>{
                this.$data.ydl = val;
                this.$data.ismodify =true;
                this.formLogic({name:'ydl',newVal:this.$data.ydl,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'ydfy', {
            get: () =>{
              return this.$data.ydfy;
            },
            set: (val) =>{
                this.$data.ydfy = val;
                this.$data.ismodify =true;
                this.formLogic({name:'ydfy',newVal:this.$data.ydfy,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'sfdj', {
            get: () =>{
              return this.$data.sfdj;
            },
            set: (val) =>{
                this.$data.sfdj = val;
                this.$data.ismodify =true;
                this.formLogic({name:'sfdj',newVal:this.$data.sfdj,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'dfid', {
            get: () =>{
              return this.$data.dfid;
            },
            set: (val) =>{
                this.$data.dfid = val;
                this.$data.ismodify =true;
                this.formLogic({name:'dfid',newVal:this.$data.dfid,oldVal:null});
            }
        });
    }

    /**
     * 初始化部件关联视图
     */
    public initRefView(){
    }

    /**
     * 获取关联视图
     */
    public getModalView(data:string){
        return this.refViewMap.get(data);
    }

    /**
     * 表单逻辑
     *
     * @private
     * @param {{ name: string, newVal: any, oldVal: any }} { name, newVal, oldVal }
     * @memberof EditForm
     */
    private formLogic({ name, newVal, oldVal }: { name: string, newVal: any, oldVal: any }): void {
                









    }

    /**
     * 获取全部值
     *
     * @returns {*}
     * @memberof Main
     */
    public getValues(): any {
        return this.$data;
    }

    /**
     * 详情模型集合
     *
     * @type {*}
     * @memberof EditForm
     */
    public detailsModel: any = {};

    /**
     * 初始化表单详情模型集合
     *
     * @memberof EditForm
     */
    public initFormDetailsModel(): void {
        Object.assign(this.detailsModel, {
            nd: new FormItemModel({ caption: '年度', detailType: 'FORMITEM', name: 'nd', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            jfrq: new FormItemModel({ caption: '计费日期', detailType: 'FORMITEM', name: 'jfrq', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            sqds: new FormItemModel({ caption: '上期底数', detailType: 'FORMITEM', name: 'sqds', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            bqs: new FormItemModel({ caption: '本期数', detailType: 'FORMITEM', name: 'bqs', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            ydl: new FormItemModel({ caption: '用电量', detailType: 'FORMITEM', name: 'ydl', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            ydfy: new FormItemModel({ caption: '用电费用', detailType: 'FORMITEM', name: 'ydfy', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            sfdj: new FormItemModel({ caption: '收费单据', detailType: 'FORMITEM', name: 'sfdj', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            grouppanel1: new FormGroupPanelModel({ caption: '分组面板', detailType: 'GROUPPANEL', name: 'grouppanel1', visible: true, isShowCaption: false })

        });
        Object.assign(this.detailsModel, {
            formpage1: new FormPageModel({ caption: '基本信息', detailType: 'FORMPAGE', name: 'formpage1', visible: true, isShowCaption: true })

        });
    }

    /**
     * 检验规则
     */
    public validateRules():boolean{
        let result =true;
        Object.keys(this.rules).forEach((item:any) =>{
            //必填校验
            if(this.rules[item][0].required){
                if(!this.data[item]){
                    this.$notification.error(this.rules[item][0].message);
                    result = false;
                    return result;
                }
            }
        });
        return result;
    }

    /**
     * 值填充
     *
     * @param {*} [_datas={}]
     * @memberof Main
     */
    public fillForm(_datas: any = {}): void {
        this.ignorefieldvaluechange = true;
        Object.keys(_datas).forEach((name: string) => {
            if (this.data.hasOwnProperty(name)) {
                this.data[name] = _datas[name];
            }
        });
        this.ignorefieldvaluechange = false;
    }

    /**
     * 部件刷新
     *
     * @param {any[]} args
     * @memberof EditForm
     */
    public refresh(args: any[]): Promise<any> {
        return new Promise((resolve: any, reject: any) =>{
        let arg: any = {};
        if (this.data.srfkey && !Object.is(this.data.srfkey, '')) {
            Object.assign(arg, { srfkey: this.data.srfkey });
            this.load(arg);
            return;
        }
        if (this.data.srfkeys && !Object.is(this.data.srfkeys, '')) {
            Object.assign(arg, { srfkey: this.data.srfkeys });
            this.load(arg);
            return;
        }
        })
    }


    /**
     * 自动加载
     *
     * @param {*} [arg={}]
     * @returns {void}
     * @memberof EditForm
     */
    public autoLoad(arg: any = {}): void {
        if (arg.srfkey && !Object.is(arg.srfkey, '')) {
            this.load(arg);
            return;
        }
        if (arg.srfkeys && !Object.is(arg.srfkeys, '')) {
            Object.assign(arg, { srfkey: arg.srfkeys });
            this.load(arg);
            return;
        }
        this.loadDraft(arg);
    }

    /**
     * 加载
     *
     * @private
     * @param {*} [opt={}]
     * @memberof EditForm
     */
    private load(opt: any = {}): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
            const arg: any = { ...opt };
            this.$http.get1(this.url + this.loadAction, {srfkey:arg.srfkey}).then((response: any) => {
                if (response) {
                    const data = response;
                    this.fillForm(data);
                    this.formLogic({ name: '', newVal: null, oldVal: null });
                    this.$data.ismodify = false;
                    this.loademit.emit(data);
                    this.formState.next({ type: 'load', data: data });
                    resolve(data);
                }
            }).catch((error: any) => {
                this.$notification.error('错误,' + error.error.message);
                reject(error);
            });
        })
    }

    /**
     * 删除
     *
     * @private
     * @param {*} [opt={}]
     * @memberof EditForm
     */    
    private remove(opt: any = {}): Promise<any> {
        if(!Object.is(opt.srfkey,this.data.srfkey)){
            return;
        }
        return new Promise((resolve: any, reject: any) => {
            const arg: any = { ...opt };
            this.$http.get1(this.url + this.removeAction, {srfkey:arg.srfkey}).then((response: any) => {
                if (response) {
                    const data = response;
                    this.removeemit.emit(data);
                    this.formState.next({ type: 'remove', data: data });
                    this.$data.ismodify = false;
                    resolve(data);
                }
            }).catch((error: any) => {
                this.$notification.error('错误,' + error.error.message);
                reject(error);
            });
        });
    }

    /**
     * 加载草稿
     *
     * @param {*} [opt={}]
     * @memberof EditForm
     */
    public loadDraft(opt: any = {}): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
            const arg: any = { ...opt };
            let post: any;
            if (!arg.srfsourcekey || Object.is(arg.srfsourcekey, '')) {
                post = this.$http.post(this.url + this.loaddraftAction, arg);
            } else {
                post = this.$http.post(this.url + this.loaddraftformAction, arg);
            }
            post.then((response: any) => {
                if (response) {
                    const data = response;
                    this.fillForm(data);
                    this.formLogic({ name: '', newVal: null, oldVal: null });
                    this.$data.ismodify = false;
                    this.loademit.emit(data);
                    this.formState.next({ type: 'load', data: data });
                    resolve(data);
                }
            }).catch((error: any) => {
                this.$notification.error('错误,' + error.error.message);
                reject(error);
            });
        })
    }

    /**
     * 自动保存
     *
     * @param {*} [opt={}]
     * @memberof EditForm
     */
    public autoSave(opt: any = {}, action?: string): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
            let result = this.validateRules();
            if(!result){
                return;
            }
            const arg: any = { ...opt };
            const data = this.getValues();
            Object.assign(arg, data);
            if (!action) {
                this.formState.next({ type: 'beforesave', data: arg });//editview9保存之前事件
            }
            if (arg.end) {
                return;
            }
            let post: any;
            if (Object.is(data.srfuf, '1')) {
                post = this.$http.post(this.url + this.updateAction, arg);
            } else {
                post = this.$http.post(this.url + this.createAction, arg);
            }
            post.then((response: any) => {
                if (response) {
                    const data = response;
                    this.fillForm(data);
                    this.formLogic({ name: '', newVal: null, oldVal: null });
                    this.$data.ismodify = false;
                    this.saveemit.emit(data);
                    this.formState.next({ type: 'save', data: data });
                    resolve(data);
                }
            }).catch((error: any) => {
                this.$notification.error('错误,' + error.error.message);
                reject(error);
            });
        })
    }

    /**
     * 保存
     *
     * @param {*} [opt={}]
     * @memberof EditForm
     */
    public save(opt: any = {},action?: string): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
            let result = this.validateRules();
            if(!result){
                return;
            }
            const arg: any = { ...opt };
            const data = this.getValues();
            Object.assign(arg, data);
            if (!action) {
                this.formState.next({ type: 'beforesave', data: arg });//editview9保存之前事件
            }
            if (arg.end) {
                return;
            }
            let post: any;
            if (Object.is(data.srfuf, '1')) {
                post = this.$http.post(this.url + this.updateAction, arg);
            } else {
                post = this.$http.post(this.url + this.createAction, arg);
            }
            post.then((response: any) => {
                if (response) {
                    const data = response;
                    this.fillForm(data);
                    this.formLogic({ name: '', newVal: null, oldVal: null });
                    this.saveemit.emit(data);
                    this.$data.ismodify = false;
                    this.formState.next({ type: 'save', data: data });
                    if(!arg.iscancelnotice){
                        this.$notification.success((data.srfmajortext ? data.srfmajortext : '') + '保存成功！');
                    }
                    resolve(data);
                }
            }).catch((error: any) => {
                if(!arg.iscancelnotice){
                    this.$notification.error('错误,' + error.error.message);
                    reject(error);
                }
            })
        })
    }

    /**
     * 表单项更新
     *
     * @param {string} mode
     * @memberof EditForm
     */
    public updateFormItems(mode: string, data: any = {}, showloading?: boolean): void {
         if (!mode || (mode && Object.is(mode, ''))) {
            return;
        }
        const action = mode.toLowerCase();
        const arg: any = { ...data };
        this.$http.post(this.url + 'updateformitem/' + action, arg,showloading).then((response: any) => {
            if (!response) {
                this.$notification.error('失败,加载数据失败');
            }
            if (response) {
                const data = response.data;
                //this.setFormEnableCond(data);
                this.fillForm(data);
                this.formLogic({ name: '', newVal: null, oldVal: null });
                this.formState.next({ type: 'updateformitem', ufimode: arg.srfufimode, data: data });
            }
        });
    }

    /**
     * 开始工作流
     *
     * @param {} data
     * @memberof EditForm
     */
    public startWorkFlow(data: any = {}): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
            const arg: any = { ...data };
            this.$http.post(this.url + 'wfstart', arg).then((response: any) => {
                if (!response) {
                    this.$notification.error('开始流程失败');
                }
                if (response) {
                    resolve(response);
                    this.$notification.success('开始流程成功');
                }
            });
        });
    }

    /**
     * 提交工作流
     *
     * @param {} data
     * @memberof EditForm
     */
    public submitWorkFlow(data: any = {},actionUrl?:string): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
            const arg: any = { ...data };
            Object.assign(arg,{srfkey:this.$data.srfkey});
            let rquestUrl = actionUrl?this.url+actionUrl:this.url+this.wfsubmitAction;
            this.$http.post(rquestUrl, arg).then((response: any) => {
                if (!response) {
                    reject({});
                }
                if (response) {
                    this.wfsubmitemit.emit(response);
                    resolve(response);
                }
            });
        });
    }

    /**
     * 多数据视图加载完成，触发后续表单项更新
     *
     * @param {string} mode
     * @memberof EditForm
     */
    public mditemsload($event:any){

    }

    /**
     * DEMEDITVIEW9 关系数据保存完成
     *
     * @param {string} mode
     * @memberof EditForm
     */
    public drdatasaved($event:any){
        this.save({},$event.action);
    }


    /**
     * DEMEDITVIEW9 关系数据值变化
     *
     * @param {string} mode
     * @memberof EditForm
     */
    public drdatachange: ($event: any) => {

    }

    /**
     * 视图数据变化
     *
     * @param {string} mode
     * @memberof EditForm
     */
    public viewdataschange: ($event: any) => {

    }

    /**
     * 视图加载完成
     *
     * @param {string} mode
     * @memberof EditForm
     */
    public viewload: ($event: any) => {

    }

    ngOnDestroy(): void {
        if (this.viewStateEvent) {
            this.viewStateEvent.unsubscribe();
        }
    }

    //表单插件逻辑



}