import {action, asMap, observable, toJS} from 'mobx';
import * as API from "../apis/Ldap.js";
import {message, Modal} from 'antd';
import {WeaLocaleProvider} from "ecCom";
import ListStore from "../public/list/stores/ListStore";
import BaseSetStore from "../public/baseSet/stores/BaseSetStore"

const getLabel = WeaLocaleProvider.getLabel;

export class LdapStore {

    @observable listStore = new ListStore();

    @observable baseSetStore = new BaseSetStore();

    template = {};

    formart = [];

    baseTableEdit = [];

    ldapRef = {};

    pkqSelectedKey = '';

    @observable status = {

        //API地址
        listApiUrl: {},

        baseApiUrl: {},

        showBase: false,

        dialogType: '',

        baseDatas: {},

        key: {},

        logDatas: {
            show: false,
            targetId: ''
        },

        baseTabKey: '',
		selectedKey: 'base',
        testInitDatas: {},

        // test页面
        showTestVersion: false,
        topinfo: {},
        menuinfo: [],
        collectInfo: {},
        buttoninfo: [],
        moreBtninfo: [],
        testColumns: [],
        testTitle: {},
        errorMessage: '',

        // 日志详情页面
        showLogDetail: false
    };

    @action
    setState = (params = {}) => {
        Object.assign(this.status, params);
    };

    setPKQSelectedKey = (val) => {
        this.pkqSelectedKey = val;
    }

    /**
     * 配置定时任务
     * @param form
     */
    @action
    configSchedule = (form) => {
        form && form.isFormInit && form.validateForm().then(f => {
            if (f.isValid) {
                let params = form.getFormParams();
                API.configSchedule(params).then(result => {
                    if (result.status == true) {
                        this.setState({
                            key: Math.random().toString(36).substr(2, 6),
                            showBase: false,
                            baseDatas: {}
                        });
                        form.resetForm();
                        message.success(result.error);
                    }
                });
            } else {
                f.showErrors();
            }
        });
    }

    /**
     * 保存LDAP基础信息
     * @param form
     */
    @action
    saveBase = (form) => {
        let type;
        if (this.status.baseDatas && this.status.baseDatas.ldapId) {
            type = "edit";
        } else {
            type = "add";
        }

        API.saveBase(type, form.getFormParams()).then(result => {
            if (result.status == true) {
                this.setState({
                    key: Math.random().toString(36).substr(2, 6),
                    showBase: false,
                    baseDatas: {}
                });
                form.resetForm();
                message.success(result.error);
            }
        });
    }
	
	 /**
     * 保存LDAP自定义接口基础信息
     * @param form
     */
    @action
    saveCustomInterfaceBase = (form) => {
        let type;
        if (this.status.baseDatas && this.status.baseDatas.formartid) {
            type = "editCustomInterface";
        } else {
            type = "addCustomInterface";
        }

        API.saveCustomInterfaceBase(type, form.getFormParams()).then(result => {
            if (result.status == true) {
                this.setState({
                    key: Math.random().toString(36).substr(2, 6),
                    showBase: false,
                    baseDatas: {}
                });
                form.resetForm();
                message.success(result.error);
            }
        });
    }

    /**
     * 删除LDAP
     * @param params
     */
    @action
    deleteLdap = (params) => {
        API.deleteLdap(params).then(result => {
            if (result.status == true) {
                message.success(result.error);
                this.setState({
                    key: Math.random().toString(36).substr(2, 6),
                    showBase: false,
                    baseDatas: {}
                });
                this.listStore.status.rowSelectIds=[];
            } else {
                message.error(result.error);
            }
        });
    }
	
	/**
     * 删除LDAP自定义接口
     * @param params
     */
    @action
    deleteCustomInterface = (params) => {
        API.deleteCustomInterface(params).then(result => {
            if (result.status == true) {
                message.success(result.error);
                this.setState({
                    key: Math.random().toString(36).substr(2, 6),
                    showBase: false,
                    baseDatas: {}
                });
                this.listStore.status.rowSelectIds=[];
            } else {
                message.error(result.error);
            }
        });
    }

