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';
import {XMMobPickupViewPage} from '@pages/demo/xmmob-pickup-view/xmmob-pickup-view.page';


@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/ht/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 = {
        xmname: [
            { required: false, type: 'string', message: '项目名称值不能为空!', trigger: 'change' }
        ],
        xmje: [
            { required: false, type: 'number', message: '项目金额值不能为空!', trigger: 'change' }
        ],
        htname: [
            { required: false, type: 'string', message: '合同名称值不能为空!', trigger: 'change' }
        ],
        dfdw: [
            { required: false, type: 'string', message: '对方单位值不能为空!', trigger: 'change' }
        ],
        lxdh: [
            { required: false, type: 'string', message: '联系电话值不能为空!', trigger: 'change' }
        ],
        cgfs: [
            { required: false, type: 'string', message: '采购方式值不能为空!', trigger: 'change' }
        ],
        je: [
            { required: false, type: 'number', 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,
            xmname:null,
            xmje:null,
            htname:null,
            dfdw:null,
            lxdh:null,
            cgfs:null,
            je:null,
            xmid:null,
            htid: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, 'xmname', {
            get: () =>{
              return this.$data.xmname;
            },
            set: (val) =>{
                this.$data.xmname = val;
                this.$data.ismodify =true;
                this.formLogic({name:'xmname',newVal:this.$data.xmname,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'xmje', {
            get: () =>{
              return this.$data.xmje;
            },
            set: (val) =>{
                this.$data.xmje = val;
                this.$data.ismodify =true;
                this.formLogic({name:'xmje',newVal:this.$data.xmje,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'htname', {
            get: () =>{
              return this.$data.htname;
            },
            set: (val) =>{
                this.$data.htname = val;
                this.$data.ismodify =true;
                this.formLogic({name:'htname',newVal:this.$data.htname,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'dfdw', {
            get: () =>{
              return this.$data.dfdw;
            },
            set: (val) =>{
                this.$data.dfdw = val;
                this.$data.ismodify =true;
                this.formLogic({name:'dfdw',newVal:this.$data.dfdw,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'lxdh', {
            get: () =>{
              return this.$data.lxdh;
            },
            set: (val) =>{
                this.$data.lxdh = val;
                this.$data.ismodify =true;
                this.formLogic({name:'lxdh',newVal:this.$data.lxdh,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'cgfs', {
            get: () =>{
              return this.$data.cgfs;
            },
            set: (val) =>{
                this.$data.cgfs = val;
                this.$data.ismodify =true;
                this.formLogic({name:'cgfs',newVal:this.$data.cgfs,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'je', {
            get: () =>{
              return this.$data.je;
            },
            set: (val) =>{
                this.$data.je = val;
                this.$data.ismodify =true;
                this.formLogic({name:'je',newVal:this.$data.je,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'xmid', {
            get: () =>{
              return this.$data.xmid;
            },
            set: (val) =>{
                this.$data.xmid = val;
                this.$data.ismodify =true;
                this.formLogic({name:'xmid',newVal:this.$data.xmid,oldVal:null});
            }
        });
        Object.defineProperty(this.data, 'htid', {
            get: () =>{
              return this.$data.htid;
            },
            set: (val) =>{
                this.$data.htid = val;
                this.$data.ismodify =true;
                this.formLogic({name:'htid',newVal:this.$data.htid,oldVal:null});
            }
        });
    }

    /**
     * 初始化部件关联视图
     */
    public initRefView(){
        this.refViewMap.set('demo_xmmobpickupview',XMMobPickupViewPage);
    }

    /**
     * 获取关联视图
     */
    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 {
                









        if(Object.is(name, 'xmname')){
            this.updateFormItems('getXminfo', this.data,false);
        }
    }

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

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

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

        });
        Object.assign(this.detailsModel, {
            xmje: new FormItemModel({ caption: '项目金额', detailType: 'FORMITEM', name: 'xmje', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            htname: new FormItemModel({ caption: '合同名称', detailType: 'FORMITEM', name: 'htname', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            dfdw: new FormItemModel({ caption: '对方单位', detailType: 'FORMITEM', name: 'dfdw', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            lxdh: new FormItemModel({ caption: '联系电话', detailType: 'FORMITEM', name: 'lxdh', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            cgfs: new FormItemModel({ caption: '采购方式', detailType: 'FORMITEM', name: 'cgfs', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            je: new FormItemModel({ caption: '金额', detailType: 'FORMITEM', name: 'je', visible: true, isShowCaption: true, disabled: false, isAllowEmpty: true })

        });
        Object.assign(this.detailsModel, {
            group1: new FormGroupPanelModel({ caption: '合同基本信息', detailType: 'GROUPPANEL', name: 'group1', visible: true, isShowCaption: true })

        });
        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();
        }
    }

    //表单插件逻辑



}