    /**
     * 删除LDAP同步日志接口
     * @param params
     */
    @action
    deleteLdapSyncLog = (params) => {
        API.deleteLdapSyncLog(params).then(result => {
            if (result.status == true) {
                message.success(result.error);
                this.setState({
                    key: Math.random().toString(36).substr(2, 6),
                    showBase: true,
                    // baseDatas: params,  // 这里复写baseDatas会出问题，导致ldapId丢失
                    showLogDetail: false,
                    dialogType: 'synclog',
                    baseApiUrl: '/api/integration/ldap/synclog'
                });
                this.baseSetStore.status.rowSelectIds=[];
            } else {
                message.error(result.error);
            }
        });
    }

    /**
     * 配置同步信息
     * @param type
     * @param params
     */
    @action
    configSync = (type,params) => {
        API.configSync(this.status.baseDatas.ldapId,type, params).then(result => {
            if (result.status == true) {
                this.setState({
                    showBase: false,
                    baseDatas: {}
                });
                message.success(result.error);
            } else {
                message.error(result.error);
            }
        });
    }

    /**
     * 配置映射关系
     * @param type
     * @param params
     */
    @action
    configMapping = (type, params) => {
        API.configMapping(this.status.baseDatas.ldapId, type, params).then(result => {
            if (result.status == true) {
                this.setState({
                    showBase: false,
                    baseDatas: {}
                });
                message.success(result.error);
            } else {
                message.error(result.error);
            }
        });
    }

    /**
     * 获取模板信息
     * @param type 类别（ou\pull:组织结构，subcompany:分部,department：部门,user：人员,
     *             oaou\push:反向组织结构，oasubcompany:反向分部,oadepartment：反向部门,oauser：反向人员）
     */
    @action
    getTemplate = (type) => {

        return API.getTemplate(type).then(result => {
            if (result.status == true) {
                let options = [];
                let datas = {};

                for (let t of result.data) {
                    options.push({
                        key: t.fieldKey,
                        showname: t.fieldName
                    });

                    datas[t.fieldKey] = {
                        attributeType: t.defaultType,
                        attributeValue: t.defaultValue,
                        showName: t.fieldName,
                        isMust: t.isMust
                    }
                }
                Object.assign(this.template, {[type]: {options, datas}});
            }
        });
    }

    /**
     * 获取数据转换方法列表
     * @param type
     */
    @action
    initFormart = (type) => {
        return API.getFormart(type).then(result => {
            if (result.status == true) {
                this.formart=[];
                for (let f of result.data) {
                    this.formart.push({
                        key: f.formartId,
                        showname: f.formartName
                    });
                }
            }
        });
    }

    /**
     * 执行同步
     * @param type
     * @param form
     */
    @action
    runSync = (type,form) => {

        const ldapId = this.status.baseDatas.ldapId;

        let params;
        if (form.getFormParams().type && form.getFormParams().type == "0") {
            params = {syncDate: form.getFormParams().syncDate};
        } else {
            params = {};
        }

        API.runSync(ldapId,type, params).then(result => {
            if (result.status == true) {
                this.showSyncLog(ldapId, 0, form);
            } else if("104" == result.errorCode) {
                this.showSyncLog(ldapId, 0, form);
            }
        },(error,datas) => {
            if(datas && "104" == result.errorCode) {
                this.showSyncLog(ldapId, 0, form);
            }
        });
    }

    /**
     * 显示同步日志信息
     */
    @action
    showSyncLog = (ldapId, lineNumber, form) => {

        API.showSyncLog(ldapId, {lineNumber: lineNumber}).then(result => {

            if(!form || !form.isFormInit || !form.getFormDatas().syncLogShow){
                return;
            }
            let log = form.getFormDatas().syncLogShow.value;
            log += result.data;
            form.updateFields({syncLogShow: log});

            if(!this.ldapRef || !this.ldapRef.refs || !this.ldapRef.refs.syncLogRefs){
                return;
            }
            this.ldapRef.refs.syncLogRefs.scrollToLast();

            let currentLineNumber;
            if(result.status == true) {
                form.updateFields({isSync: 0});
                currentLineNumber = 0;
            }else if (result.status == false && "106" == result.errorCode) {
                if (result.ext && !isNaN(result.ext) && parseInt(result.ext) >= 0) {
                    currentLineNumber = parseInt(result.ext) + 1;
                    setTimeout((ldapId, currentLineNumber, form) => {
                        this.showSyncLog(ldapId, currentLineNumber, form)
                    }, 2000, ldapId, currentLineNumber, form);
                }
            }
        },(error,datas) => {
            if(datas && "106" == result.errorCode) {
                if (result.ext && !isNaN(result.ext) && parseInt(result.ext) >= 0) {
                    currentLineNumber = parseInt(result.ext) + 1;
                    setTimeout((ldapId, currentLineNumber, form) => {
                        this.showSyncLog(ldapId, currentLineNumber, form)
                    }, 2000, ldapId, currentLineNumber, form);
                }
            }
        });
    }

    @action 
    getBase = (type) => {
        API.getBase(this.status.baseDatas.ldapId, type).then(result => {
            this.setState({
                testInitDatas: {},
                errorMessage: ''
            })
            if(type == (this.status.topinfo && this.status.topinfo.tab && this.status.topinfo.tab.selectedKey)) {
                if(result.status) {
                    if(result.ext == 'true') {
                        let datas = {};
                        if(result.data && result.data.sync) {
                            datas = Object.assign({}, datas, {'sync': result.data.sync});
                        }
                        if(result.data && result.data.ou) {
                            datas = Object.assign({}, datas, {'ou': result.data.ou});
                        }  
                        if(result.data && result.data.subcompany) {
                            datas = Object.assign({}, datas, {'subcompany': result.data.subcompany});
                        } 
                        if(result.data && result.data.department) {
                            datas = Object.assign({}, datas, {'department': result.data.department});
                        }
                        if(result.data && result.data.user) {
                            datas = Object.assign({}, datas, {'user': result.data.user});
                        }
    
                        if(type == 'base') {
                            this.setState({
                                testInitDatas: result.data
                            })
                        }else {
                            this.setState({
                                testInitDatas: datas
                            })
                        }
                    }else if(result.ext == 'false') {
                        this.setState({
                            errorMessage: result.error
                        })
                    }
                }
            }
        })
    }

    @action
    getTestFields = () => {
        API.getFields(this.status.baseApiUrl, this.status.baseDatas).then(res => {
            if(res.status) {
                this.setState({
                    testColumns: res.data.columns,
                    testTitle: res.data.title
                })
            }
        })
    }

    @action
    getTestMenu = () => {
        API.getRightMenu(this.status.baseApiUrl, this.status.baseDatas).then(result => {
            if(result.status) {
                this.setState({
                    menuinfo: result.data.rightMenus,
                    collectinfo: result.data.collectParams,
                    topinfo: result.data.top,
                    buttoninfo: result.data.button,
                    moreBtninfo: result.data.moreButton
                })
            }
        })
    }

    @action 
    updateUserInfo = (param) => {
      API.updateUserInfo(param).then(result => {
        if(result.status && (result.errorCode == 100)) {
          this.setState({
            showBase: false
          })
          this.listStore.setState({rowSelectIds: []});
          this.listStore.tableStore.reloadCurrent();
          message.success(result.error);
        }
      })
    }

    @action
    mergeUserInfo = (param) => {
      API.mergeUserInfo(param).then(result => {
        if(result.status && (result.errorCode == 100)) {
          this.setState({
            showBase: false
          })
          this.listStore.setState({rowSelectIds: []});
          this.listStore.tableStore.reloadCurrent();
          message.success(result.error);
        }
      })
    }

    @action
    getTestMatchData = (params) => {
      API.getTestMatchData(params).then(result => {
        if(result.status === 'SUCCESS'){
          this.baseSetStore.setState({
            testMatchColumns: result.columns || [],
            testMatchDatas: result.datas || [],
            loading: true
          });
        }else if(!result.status.status && (result.status.errorCode == 103)) {
          message.error(result.status.error);
        }
      })
    }

    @action 
    batchMergeUserInfo = (params) => {
      API.batchMergeUserInfo(params).then(result => {
        if(result.status) {
          this.setState({
            showBase: false
          })
          message.success(result.error);
          this.listStore.tableStore.reloadCurrent();
        }else {
          message.error(result.error);
        }
      })
    }
}

