import * as Api from '../apis/login'; //TODO
import {
    getAdvancedItem,
    checkNonstandard
} from '../util/IntegrationUtil';
import uuid from 'uuid';
import {
    observable,
    action,
    toJS,
} from 'mobx';
import {
    WeaForm,
    WeaTableNew,
    WeaLogView,
} from 'comsMobx';
import {
    WeaLocaleProvider,
    WeaButtonIcon,
    WeaTools,
} from 'ecCom';
import {
    message,
    Button,
    Modal,
} from 'antd';

const {
    TableStore
} = WeaTableNew;
const {
    LogStore
} = WeaLogView;
const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;
const Base64 = WeaTools.Base64;

export class InteLogin {
    //*************************index********************************
    @observable main = {
        authorized: false,
        loading: true,
        hasNonStandard: true,
        nonStandLoading: true
    }
    @observable HRMNetworkListVisible = false; 
    @observable mailTypeAuthorized = true; 
    @observable mailTypeAuthorizedLoading = true; 
    @observable mailOutterSelect = []; 
    @observable source = '';
    @observable dialog = '';
    @observable result = '';
    @observable status = {
        showErrorDialog:false,
        errorMessage:[],
        hiddenField:true,
        isRequestTypeEdit:false,
    };

    setState = (params = {}) => {
        let status = { ...this.status };
        Object.keys(params).forEach(key => {
            status[key] = params[key];
        });
        this.status = status;
    };

    @action
    getAuth = () => {
        checkNonstandard({num: "005"}, (result) => {
          this.main.hasNonStandard = result.isOpen;
          this.main.nonStandLoading = false;
          if(result.isOpen) {
            if(!this.source) {
                this.refresh();
            }
            Api.getAuth().then(cb => {
                const {
                    status,
                    ret,
                } = cb;
    
                if (status == '1') { 
                    ret == 'success' && this.grantAuth();
                    this.main.loading = false;
                } else {
                    message.error(cb.message);
                }
            }).catch(error => {
                message.error(error);
            });
          }
        })
    }

    @action
    grantAuth = () => {
        this.main.authorized = true;
    }

    @action
    stoploading = () => {
        this.main.loading = false;
    }

    @action
    refresh = () => {
        this.clickTab('0');
    }

    //*************************Top*******************************
    @observable top = {
        title: getLabel(20960, "集成登录"), //todo
        menu: [],
        buttons: [],
        dropMenuDatas: []
    }

    @action
    getMenus = (select) => {
        const {
            key
        } = this.mainTab;
        let selectedKey = select || key;
        Api[selectedKey == '0' ? 'operateSysForm' : selectedKey == '1' ? 'operateEncryptForm' : 'operateTypeForm']({
            operate: 'getListButtons'
        }).then(cb => {
            const {
                status,
                rightMenus
            } = cb;

            if (status == '1') {
                this.top.menu = rightMenus;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    get menus() {
        const top = this.top && this.top.menu && this.top.menu.filter(item => item.isTop == '1' && (item.menuFun != 'BTN_LOG') && (item.menuFun != 'BTN_TYPE_LOG')),
            right = this.top && this.top.menu && this.top.menu.filter(item => (item.menuFun != 'BTN_Collect') && (item.menuFun != "BTN_TYPE_Collect"));

        const {
            tableStore
        } = this.mainTable;

        let buttons = [],
            dropMenuDatas = [],
            outTopButtons = [];

        top && top.map(item => {
            const disabled = (['BTN_DEL', 'encrypt_delete', 'BTN_TYPE_DEL'].includes(item.menuFun)) ? tableStore.selectedRowKeys.length == 0 : tableStore.loading;
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@81l0km@integrationOutterButton${item.menuFun}Btn`} type='primary' disabled={disabled}
                                 onClick={() => this.handleTopBtnsClick(item)}>{item.menuName}</Button>);
        });

        right && right.map((item, index) => {
            let obj = {
                key: item.menuFun,
                icon: <i className={`${item.menuIcon}`}/>,
                content: item.menuName,
                onClick: (params={}) => this[item.menuFun](params)
            }
            if (['BTN_DEL', 'encrypt_delete', 'BTN_TYPE_DEL'].includes(item.menuFun)) {
                obj.disabled = tableStore.selectedRowKeys.length == 0;
            }
            if(!['BTN_COLUMN', 'BTN_TYPE_LOG', 'BTN_LOG'].includes(item.menuFun)) {
              outTopButtons.push(obj); 
            }
            dropMenuDatas.push(obj);
        })

        return {
            buttons,
            dropMenuDatas,
            outTopButtons
        };
    }

    @action
    handleTopBtnsClick = (item, params={}) => {
        const {
            isPanelShow
        } = this.mainTab;

        isPanelShow && this.changePanelStatus(false);
        this[item.menuFun] && this[item.menuFun](params);
    }

    @action
    BTN_TYPE_NEW = () => {
        this.openDialog({
            type: 'BTN_TYPE_NEW'
        })
    }

    @action
    BTN_NEW = () => {
        this.openDialog({
            type: 'BTN_NEW'
        })
    }

    @action
    encrypt_new = () => {
        this.setIsSysAlgorithm({
            isSysAlgorithm: false
        });
        this.openDialog({
            type: 'encrypt_new'
        })
    }

    BTN_TYPE_DEL = (params={}) => {
        this.showConfirm({
            type: '1',
            mailParams: {...params}
        });
    }

    BTN_DEL = (params={}) => {
        this.showConfirm({
            type: '1',
            mailParams: {...params}
        });
    }

    encrypt_delete = () => {
        this.showConfirm({
            type: '1'
        });
    }

    BTN_COLUMN = () => {
        this.displayColCustom();
    }

    BTN_TYPE_COLUMN = () => {
        this.displayColCustom();
    }

    encrypt_column = () => {
        this.displayColCustom();
    }

    displayColCustom = () => {
        const {
            tableStore
        } = this.mainTable;

        tableStore.setColSetVisible(true);
        tableStore.tableColSet(true);
    }

    BTN_LOG = (params={}) => {
        this.openLogView({
            ...params,
            index: '',
            id: '',
        });
    }

    BTN_TYPE_LOG = () => {
        this.openLogView({
            index: '',
            id: '',
        });
    }


    //*************************MainTab*******************************
    @observable mainTab = {
        key: '0',
        isPanelShow: false,
        conditionCount: 2,
        form: new WeaForm(),
        condition: [],
    }

    get mTdatas() {
        let tabs = [];
        // ['0', '1', '2'].map((v, i) => {
        //     tabs.push({
        //         key: v,
        //         title: (i == 0) ? getLabel(20961, "集成登录设置") : (i == 1) ? getLabel(125409, "加密算法设置") : getLabel('504666','集成登录分类') 
        //     });
        // });
        ['0', '1'].map((v, i) => {
            tabs.push({
                key: v,
                title: (i == 0) ? getLabel(20961, "集成登录设置") : (i == 1) ? getLabel(125409, "加密算法设置") : ''
            });
        });
        return tabs
    }

    get buttonsAd() {
        const {
            form
        } = this.mainTab;

        let buttonsAd = [];
        [0, 1, 2].map((v, index) => {
            const func = (v == 0) ? 'search' : 'changePanelStatus';
            const name = (v == 0) ? getLabel(82529, '搜索') : (v == 1) ? getLabel(27088, '重置') : getLabel(32694, '取消');
            buttonsAd.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@iy2at5@${v}`} type={v == 0 ? "primary" : ''} onClick={() => {
                v == 1 ? form.reset() : this[func]()
            }}>{name}</Button>);
        });

        return buttonsAd;
    }

    get searchsAd() {
        const {
            form,
            condition
        } = this.mainTab;
        return getAdvancedItem(form, condition, this.search);
    }

    @action
    clickTab = (key) => {
        const {
            visible
        } = this.mainDialog;

        this[!visible ? 'mainTab' : 'subTab'].key = key;
        if (!visible) {
            this.getMenus();
            ['resetSearch', 'getSearchCondition', 'getList'].map((f, i) => {
                this[f](i == 0 && {
                    action: '1'
                });
            });
        }

    }

    @action
    changePanelStatus = (bool) => {
        this.mainTab.isPanelShow = bool;
    }

    @action
    search = (params={}) => {
        const {
            isPanelShow
        } = this.mainTab;
        isPanelShow && this.changePanelStatus(false);
        this.source === 'coremail' ? this.getList({
                typename: '8'
            }) :
            this.source === 'tencentmail' ? this.getList({
                typename: '6',
                ...params
            }) : this.source === 'NC' ? this.getList({
                typename: '1'
            }) : this.source === 'EAS' ? this.getList({
                typename: '2'
            }) : this.source === 'U8' ? this.getList({
                typename: '3'
            }) : this.source === 'K3' ? this.getList({
                typename: '4'
            }) : this.getList(params);
    }

    @action
    getSearchCondition = (select) => {
        let {
            key
        } = this.mainTab;
        key = select || key;
        Api[key == '0' ? 'operateSysForm' : key == '1' ? 'operateEncryptForm' : 'operateTypeForm']({
            operate: 'getAdvancedSearch'
        }).then(rs => {
            const {
                status,
                condition
            } = rs;

            if (status == '1') {
                this.mainTab.condition = condition;
                this.mainTab.form.initFormFields(condition);
            } else {
                message.error();
            }
        }).catch(error => {
            message.error();
        });
    }

    @action
    resetSearch = (params) => {
        const {
            action
        } = params;
        this.mainTab.isPanelShow = false;
        action == '1' ? this.mainTab.form = new WeaForm() : this.mainTab.form.reset();
    }


    //*************************MainTable*******************************
    @observable mainTable = {
        tableStore: new TableStore(),
        listTableStore: new TableStore(),
    }

    @action
    getList = (param={}) => {
        const {
            key,
            form,
        } = this.mainTab;
        this.mainTable.tableStore = new TableStore();
        let params = Object.assign({}, form.getFormParams(), param);
        let selectedKey = (this.source || param.typename) ? '0' : key;
        Api[selectedKey == '0' ? 'getOutterSysList' : selectedKey == '1' ? 'getOutterEncryptList' : 'getOutterTypeList']({
            ...params
        }).then(cb => {
            const {
                status,
                sessionkey,
            } = cb;
            if(params && "mail" === params.type) {
                if (cb.ret && cb.ret == "noright") {
                    this.mailTypeAuthorized = false;
                } else {
                    this.mailTypeAuthorized = true;
                }
            }
            if (cb.status == '1' && cb.sessionkey) {
                this.mainTable.tableStore.getDatas(cb.sessionkey, 1);
            }
            if(params && "mail" === params.type) {
                this.mailTypeAuthorizedLoading = false;
            }
        }).catch(error => {
        });
    }
    @observable Id
    @action onOperatesClick = (record, rowIndex, operate, mailParams = {}) => {
        const { randomFieldId, iurlspan, ourlspan, id } = record,
            { index } = operate,
            { key } = this.mainTab;
        this.Id = id
        this.setIoUrl((key == '0') ? {
            iurlspan,
            ourlspan
        } : {
            iurlspan: '',
            ourlspan: '',
        });

        this.setIsSysAlgorithm({
            isSysAlgorithm: (key == '1') ? (parseInt(randomFieldId) < 0 ? true : false) : false,
        })

        if (index == '0' || index == '2') {
            this.openDialog({
                type: index,
                id: randomFieldId,
                Id: this.Id
            });
        }
        if (index == '1') {
            this.mainTable.id = record.randomFieldId;
            this.showConfirm({
                type: '0',
                mailParams,
            })
        }
        if (index == '3') {
            this.openLogView({
                type: index,
                id: id
            });
        }
    }

    @action
    setIoUrl = (params) => {
        this.mainTable.ioUrl = params;
    }

    @action
    setIsSysAlgorithm = (params) => {
        this.mainTable.isSysAlgorithm = params.isSysAlgorithm;
    }

    showConfirm = (params) => {
        const {
            type,
            typename,
            mailParams={},
        } = params;

        let _this = this;
        confirm({
            title: getLabel(131329, '信息确认'),
            content: (['1', '3'].includes(type)) ? getLabel(385625, '确定要删除选择的记录吗？') : getLabel(83877, '确定要删除吗？'),
            okText: getLabel(33703, '确定'),
            cancelText: getLabel(32694, '取消'),
            onOk() {
                _this.onOk(type, {typename, ...mailParams})
            },
            onCancel() {
                return false
            },
        });
    }

    onOk = (type, params={}) => {
        (type == '3') ? this.delShare() : this.del(type, params);
    }

    del = (type, params={}) => {
        const {
            key
        } = this.mainTab, {
            id,
            tableStore
        } = this.mainTable;
        let selectedKey = params.typename ? '0' : key;

        Api[selectedKey == '0' ? 'operateSysForm' : selectedKey == '1' ? 'operateEncryptForm' : 'operateTypeForm']({
            operate: 'delete',
            [selectedKey == '0' ? 'sysid' : selectedKey == 1 ? 'id' : 'outterTypeid']: (type == '1') ? tableStore.selectedRowKeys.toString() : id,
        }).then(rs => {
            const {
                status,
                msg
            } = rs;

            if (status == '1') {
                if (msg && msg != 'success') {
                    message.warning(msg);
                } else {
                    message.success(getLabel(83472, '删除成功！'));
                }
                this.getListNum({typename: 6});
                this.source === 'coremail' ? this.getList({
                    typename: '8'
                }) : this.source === 'tencentmail' ? this.getList({
                    typename: '6'
                }) : this.source === 'NC' ? this.getList({
                    typename: '1'
                }) : this.source === 'EAS' ? this.getList({
                    typename: '2'
                }) : this.source === 'U8' ? this.getList({
                    typename: '3'
                }) : this.source === 'K3' ? this.getList({
                    typename: '4'
                }) : this.getList(params);
            }
        }).catch(error => {
            message.error();
        });
    }

    //*************************MainDialog*******************************
    @observable mainDialog = {
        visible: false,
        title: '',
    };

    getDialogFooter = (mailParams={}) => {
        const {
            type
        } = this.mainDialog, {
            key
        } = this.mainTab, {
            isSysAlgorithm
        } = this.mainTable;

        let buttons = [],
            dropMenuDatas = [];

        if (['BTN_NEW', '0', 'encrypt_new', 'BTN_TYPE_NEW'].includes(type)) {
            const loading = (key == '0') ? this.loginForm.loading : (key == '1') ? this.algorithmForm.loading : this.typeForm.loading;
            let params;
            if (key == '0') {
                params = {
                    ob: 'loginForm',
                    operate: 'saveLoginSet',
                    hide: 'hideloginField',
                }
            } else if (key == '1') {
                params = {
                    ob: 'algorithmForm',
                    operate: 'saveAlgorithmSet',
                    hide: 'hideAlgorithmField',
                }
            } else if (key == '2') {
                params = {
                    ob: 'typeForm',
                    operate: 'saveTypeSet',
                }
            }

            key != 2 ? Object.assign(params, {
                ishide: true
            }) : Object.assign(params, {
                ishide: false
            });

            if (this.subTab.key != '1') {
                buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rre0b7@integrationOutterButtonSaveBtn`} type="primary" disabled={loading}
                                     onClick={() => this.saveAndTest(params, mailParams)}>{getLabel(30986, '保存')}</Button>);
                dropMenuDatas.push({
                    key: '0',
                    icon: <i className='icon-coms-Preservation'/>,
                    content: getLabel(30986, '保存'),
                    disabled: loading,
                    onClick: () => this.saveAndTest(params, mailParams),
                })
            }
        }
        if (['0', '2'].includes(type) && key != '2') {
            let loading, params;
            if (type == '0') {
                loading = (key == '0') ? this.loginForm.loading : this.algorithmForm.loading;
                params = {
                    type: '2',
                    id: this.mainTable.id
                }
            } else {
                loading = (key == '0') ? this.loginTestForm.loading : this.algorithmTestForm.loading;

                if (key == '0') {
                    params = {
                        ob: 'loginTestForm',
                        operate: 'testLogin'
                    }
                } else {
                    params = {
                        ob: 'algorithmTestForm',
                        operate: 'testAlgorithm'
                    }
                }
            }

            Object.assign(params, {
                ishide: false
            });

            if (this.subTab.key != '1' && !isSysAlgorithm) {

                if (type=='0') {
                    buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pav0bi@integrationOutterButtonTest${type}Btn`} type="primary" disabled={loading}
                                         onClick={() => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)}>{getLabel(25496, '测试')}</Button>)

                    dropMenuDatas.push({
                        key: '1',
                        icon: <i className='icon-coms-currency-Task'/>,
                        content: getLabel(25496, '测试'),
                        disabled: loading,
                        onClick: () => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)
                    })
                }else {
                    if(key != 1) {
                        buttons.push(
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@g0dczs@integrationOutterButtonPreShow${type}${key}Btn`} type="primary" disabled={loading}
                              onClick={() =>this.saveAndTest({
                                ob: 'loginTestForm',
                                operate: 'testPreviewUrl',
                              })}>{getLabel(221, '预览')}</Button>
                       )
                    }
                    buttons.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yalbyy@integrationOutterButtonTest${type}${key}Btn`} type="primary" disabled={loading}
                                         onClick={() => (type == '0') ? this.openDialog(params) : this.saveAndTest(params, mailParams)}>{getLabel(25496, '测试')}</Button>);
                    
                    if(key != 1) {
                        dropMenuDatas.push({
                            key: '2',
                            icon: <i className='icon-coms-currency-Task'/>,
                            content: getLabel(221, '预览'),
                            disabled: loading,
                            onClick: () => this.saveAndTest({
                                ob: 'loginTestForm',
                                operate: 'testPreviewUrl',
                            })
                        })
                    }
                    dropMenuDatas.push({
                        key: '1',
                        icon: <i className='icon-coms-currency-Task'/>,
                        content: getLabel(25496, '测试'),
                        disabled: loading,
                        onClick: () => (type == '0') ? this.openDialog(params) : this.saveAndTest(params, mailParams)
                    });
                }

            }
        }

        return {
            buttons,
            dropMenuDatas,
        };
    }

    get mMenus() {
        const {
            type
        } = this.mainDialog, {
            key
        } = this.mainTab, {
            isSysAlgorithm
        } = this.mainTable;

        let buttons = [],
            dropMenuDatas = [];

        if (['BTN_NEW', '0', 'encrypt_new', 'BTN_TYPE_NEW'].includes(type)) {
            const loading = (key == '0') ? this.loginForm.loading : (key == '1') ? this.algorithmForm.loading : this.typeForm.loading;
            let params;
            if (key == '0') {
                params = {
                    ob: 'loginForm',
                    operate: 'saveLoginSet',
                    hide: 'hideloginField',
                }
            } else if (key == '1') {
                params = {
                    ob: 'algorithmForm',
                    operate: 'saveAlgorithmSet',
                    hide: 'hideAlgorithmField',
                }
            } else if (key == '2') {
                params = {
                    ob: 'typeForm',
                    operate: 'saveTypeSet',
                }
            }

            key != 2 ? Object.assign(params, {
                ishide: true
            }) : Object.assign(params, {
                ishide: false
            });

            if (this.subTab.key != '1') {
                buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@g9yboz@integrationOutterButtonPreShow${this.subTab.key}Btn`} type="primary" disabled={loading}
                                     onClick={() => this.saveAndTest(params)}>{getLabel(30986, '保存')}</Button>);
                dropMenuDatas.push({
                    key: '0',
                    icon: <i className='icon-coms-Preservation'/>,
                    content: getLabel(30986, '保存'),
                    disabled: loading,
                    onClick: () => this.saveAndTest(params),
                })
            }
        }
        if (['0', '2'].includes(type) && key != '2') {
            let loading, params;
            if (type == '0') {
                loading = (key == '0') ? this.loginForm.loading : this.algorithmForm.loading;
                params = {
                    type: '2',
                    id: this.mainTable.id
                }
            } else {
                loading = (key == '0') ? this.loginTestForm.loading : this.algorithmTestForm.loading;

                if (key == '0') {
                    params = {
                        ob: 'loginTestForm',
                        operate: 'testLogin'
                    }
                } else {
                    params = {
                        ob: 'algorithmTestForm',
                        operate: 'testAlgorithm'
                    }
                }
            }

            Object.assign(params, {
                ishide: false
            });

            if (this.subTab.key != '1' && !isSysAlgorithm) {

                if (type=='0') {
                    buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ccdy07@integrationOutterButtonTest${type}Btn`} type="primary" disabled={loading}
                                         onClick={() => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)}>{getLabel(25496, '测试')}</Button>)

                    dropMenuDatas.push({
                        key: '1',
                        icon: <i className='icon-coms-currency-Task'/>,
                        content: getLabel(25496, '测试'),
                        disabled: loading,
                        onClick: () => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)
                    })
                }else {
                    if(key != 1) {
                        buttons.push(
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@2z1rn0@integrationOutterButtonPreShow${key}Btn`} type="primary" disabled={loading}
                              onClick={() =>this.saveAndTest({
                                ob: 'loginTestForm',
                                operate: 'testPreviewUrl',
                              })}>{getLabel(221, '预览')}</Button>
                       )
                    }
                    buttons.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@g37n7m@integrationOutterButtonTest${key}Btn`} type="primary" disabled={loading}
                                         onClick={() => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)}>{getLabel(25496, '测试')}</Button>);
                    
                    if(key != 1) {
                        dropMenuDatas.push({
                            key: '2',
                            icon: <i className='icon-coms-currency-Task'/>,
                            content: getLabel(221, '预览'),
                            disabled: loading,
                            onClick: () => this.saveAndTest({
                                ob: 'loginTestForm',
                                operate: 'testPreviewUrl',
                            })
                        })
                    }
                    dropMenuDatas.push({
                        key: '1',
                        icon: <i className='icon-coms-currency-Task'/>,
                        content: getLabel(25496, '测试'),
                        disabled: loading,
                        onClick: () => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)
                    });
                }

            }
        }

        return {
            buttons,
            dropMenuDatas,
        };
    };

    @action getmMenus = (typename="") => {
        const {
            type
        } = this.mainDialog, {
            key
        } = this.mainTab, {
            isSysAlgorithm
        } = this.mainTable;

        let buttons = [],
            dropMenuDatas = [];

        if (['BTN_NEW', '0', 'encrypt_new', 'BTN_TYPE_NEW'].includes(type)) {
            const loading = (key == '0') ? this.loginForm.loading : (key == '1') ? this.algorithmForm.loading : this.typeForm.loading;
            let params;
            if (key == '0') {
                params = {
                    ob: 'loginForm',
                    operate: 'saveLoginSet',
                    hide: 'hideloginField',
                    params: {typename}
                }
            } else if (key == '1') {
                params = {
                    ob: 'algorithmForm',
                    operate: 'saveAlgorithmSet',
                    hide: 'hideAlgorithmField',
                }
            } else if (key == '2') {
                params = {
                    ob: 'typeForm',
                    operate: 'saveTypeSet',
                }
            }

            key != 2 ? Object.assign(params, {
                ishide: true
            }) : Object.assign(params, {
                ishide: false
            });

            if (this.subTab.key != '1') {
                buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@u2jvwf@integrationOutterButtonSave${this.subTab.key}Btn`} type="primary" disabled={loading}
                                     onClick={() => this.saveAndTest(params)}>{getLabel(30986, '保存')}</Button>);
                dropMenuDatas.push({
                    key: '0',
                    icon: <i className='icon-coms-Preservation'/>,
                    content: getLabel(30986, '保存'),
                    disabled: loading,
                    onClick: () => this.saveAndTest(params),
                })
            }
        }
        if (['0', '2'].includes(type) && key != '2') {
            let loading, params;
            if (type == '0') {
                loading = (key == '0') ? this.loginForm.loading : this.algorithmForm.loading;
                params = {
                    type: '2',
                    id: this.mainTable.id
                }
            } else {
                loading = (key == '0') ? this.loginTestForm.loading : this.algorithmTestForm.loading;

                if (key == '0') {
                    params = {
                        ob: 'loginTestForm',
                        operate: 'testLogin'
                    }
                } else {
                    params = {
                        ob: 'algorithmTestForm',
                        operate: 'testAlgorithm'
                    }
                }
            }

            Object.assign(params, {
                ishide: false
            });

            if (this.subTab.key != '1' && !isSysAlgorithm) {

                if (type=='0') {
                    buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yxyxji@integrationOutterButtonSave${type}Btn`} type="primary" disabled={loading}
                                         onClick={() => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)}>{getLabel(25496, '测试')}</Button>)

                    dropMenuDatas.push({
                        key: '1',
                        icon: <i className='icon-coms-currency-Task'/>,
                        content: getLabel(25496, '测试'),
                        disabled: loading,
                        onClick: () => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)
                    })
                }else {
                    if(key != 1) {
                        buttons.push(
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@l9zzss@integrationOutterButtonSave${key}Btn`} type="primary" disabled={loading}
                              onClick={() =>this.saveAndTest({
                                ob: 'loginTestForm',
                                operate: 'testPreviewUrl',
                              })}>{getLabel(221, '预览')}</Button>
                       )
                    }
                    buttons.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ry0re2@integrationOutterButtonSave${key}Btn`} type="primary" disabled={loading}
                                         onClick={() => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)}>{getLabel(25496, '测试')}</Button>);
                    
                    if(key != 1) {
                        dropMenuDatas.push({
                            key: '2',
                            icon: <i className='icon-coms-currency-Task'/>,
                            content: getLabel(221, '预览'),
                            disabled: loading,
                            onClick: () => this.saveAndTest({
                                ob: 'loginTestForm',
                                operate: 'testPreviewUrl',
                            })
                        })
                    }
                    dropMenuDatas.push({
                        key: '1',
                        icon: <i className='icon-coms-currency-Task'/>,
                        content: getLabel(25496, '测试'),
                        disabled: loading,
                        onClick: () => (type == '0') ? this.openDialog(params) : this.saveAndTest(params)
                    });
                }

            }
        }

        return {
            buttons,
            dropMenuDatas,
        };
    }

    saveAndTest = (params, mailParams={}) => {
        const {
            ob,
            operate,
            hide,
            ishide,
        } = params;

        ishide && this[hide]();

        this[ob].form.validateForm().then(f => {
            if (f.isValid) {
                this[operate]({...(params.params || {}), ...mailParams});
            } else {
                f.showErrors();
            }
        })
    }

    get mstyle() {
        const {
            type,
        } = this.mainDialog, {
            key
        } = this.mainTab;

        let style;
        if (type == 'expression') {
            style = {
                width: 670,
                height: 480
            }
        }
        if (['BTN_NEW', '0'].includes(type) && key == '0') {
            style = {
                width: 1000,
                height: 650
            }
        }
        if (['encrypt_new', '0'].includes(type) && key == '1') {
            style = {
                width: 800,
                height: 650
            }
        }
        if (['BTN_TYPE_NEW', '0'].includes(type) && key == '2') {
            style = {
                width: 800,
                height: 650
            }
        }
        if (type == '2' && key == '1') {
            style = {
                width: 650,
                height: 650
            }
        }

        return style;
    }

    @action
    openDialog = (params) => {
        const {
            type,
            id,
            Id,
            from = ""
        } = params, {
            visible
        } = this.mainDialog, {
            key
        } = this.mainTab;
        if (type === 'BTN_NEW' || (key == "0" && type == "0")) {
            this.Id = Id;//通过点击标识拿到行数据id
        }

        // 加密算法入口区分
        if (from != "" && type === 'encrypt_new') {
            this.algorithmForm.from = "quickAdd";
        } else {
            if (type === 'encrypt_new') {
                this.algorithmForm.from = "";
            }
            this.mainTable.id = id;
        }

        let title;

        this[!visible ? 'mainDialog' : 'subDialog'].visible = true;
        this[!visible ? 'mainDialog' : 'subDialog'].type = type;
        if (type == 'BTN_NEW') {
            title = getLabel(387205, '新建集成登录设置');
        }else {
            if (key == '0' && type == '0') {
                title = getLabel(387206, '编辑集成登录设置');
            }
            if (type == 'encrypt_new') {
                title = getLabel(387207, '新建加密算法设置');
            }
            if (key == '1' && type == '0') {
                title = getLabel(387208, '编辑加密算法设置');
            }
            if (type == 'BTN_TYPE_NEW') {
                title = getLabel('504626', '新建集成登录分类');
            }
            if (key == '2' && type == '0') {
                title = getLabel('504634', '编辑集成登录分类');
            }
            if (key == '0' && type == '2') {
                title = getLabel('387419', "集成登录测试");
                this.getLoginTestForm();
            }
            if (key == '1' && type == '2') {
                title = getLabel('387420', "加密算法测试");
            }
            if (type == 'share') {
                title = getLabel(19910, '共享范围');
            }
            if (type == 'expression') {
                title = getLabel(387209, '设置表达式');
            }
        }   
        this[!visible ? 'mainDialog' : 'subDialog'].title = title;
    }

    @action
    closeDialog = () => {
        const {
            visible
        } = this.subDialog;

        this[visible ? 'subDialog' : 'mainDialog'].visible = false;
    }


    hideloginField = () => {
        const {
            typename
        } = this.loginForm;

        let temp = [];

        if (typename == '0' || typename == '2' || typename == '3' || typename == '4' || typename == '9' || typename == '10') {
            temp = ['accountcode', 'client_id', 'client_secret', 'alssosecret', 'alssokey', 'email263_domain', 'email263_cid', 'email263_key', 'email163_domain', 'email163_pubkey', 'email163_key'];
        }else if (typename == '1' || typename == '5') {
            temp = ['client_id', 'client_secret', 'alssosecret', 'alssokey', 'email263_domain', 'email263_cid', 'email263_key', 'email163_domain', 'email163_pubkey', 'email163_key'];
        }else if (typename == '6') {
            temp = ['iurl', 'ourl', 'accountcode', 'alssosecret', 'alssokey', 'email263_domain', 'email263_cid', 'email263_key', 'email163_domain', 'email163_pubkey', 'email163_key'];
        }else if (typename == '7') {
            temp = ['accountcode', 'client_id', 'client_secret', 'alssosecret', 'alssokey', 'email163_domain', 'email163_pubkey', 'email163_key'];
        }else if (typename == '8') {
            temp = ['accountcode', 'client_id', 'client_secret', 'alssosecret', 'alssokey', 'email263_domain', 'email263_cid', 'email263_key', 'email163_domain', 'email163_pubkey', 'email163_key'];
        }else if (typename == '11') {
            temp = ['accountcode', 'client_id', 'client_secret', 'alssosecret', 'alssokey', 'email263_domain', 'email263_cid', 'email263_key'];
        }else if(typename == "12") {
            temp = ['iurl', 'ourl', 'client_id', 'client_secret', 'accountcode', 'email263_domain', 'email263_cid', 'email263_key', 'email163_domain', 'email163_pubkey', 'email163_key'];
        }

        window.e9HideFormFieldKeys = temp;
    }

    @action
    getIpAddresses = () => {
        const {
            ipAddresses
        } = this.loginForm;
        const obj = {};

        ipAddresses && ipAddresses.map((address, index) => {
            const key = `sysIpAddress${index}`;
            Object.assign(obj, {
                [key]: address
            })
        });

        Object.assign(obj, {
            ipaddressLength: ipAddresses.length
        });
        return obj;
    }

    @action
    getPicParams = () => {
        const {key} = this.mainTab;
        let datas = key == 2 ? this.typeForm : this.loginForm;
        const {
            excelFileId,
            urllinkimagid,
            fileName
        } = datas;
        if (key == 2) {
            return {
                iconId: excelFileId ? excelFileId : urllinkimagid,
                filename: fileName,
            }
        } else {
            return {
                urllinkimagid: excelFileId ? excelFileId : urllinkimagid,
                filename: fileName,
            }
        }
    }

    @action
    jsonTranslation = (datas) => {
        let obj = {};

        datas && datas.map((data, index) => {
            Object.keys(data) && Object.keys(data).map(key => {
                if (key === 'id') return;
                const val = data[key];
                if (Array.isArray(val)) {
                    obj[`paramtypes_${index}`] = val[0];
                    obj[`paramvalues_${index}`] = val[1] ? val[1] : val[2];
                } else {
                    obj[`${key}_${index}`] = val;
                }
            })
        });

        Object.assign(obj, {
            datasLength: datas.length,
        });

        return obj
    }

    /**
     * @algorithmFrom  用于加密算法校验时的判断，只与加密算法相关；若值为quickAdd，则证明是从集成登录设置的自定义页面入口进入
     */
    checkTableFieldValueUnique = (params, i, algorithmFrom) => {
        Api.checkTableFieldValueUnique(params).then(cb => {
            const {
                status,
                isNotUnique,
            } = cb, {
                key
            } = this.mainTab;

            if (status == '1') {
                let checkUniqueForm = key == '1' ? 'algorithmForm' : 'typeForm',  // 用于校验的form
                  checkUniqueKey = '',    // 用于校验唯一性的key
                  checkUniqueTips = '';   // 用于校验后的提示信息

                if(key == '0') {
                    // 判断此时验证的是加密算法或是集成登录设置标识的重复判断
                    if('quickAdd' === algorithmFrom) {
                        checkUniqueForm = 'algorithmForm';
                        checkUniqueKey = 'encryptname'; 
                        checkUniqueTips = getLabel('129943', "名称已存在");
                    } else {
                        checkUniqueForm = 'loginForm';
                        checkUniqueKey = 'sysid';
                        checkUniqueTips = getLabel('387654', '标识已存在');
                    }
                }

                this[checkUniqueForm][`isNotUnique${(i !== undefined ? i : '')}`] = isNotUnique;
                if(isNotUnique) {
                    this[checkUniqueForm].form.showError(
                        [
                            key == '0' 
                              ? checkUniqueKey
                              : key == '1' 
                                ? 'encryptname' 
                                : i == 0 
                                  ? 'fullName' 
                                  : 'shortName'
                        ], 
                        (key == '0') 
                          ? checkUniqueTips 
                          : key == '1' 
                            ? getLabel('129943', "名称已存在") 
                            : i == 0 
                              ? getLabel('504643', '全称已存在') 
                              : getLabel('504645', '简称已存在')
                    )
                }
            } else {
                message.error(cb.msg);
            }
        });
    }

    checkValueUnique = (params) => {
        return Api.checkTableFieldValueUnique(params);
    }

    //*************************SubDialog*******************************
    @observable subDialog = {
        visible: false,
        title: '',
    }

    get sMenus() {
        const {
            type
        } = this.subDialog, {
            key
        } = this.mainTab;

        let buttons = [],
            dropMenuDatas = [];

        if (['encrypt_new', 'expression', 'share'].includes(type)) {
            const loading = (type != 'expression') ? this[type == 'encrypt_new' ? 'algorithmForm' : 'shareForm'].loading : false;

            let params;
            if (type == 'encrypt_new') {
                params = {
                    ob: 'algorithmForm',
                    operate: 'saveAlgorithmSet',
                    hide: 'hideAlgorithmField',
                }
            } else {
                params = {
                    ob: 'shareForm',
                    operate: 'saveShareScope',
                    hide: 'hideShareField',
                }
            }
            Object.assign(params, {
                ishide: true
            });
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pycnhh@integrationOutterButtonSave${type}Btn`} type="primary" disabled={loading} onClick={() => {
                type != 'expression' ? this.saveAndTest(params) : this.writeExpToTable()
            }}>{getLabel(30986, '保存')}</Button>)
            dropMenuDatas.push({
                key: '0',
                icon: <i className='icon-coms-Preservation'/>,
                content: getLabel(30986, '保存'),
                disabled: loading,
                onClick: () => {
                    type != 'expression' ? this.saveAndTest(params) : this.writeExpToTable()
                },
            })
        }
        if (type == '2') {
            const loading = (key == '0') ? this.loginTestForm.loading : this.algorithmTestForm.loading;

            let params;
            if (key == '0') {
                params = {
                    ob: 'loginTestForm',
                    operate: 'testLogin',
                }
            } else {
                params = {
                    ob: 'algorithmTestForm',
                    operate: 'testAlgorithm',
                }
            }
            Object.assign(params, {
                ishide: false
            });
            key == '0'?buttons.push(
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@0h5cr5@integrationOutterButtonPreShow${key}Btn`} type="primary" disabled={loading}
                                onClick={() =>this.saveAndTest({ob: 'loginTestForm', operate: 'testPreviewUrl',})}>{getLabel(221, '预览')}
                        </Button>,
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@t67msv@integrationOutterButtonTest${key}Btn`} type="primary" disabled={loading}
                                onClick={() => this.saveAndTest(params)}>{getLabel(25496, '测试')}</Button>):
                buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rk1fde@integrationOutterButtonTest${key}Btn`} type="primary" disabled={loading}
                            onClick={() => this.saveAndTest(params)}>{getLabel(25496, '测试')}</Button>);
            if (key == '0') {//登录测试，不等于0：加密算法测试
                dropMenuDatas.push({
                    key: '2',
                    icon: <i className='icon-coms-currency-Task'/>,
                    content: getLabel(221, '预览'),
                    disabled: loading,
                    onClick: () => this.saveAndTest({
                        ob: 'loginTestForm',
                        operate: 'testPreviewUrl',
                    })
                });
            }
            dropMenuDatas.push({
                key: '1',
                icon: <i className='icon-coms-currency-Task'/>,
                content: getLabel(25496, '测试'),
                disabled: loading,
                onClick: () => this.saveAndTest(params)
            });
           
        }

        return {
            buttons,
            dropMenuDatas
        };
    }


    get sStyle() {
        const {
            type
        } = this.subDialog, {
            key
        } = this.mainTab;

        let style;
        if (type == 'expression') {
            style = {
                width: 670,
                height: 480
            }
        }
        if (type == 'encrypt_new') {
            style = {
                width: 800,
                height: 650
            }
        }
        if (type == 'share') {
            style = {
                width: 670,
                height: 350
            }
        }
        if (type == '2' && key == '1') {
            style = {
                width: 650,
                height: 650
            }
        }
        return style;
    }

    //*************************LogView*******************************
    @observable logView = {
        logStore: new LogStore(),
        visible: false,
    }

    @action
    openLogView = (params) => {
        const {
            id,
            typename=""
        } = params;

        this.mainTable.id = id;
        this.logView.visible = true;
        this.logView.params={typename};
    }

    @action
    closeLogView = () => {
        this.logView.visible = false;
    }


    //*************************LoginForm*******************************
    @observable loginForm = {
        encryptClassOptions: [],
        condition: [],
        form: new WeaForm(),
        loading: true,
        typename: '',
        fields: [],
        algorithms: [],
        accountParameter: [],
        automaticLogin: [],
        passwordParameter: [],
        requestType: [],
        ipAddresses: [],
        isneedpwd: '0',
        isneediv: '0',
        urllinkimagid: '',
        date: '',
        autologin: '',
        requesttype: '',
        encrypttype: '',
        urlparaencrypt1: '',
        urlparaencrypt2: '',
        ipaddress: '',
    }

    @action
    getDefaultEntranceUrl = (params={}) => {
        Api.getDefaultEntranceUrl().then(cb => {
            const {
                status,
                defaultEntranceUrl,
            } = cb;

            if (status == '1') {
                this.getListNum({typename: '6'}, () => {
                    this.loginForm.defaultEntranceUrl = defaultEntranceUrl;
                    this.getLoginForm(params);
                });
                
            } else {
                message.error(cb.message);
            }
        }).catch(error => {
            message.error(error);
        });
    }

    @action
    getLoginForm = (params={}) => {
        const {
            id,
            listTableStore
        } = this.mainTable, {
            type
        } = this.mainDialog;
        params = Object.assign({}, params, {operate: 'getForm', id: type != 'BTN_NEW' ? id : ''});

        Api.operateSysForm(params).then(rs => {
            const {
                status,
                paramList,
            } = rs;

            if (status == '1') {
                ['condition', 'ipaddress', 'urllinkimagid'].map((v, i) => {
                    if (i == 0) {
                        const c = rs[v].slice(0, 1);
                        // 获取加密的自定义下拉框
                        c && c.forEach(data => {
                          data && data.items && data.items.forEach(item => {
                            if(item.domkey[0] === "encryptclassId") {
                              this.loginForm.encryptClassOptions = item.options;
                            }
                          })
                        })

                        if (this.source === 'tencentmail') {
                            c[0].items[0].options && c[0].items[0].options.forEach((v, index) => {
                                if(v.key == 0) {
                                   c[0].items[0].options[index].selected = false;
                                }else if(v.key == 6) {
                                   c[0].items[0].options[index].selected = true;
                                }
                            })
                            c[0].items[0].otherParams.viewAttr = 1;
                        } else if (this.source === 'coremail') {
                            c[0].items[0].options && c[0].items[0].options.filter(option => option.key == 0) && (c[0].items[0].options.filter(option => option.key == 0)[0].selected = false);
                            c[0].items[0].options && c[0].items[0].options.filter(option => option.key == 8) && (c[0].items[0].options.filter(option => option.key == 8)[0].selected = true);
                            c[0].items[0].otherParams.viewAttr = 1;
                        } else if (this.source === 'NC') {
                            let opts = [];
                            opts.push(c[0].items[0].options[1]);
                            opts.push(c[0].items[0].options[5]);
                            c[0].items[0].options = opts;
                            // c[0].items[0].otherParams.viewAttr = 1;
                        } else if (this.source === 'EAS') {
                            c[0].items[0].options && c[0].items[0].options.filter(option => option.key == 0) && (c[0].items[0].options.filter(option => option.key == 0)[0].selected = false);
                            c[0].items[0].options && c[0].items[0].options.filter(option => option.key == 2) && (c[0].items[0].options.filter(option => option.key == 2)[0].selected = true);
                            c[0].items[0].otherParams.viewAttr = 1;
                        } else if (this.source === 'U8') {
                            c[0].items[0].options && c[0].items[0].options.filter(option => option.key == 0) && (c[0].items[0].options.filter(option => option.key == 0)[0].selected = false);
                            c[0].items[0].options && c[0].items[0].options.filter(option => option.key == 3) && (c[0].items[0].options.filter(option => option.key == 3)[0].selected = true);
                            c[0].items[0].otherParams.viewAttr = 1;
                        } else if (this.source === 'K3') {
                            c[0].items[0].options && c[0].items[0].options.filter(option => option.key == 0) && (c[0].items[0].options.filter(option => option.key == 0)[0].selected = false);
                            c[0].items[0].options && c[0].items[0].options.filter(option => option.key == 4) && (c[0].items[0].options.filter(option => option.key == 4)[0].selected = true);
                            c[0].items[0].otherParams.viewAttr = 1;
                        }

                        let listDatasNum = toJS(listTableStore).datas;
                        if (listDatasNum.length > 0 && type == 'BTN_NEW') {
                            let index = -1;
                            index = c[0].items[0].options && c[0].items[0].options.findIndex(option => option.key == 6);
                            if (index != -1) {
                                c[0].items[0].options.splice(index, 1);
                            }
                        }
                        this.handleCondition({
                            condition: c,
                            func: 'handlelfCondition'
                        });
                        this.loginForm[v] = c;
                        this.loginForm.form.initFormFields(c);
                        this.extractDefaultValues({
                            condition: c,
                            func: 'exportlfSelectedValue'
                        });
                    } else {
                        this.loginForm[v == 'ipaddress' ? 'ipAddresses' : v] = rs[v];
                    }
                });
                this.tableEdit.datas = paramList;
                this.toCells(paramList);
                this.loginForm.loading = false;
            }
        }).catch(error => {
            message.error();
        });
    }

    @action
    handleCondition = (params) => {
        const {
            condition,
            func
        } = params;

        condition && condition[0] && condition[0].items && condition[0].items.map(item => {
            const key = item.domkey[0];
            this[func]({
                key,
                item,
            })
        });
    }

    @action
    handlelfCondition = (params) => {
        const {
            key,
            item,
        } = params;
        let selectedKey = this.mainTab.key;

        if (selectedKey == 2) {
            // 分类
            if (["iconWidth", "iconHeight"].includes(key)) {
                this.typeForm.fields.push(item);
            }
        } else {
            if (['imagewidth', 'imageheight'].includes(key)) {
                this.loginForm.fields.push(item)
            }
            if (['encrypttype', 'encryptclassId', 'result'].includes(key)) {
                this.loginForm.algorithms.push(item)
            }
            if (['baseparam1', 'basetype1', 'urlparaencrypt1', 'encryptcode1', 'encryptiv1'].includes(key)) {
                this.loginForm.accountParameter.push(item)
            }
            if (['autologin', 'ipaddress'].includes(key)) {
                this.loginForm.automaticLogin.push(item)
            }
            if (['baseparam2', 'basetype2', 'urlparaencrypt2', 'encryptcode2', 'encryptiv2'].includes(key)) {
                this.loginForm.passwordParameter.push(item)
            }
            if (['requesttype', 'urlencodeflag'].includes(key)) {
                this.loginForm.requestType.push(item)
            }
        }
    }

    @action
    extractDefaultValues = (params) => {
        const {
            condition,
            func,
        } = params;

        condition && condition[0] && condition[0].items && condition[0].items.map(item => {
            let t;
            if (item.value) {
                t = item.value;
            } else {
                if (item.options) {
                    const option = item.options.find(option => option.selected === true);
                    t = option ? option.key : '0';
                } else {
                    t = '';
                }
            }

            this[func]({
                val: t,
                key: item.domkey[0]
            });
        });
    }

    @action("根据邮箱标识填充数据")
    getMailSysCodeData = (params={}) => {
      Api.operateSysForm({operate: "getMailDetailMessage", ...params}).then(result => {
        if(result.status == 1) {
          delete result.status;
          this.loginForm.form.updateFields({...result});
        }
      })
    }

    @action
    getMailCode = (params={}) => {
      Api.operateSysForm({operate: "getMailSelect", ...params, id: this.mainTable.id}).then(result => {
        if(result.status == 1) {
          this.mailOutterSelect = result.mailOutterSelect || [];
        }
      })
    }

    @action
    exportlfSelectedValue = (params) => {
        const {
            val,
            key
        } = params, {
            type
        } = this.mainDialog;

        this.loginForm[key] = val;

        if (key == 'typename') {
            if(type == 'BTN_NEW') {
                this.setDefaultEntranceUrl({
                    val
                })
                this.setDefaultParams({
                    val
                });
                this.setDefaultViewAttr({
                    val
                });    
                let index = this.tableEdit.datas.findIndex(v => v.paramnames === 'pkcorp');
                if (index === 0) {
                    this.tableEdit.datas.splice(0, 1);
                }
                let index00 = this.tableEdit.datas.findIndex(v => v.paramnames === 'k3server');
                if (index00 === 0) {
                    this.tableEdit.datas.splice(0, 5);
                }
                let index01 = this.tableEdit.datas.findIndex(v => v.paramnames === 'dbid');
                if (index01 === 1) {
                    this.tableEdit.datas.splice(1, 6);
                }
    
                if (['1', '5'].includes(val)) {
                    this.tableEdit.datas.unshift({
                        id: uuid(),
                        cascader: ['0', 'pkcorp'],
                        paramnames: 'pkcorp',
                        labelnames: getLabel('1976', '公司名称')
                    })
                }
    
                if (['9', '10'].includes(val)) {
                    this.tableEdit.datas.unshift({
                        id: uuid(),
                        cascader: ['0', ''],
                        paramnames: 'lcid',
                        labelnames: getLabel('16066', '系统语言')
                    })
                    this.tableEdit.datas.unshift({
                        id: uuid(),
                        cascader: ['0', ''],
                        paramnames: 'appsecret',
                        labelnames: getLabel('508213', '第三方系统应用秘钥')
                    })
                    this.tableEdit.datas.unshift({
                        id: uuid(),
                        cascader: ['0', ''],
                        paramnames: 'appid',
                        labelnames: getLabel('508214', '第三方系统应用id')
                    })
                    this.tableEdit.datas.unshift({
                        id: uuid(),
                        cascader: ['0', ''],
                        paramnames: 'dbid',
                        labelnames: getLabel('508215', '数据中心id')
                    })
                    this.tableEdit.datas.unshift({
                        id: uuid(),
                        cascader: ['0', ''],
                        paramnames: 'k3server',
                        labelnames: getLabel('508212', 'k3服务地址')
                    })
                }
            }
            // 编辑和新建的时候都通过前端塞入下拉框选项值
            this.getMailCode({
                typename: val 
            });
        }

        if (key === "mailsyscode") {
            this.getMailSysCodeData({mailsyscode: val});
        }

        (key == 'encrypttype' && val != '2') && this.getOutterSysIsNeedPwdAndIv();

        ((key == 'encrypttype' && val == '2') || (key == 'encryptclassId' && this.loginForm.encrypttype == '2')) && this.getCustomEncryptClass();
    }

    @action
    setDefaultEntranceUrl = (params) => {
        const {
            defaultEntranceUrl,
            form
        } = this.loginForm, {
            val
        } = params;

        defaultEntranceUrl && defaultEntranceUrl.map(url => {
            if (url.id == val) {
                form.updateFields({
                    entranceurl: url.value
                })
            }
        });
    }

    //设置默认值
    @action
    setDefaultParams = (params) => {
        const {
            val
        } = params;

        let s1, s2;
        if (val === '0' || val == '6') {
            s1 = '';
            s2 = '';
        }else if(val == '1') {
            s1 = 'usercode';
            s2 = 'pwd';
        }else if(val == '5') {
            s1 = 'userCode';
            s2 = '';
        }else if (val == '7') {
            s1 = 'uid';
            s2 = '';
        } else if (val == '8') {
            s1 = '';
            s2 = 'password';
        } else if (val == '11') {
            s1 = 'account_name';
            s2 = '';
        } else if(val == '9') {
            s1 = 'username';
            s2 = '';
        }else if(val == '10') {
            s1 = 'username';
            s2 = '';
        }else if(val == '2') {
            s1 = 'username';
            s2 = '';
        }else  {
            s1 = 'username';
            s2 = 'password';
        }

        this.loginForm.form.updateFields({
            baseparam1: s1,
            baseparam2: s2,
        })
    };

    //设置默认属性
    @action
    setDefaultViewAttr = (params) => {
        const {val} = params;

        if (val === '0') {
            this.status.isRequestTypeEdit = true;
        }else {
            this.status.isRequestTypeEdit = false;
        }
    };

    @action
    getOutterSysIsNeedPwdAndIv = () => {
        Api.getOutterSysIsNeedPwdAndIv({
            id: this.loginForm.encrypttype
        }).then(cb => {
            const {
                status,
                isneedpwd,
                isneediv,
            } = cb;

            if (status == '1') {
                ['isneedpwd', 'isneediv'].map(v => {
                    const target = cb[v].find(item => item.id == this.loginForm.encrypttype);
                    this.loginForm[v] = target ? target.value : target;
                });
            } else {
                message.error();
            }
        });
    }

    @action
    getCustomEncryptClass = () => {
        Api.getCustomEncryptClass({
            id: this.loginForm.encryptclassId
        }).then(cb => {
            const {
                status,
            } = cb;

            if (status == '1') {
                ['isneedpwd', 'isneediv'].map(v => {
                    this.loginForm[v] = cb[v];
                });
            } else {
                message.error();
            }
        });
    }

    saveLoginSet = (params={}) => {
        const {
            ref,
            datas
        } = this.tableEdit, {
            isneedpwd,
            isneediv,
            form,
            isNotUnique,
        } = this.loginForm;    

        if (isNotUnique) {
            this.checkTableFieldValueUnique({
                tableName: 'outter_sys',
                fieldName: 'sysid',
                fieldValue: form.getFormParams().sysid,
            })
            return
        }

        if (ref && !ref.doValidate().pass) {
            return
        }

        let formParams = this.loginForm.form.getFormParams();
        formParams.showorder = (typeof(formParams.showorder) === "object" 
            ? formParams.showorder.join && formParams.showorder.join(",")
            ? formParams.showorder 
            : "0"
            : formParams.showorder);

        Api.operateSysForm({
            operate: 'save',
            id: this.Id,
            isneedpwd,
            isneediv,
            ...formParams,
            ...this.jsonTranslation(toJS(datas)),
            ...this.getIpAddresses(),
            ...this.getPicParams(),
        }).then(cb => {
            const {
                status,
                msg,
            } = cb;

            if (status == '1') {
                if (msg != 'success') {
                    message.warning(msg);
                    return
                }


                message.success(getLabel(22619, '保存成功'));
                this.getListNum({typename: 6});
                this.source === 'tencentmail' ? this.getList({
                        typename: '6'
                    }) :
                    this.source === 'coremail' ? this.getList({
                        typename: '8'
                    }) : this.source === 'NC' ? this.getList({
                        typename: '1'
                    }) : this.source === 'EAS' ? this.getList({
                        typename: '2'
                    }) : this.source === 'U8' ? this.getList({
                        typename: '3'
                    }) : this.source === 'K3' ? this.getList({
                        typename: '4'
                    }) : this.getList(params);
                this.closeDialog();
            } else {
                message.warning(getLabel(22620, '保存失败'));
            }
        });
    }

    //测试登录-参数 operate: 'test'
    testLogin = () => {
        const {
            form
        } = this.loginTestForm;
        let formParams = form.getFormParams();
        let keys = Object.keys(formParams) || [];

        // QC1088048
        if(keys && keys.length && keys.indexOf('id') != -1) {
            formParams = Object.assign({}, formParams, {sysid___: this.mainTable.id});
        } else {
            formParams = Object.assign({}, formParams, {id: this.mainTable.id});
        }

        Api.operateSysForm({
            operate: 'test',
            ...formParams,
        }).then(cb => {
            const {
                status,
                otherPageUrlString,
                actionStr,
            } = cb;

            if (status == '1') {
                //打开jsp地址，进行解析
                //alert(`${actionStr}?otherPageUrlString=${Base64.encode(`${otherPageUrlString}`)}&operationType=test&${otherPageUrlString}`)
                window.open(`${actionStr}?otherPageUrlString=${Base64.encode(`${otherPageUrlString}`)}&operationType=test&${otherPageUrlString}`);
            } else {
                message.error();
            }
        });
    }

    //测试预览
    testPreviewUrl = () =>{
        const { form } = this.loginTestForm;
        let result ='',params='';
        let formParams = form.getFormParams();
        let keys = Object.keys(formParams) || [];

        // QC1088048
        if(keys && keys.length && keys.indexOf('id') != -1) {
            formParams = Object.assign({}, formParams, {sysid___: this.mainTable.id});
        } else {
            formParams = Object.assign({}, formParams, {id: this.mainTable.id});
        }

        Api.getPreviewUrl({
            operate: 'test',
            ...formParams,
        }).then(cb => {
            const {
                isError,
                errorMsg,
                isRedirect,
                redirectUrl,
                paramValues,
            } = cb;
            if (isError=='true') {//发生异常
                //msg=errorMsg;
                this.status.showErrorDialog = true;//显示弹框
                this.status.errorMessage = errorMsg;
            }else {
                if (isRedirect == 'true') {
                    result=redirectUrl;
                    params=paramValues;
                }else {
                    result=redirectUrl;
                    params=paramValues;
                }
                this.status.hiddenField = false;
                form.updateFields({redirecturl:result});//设置值
                form.updateFields({parameters:params});//设置值
            }
        });
    };

    testPreviewUrl2 = (id,result,params,msg) =>{
        let obj = this;
        const { form } = this.loginTestForm;
        let p = new Promise(function(resolve, reject){
            //做一些异步操作
            Api.getPreviewUrl({
                operate: 'test',
                id: id,
                ...form.getFormParams(),
            }).then(cb => {
                const {
                    isError,
                    errorMsg,
                    isRedirect,
                    redirectUrl,
                    paramValues,
                } = cb;
                if (isError=='true') {//发生异常
                    msg=errorMsg;
                    obj.status.showErrorDialog = true;//显示弹框
                    obj.status.errorMessage = msg;
                }else {
                    if (isRedirect == 'true') {
                        result=redirectUrl;
                        params=paramValues;
                    }else {
                        result=redirectUrl;
                        params=paramValues;
                    }
                    obj.result=result;
                    form.updateFields({redirecturl:result});//设置值
                    form.updateFields({parameters:params});//设置值
                }

            });
        }).then(function(data){

        });
    };

    @action
    delPic = () => {
        const {key} = this.mainTab;
        let params = key == 2 ? {
            operate: 'delpic',
            outterTypeid: this.mainTable.id,
        } : {
            operate: 'delpic',
            sysid: this.loginForm.sysid,
        }
        Api[key == 2 ? 'operateTypeForm' : 'operateSysForm'](params).then(cb => {
            const {
                status,
                msg
            } = cb;

            if (status == '1') {
                if (msg != 'success') {
                    message.warning(msg);
                    return;
                }
                message.success(getLabel(83472, '删除成功！'));
                key == 2 ? (this.typeForm.urllinkimagid = '') : (this.loginForm.urllinkimagid = '');
            } else {
                message.warning(msg)
            }
        }).catch(error => {
            message.error(error);
        });
    }

    @action
    addIpAddress = (ipaddress) => {
        this.loginForm.ipAddresses.push(ipaddress);
    }

    @action
    deleteIpAddress = (index) => {
        this.loginForm.ipAddresses.splice(index, 1);
    }

    @action
    exportExcelFileId = (id, filename) => {
        const {key} = this.mainTab;
        if (key == 2) {
            this.typeForm.excelFileId = id;
            this.typeForm.fileName = filename;
        } else {
            this.loginForm.excelFileId = id;
            this.loginForm.fileName = filename;
        }
    }

    @action
    refreshLoginForm = () => {
        this.loginForm.form = new WeaForm();
        this.loginForm.loading = true;
        ['condition', 'fields', 'algorithms', 'accountParameter', 'automaticLogin', 'passwordParameter', 'requestType'].map(v => {
            this.loginForm[v] = [];
        });
        ['filename', 'excelFileId', 'urllinkimagid'].map(v => {
            this.loginForm[v] = '';
        });
    }

    //*************************TableEdit*******************************
    @observable tableEdit = {
        datas: [],
        cells: [],
    }

    @action
    setRef = (ref) => {
        this.tableEdit.ref = ref;
    }

    locateRowIndex = (index) => {
        this.tableEdit.index = index;
        this.bring();
    }

    @action
    bring = () => {
        const {
            datas,
            index
        } = this.tableEdit;

        this.expression.txtAreaValue = datas[index].cascader && datas[index].cascader[2];
    }

    @action
    exportTableEditDatas = (datas) => {
        this.tableEdit.datas = datas;
        this.toCells(datas);
    }

    verifyOtherParam = (value) => {
        const {
            datas
        } = this.tableEdit;

        let b = 0;
        datas && datas.map(d => {
            if (d.paramnames && d.paramnames.trim() === value) {
                b++;
            }
        });
        return (b == 1) ? true : false
    }

    willAdd = (datas, addData) => {
        const formParams = this.loginForm.form.getFormParams();
        this.toCells(datas);

        return datas;
    }

    toCells = (datas) => {
        datas && datas.map((data, index) => {
            const {
                paraencrypts,
                id,
                cascader,
            } = data;

            cascader && this.changeCells(cascader[0] == '5' ? this.hideSwitch({
                id,
            }) : this.showSwitch({
                id,
            }), index)

            if (!paraencrypts || paraencrypts == '0') {
                this.changeCells(this.handleCodesIvs({
                    id,
                    value: '0'
                }), index)
            }
        });

    }

    hideSwitch = (params) => {
        const {
            id,
        } = params;

        return {
            id,
            paraencrypts: {
                com: [{
                    type: 'TEXT',
                    key: 'paraencrypts',
                }],
            },
        }
    }

    showSwitch = (params) => {
        const {
            id,
        } = params;

        return {
            id,
            paraencrypts: {
                com: [{
                    type: 'SWITCH',
                    key: 'paraencrypts',
                }]
            },
        }
    }

    willEdit = (datas, result) => {
        const formParams = this.loginForm.form.getFormParams();
        const {
            key,
            record,
            value,
        } = result;

        if (key === 'paraencrypts') {
            return datas.map((data, index) => {
                if (data.id === record.id) {
                    this.changeCells(this.handleCodesIvs({
                        id: record.id,
                        value
                    }), index)
                    return (value == '0') ? this.changeData(data) : data;
                }
                return data;
            });
        }
        return datas;
    }

    handleCodesIvs = (params) => {
        const {
            id,
            value
        } = params;

        return {
            id,
            encryptcodes: {
                com: [{
                    type: value === '1' ? 'INPUT' : 'TEXT',
                    key: 'encryptcodes',
                    otherParams: value === '1' && {
                        type: 'password'
                    },
                }],

            },
            encryptivs: {
                com: [{
                    type: value === '1' ? 'INPUT' : 'TEXT',
                    key: 'encryptivs',
                    otherParams: value === '1' && {
                        type: 'password'
                    },
                }],
            }
        }
    }

    @action
    changeData = (data) => {
        ['encryptcodes', 'encryptivs'].map(v => {
            data[v] = '';
        });

        return data;
    }

    @action
    changeCells = (cell, index) => {
        const {
            cells
        } = this.tableEdit;

        if (cells.every(cl => cell.id != cl.id)) {
            this.tableEdit.cells.push(cell)
        } else {
            const t = cells.findIndex(cl => cell.id == cl.id)
            this.tableEdit.cells[t] = Object.assign(cells[t], cell);
        }
    }

    @action
    resetTableEdit = () => {
        ['datas', 'cells'].map(v => {
            this.tableEdit[v] = [];
        });
    }


    //*************************SubTab*******************************
    @observable subTab = {
        key: '0',

    }

    get sTdatas() {
        let temp = [];
        ['0', '1'].map((v, i) => {
            temp.push({
                key: v,
                title: (i == 0) ? getLabel(16484, '基础设置') : getLabel(19910, '共享范围')
            });
        });
        return temp
    }

    get sTbuttons() {
        return [
            <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@m5b20k@integrationOutterButtonShareBtn`} buttonType='add' type="primary"
                           onClick={() => this.openDialog({type: 'share', id: this.mainTable.id})}/>,
            <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@e7g4gd@integrationOutterButton3Btn`} buttonType='del' type="primary" disabled={this.subTable.selectedRowKeys == 0}
                           onClick={() => this.showConfirm({type: '3'})}/>
        ]
    }


    @action
    resetSubTab = () => {
        this.subTab.key = '0';
    }


    //*************************SubTable*******************************
    @observable subTable = {
        datas: [],
        loading: true,
        selectedRowKeys: [],
    }

    @action
    getShareList = () => {
        Api.operateShareForm({
            operate: 'getShare',
            sysid: this.mainTable.id,
        }).then(cb => {
            const {
                status,
                shareResult,
            } = cb;

            if (status == '1') {
                this.subTable.datas = shareResult;
                this.subTable.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error(error);
        });
    }

    @action
    refreshShareList = () => {
        ['datas', 'loading'].map((v, i) => {
            this.subTable[v] = (v == 0) ? [] : false;
        });
    }

    @action
    setSelectedRowKeys = (selectedRowKeys) => {
        this.subTable.selectedRowKeys = selectedRowKeys;
    }

    @action
    delShare = () => {
        Api.operateShareForm({
            operate: 'delShare',
            sysid: this.mainTable.id,
            id: this.subTable.selectedRowKeys.toString(),
        }).then(cb => {
            const {
                status,
                shareResult,
            } = cb;

            if (status == '1') {
                if (shareResult && shareResult != 'success') {
                    message.warning(msg);
                    return
                }
                message.success(getLabel(83472, '删除成功！'));
                this.getShareList();
            } else {
                message.warning(getLabel(20462, '删除失败！'))
            }
        }).catch(error => {
            message.error(error);
        });
    }

    //*************************LoginTestForm*******************************
    @observable loginTestForm = {
        condition: [],
        form: new WeaForm(),
        loading: true,
    };

    //初始化 TestForm 数据
    @action
    getLoginTestForm = () => {
        this.loginTestForm.loading = true;
        Api.operateSysForm({
            operate: 'getTestForm',
            id: this.mainTable.id,
        }).then(cb => {
            const {
                status,
                condition,
            } = cb;

            if (status == '1') {
                this.loginTestForm.form.initFormFields(condition); 
                this.loginTestForm.condition = condition;
		this.loginTestForm.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error(error);
        });
    };

    @action
    resetLoginTestForm = () => {
        this.loginTestForm.condition = [];
        this.loginTestForm.form = new WeaForm();
        this.loginTestForm.loading = true;
        this.status.hiddenField = true;
    }

    //*************************AlgorithmFormSetting*******************************
    @observable algorithmForm = {
        condition: [],
        form: new WeaForm(),
        loading: true,
        isSysAlgorithm: false,
        pwd: [],
        isneedpwd: '',
        iv: [],
        isneediv: '',
        from: ''   //from 值为quickAdd的时候，表示是从集成登录的弹窗中新建自定义加密算法
    }

    /**
     * 添加params是为了解决在集成登陆中新建自定义加密算法，id被覆盖的问题
     */
    @action
    getAlgorithmForm = () => {
        const {
            isSysAlgorithm
        } = this.mainTable;

        Api.operateEncryptForm({
            operate: 'getForm',
            id: this.algorithmForm.from === "quickAdd" ? "" : this.mainTable.id,
            iscustom: !isSysAlgorithm,
        }).then(cb => {
            const {
                status,
                condition,
            } = cb;

            if (status == '1') {
                !isSysAlgorithm && this.handleCondition({
                    condition,
                    func: 'handleAlgorithmCondition',
                });
                this.extractDefaultValues({
                    condition,
                    func: 'exportafsSelectedValue'
                });
                this.algorithmForm.oldencryptname = condition[0].items.find(item => item.domkey[0] == 'encryptname').value;
                this.algorithmForm.condition = condition;
                this.algorithmForm.form.initFormFields(condition);
                this.algorithmForm.loading = false;
            } else {
                message.error(cb.msg);
            }
        }).catch(error => {
            message.error(error);
        });
    }

    handleAlgorithmCondition = (params) => {
        const {
            key,
            item,
        } = params;

        if (['isneedpwd', 'password'].includes(key)) {
            this.algorithmForm.pwd.push(item)
        }
        if (['isneediv', 'ivparam'].includes(key)) {
            this.algorithmForm.iv.push(item)
        }

    }

    @action
    exportafsSelectedValue = (params) => {
        const {
            val,
            key
        } = params;

        this.algorithmForm[key] = val;
    }

    saveAlgorithmSet = () => {
        const {
            type
        } = this.mainDialog, {
            oldencryptname,
            form,
            isNotUnique0,
            isNotUnique1,
            encryptname,
            from
        } = this.algorithmForm, {
            id
        } = this.mainTable;

        if (isNotUnique0 || isNotUnique1) {
            ['outter_encryptclass_sys', 'outter_encryptclass'].forEach((v, i) => {
                this.checkTableFieldValueUnique({
                    tableName: v,
                    fieldName: 'encryptname',
                    fieldValue: encryptname,
                    idName: 'id',
                    idValue: this.algorithmForm.from ? "" : id
                }, i, this.algorithmForm.from);
            })
        } else {
            Api.operateEncryptForm({
                operate: 'save',
                id: from === "quickAdd" ? "" : ((type != 'encrypt_new') ? this.mainTable.id : ''),
                oldencryptname,
                ...form.getFormParams(),
            }).then(cb => {
                const {
                    status,
                    msg,
                    encryptClassOptions=[]
                } = cb;
    
                if (status == '1') {
                    if (msg && msg != 'success') {
                        message.warning(msg);
                        return
                    }
                    message.success(getLabel(22619, '保存成功'));
                    this.loginForm.encryptClassOptions = encryptClassOptions;
                    if(cb.encryptClassOptions.length > 0) {
                      this.loginForm.form.updateFields({encryptclassId: encryptClassOptions[encryptClassOptions.length-1].key});
                    }
                    this.getList();
                    this.closeDialog();
                } else {
                    message.warning(getLabel(22620, '保存失败'));
                }
            });
        }

    }

    getNetworkIPColumnsSet = () => {
        Api.getNetworkIPColumnsSet().then(result => {
            if (result.status == '1') {
                this.loginForm.automaticLogin[1].options = result.networkIPColumnsSet[0].com[0].options;
                this.loginForm.condition[0].items[6].options = result.networkIPColumnsSet[0].com[0].options;
                this.dialog.hide();
            }
        })
    }

    openNetworkSegmentStrategy = () => {
        this.dialog = WeaTools.createDialog({
            title: getLabel(83726, '网段策略'),
            moduleName: 'hrm',
            url: `${window.ecologyContentPath || ""}/spa/hrm/engine.html#/hrmengine/securitySetting?single=1&type=network`,
            style: {
                width: 820,
                height: 650
            },
            moreBtn: {
                collectParams: []
            },
            buttons: [],
            callback: (datas) => {
            },
            onCancel: () => {
                this.getIpAddressOptions()
            }
        });
        this.dialog.show();
    }

    @action
    getIpAddressOptions = () => {

    }

    hideAlgorithmField = () => {
        const {
            isSysAlgorithm
        } = this.mainTable, {
            isneedpwd,
            isneediv
        } = this.algorithmForm;

        window.e9HideFormFieldKeys = [];

        if (!isSysAlgorithm) {
            if (isneedpwd == '0' || !isneedpwd) window.e9HideFormFieldKeys.push('password');
            if (isneediv == '0' || !isneediv) window.e9HideFormFieldKeys.push('ivparam');
        }
    }

    @action
    resetAlgorithmForm = () => {
        ['condition', 'pwd', 'iv'].map(v => {
            this.algorithmForm[v] = [];
        });
        ['isneedpwd', 'isneediv', 'from'].map(v => {
            this.algorithmForm[v] = '';
        });
        this.algorithmForm.form = new WeaForm();
    }

    //*************************AlgorithmTestForm*******************************
    @observable algorithmTestForm = {
        condition: [],
        form: new WeaForm(),
        loading: true,
    }

    @action
    getAlgorithmTestForm = () => {
        Api.operateEncryptForm({
            operate: 'getTestForm',
            id: this.mainTable.id,
        }).then(cb => {
            const {
                status,
                condition,
                errMsg,
            } = cb;

            if (status == '1') {
                if (errMsg) {
                    message.warning(errMsg);
                }
                ['condition', 'testResult', 'errMsg'].map(v => {
                    this.algorithmTestForm[v] = cb[v];
                });
                this.algorithmTestForm.form.initFormFields(condition);
                this.algorithmTestForm.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error(error);
        });
    }

    testAlgorithm = () => {
        const {
            form,
        } = this.algorithmTestForm;

        Api.operateEncryptForm({
            operate: 'test',
            id: this.mainTable.id,
            ...form.getFormParams(),
        }).then(cb => {
            const {
                status,
                testmsg,
            } = cb, {
                decryptStr,
                encryptStr
            } = testmsg

            if (status == '1') {
                decryptStr && form.updateFields({
                    decryptSpan: decryptStr,
                });
                encryptStr && form.updateFields({
                    encryptSpan: encryptStr
                });
            } else {
                message.error();
            }
        });
    }

    @action
    resetAlgorithmTestForm = () => {
        this.algorithmTestForm.condition = [];
        this.algorithmTestForm.form = new WeaForm();
        this.algorithmTestForm.loading = true;
    }


    //*************************ShareForm*******************************
    @observable shareForm = {
        condition: [],
        form: new WeaForm(),
        loading: true,
        role: [],
        post: [],
        jobtitlelevel: '',
        permissiontype: '',
    }

    @action
    getShareForm = () => {
        Api.operateShareForm({
            operate: 'getAddShareForm',
            sysid: this.mainTable.id,
        }).then(cb => {
            const {
                status,
                condition,
            } = cb;

            if (status == '1') {
                this.handleCondition({
                    condition,
                    func: 'handleShareCondition'
                });
                this.extractDefaultValues({
                    condition,
                    func: 'exportShSelectedValue'
                });
                this.shareForm.condition = condition;
                this.shareForm.form.initFormFields(condition);
                this.shareForm.loading = false;
            } else {
                message.error();
            }
        }).catch(error => {
            message.error(error);
        });
    }

    handleShareCondition = (params) => {
        const {
            key,
            item,
        } = params;

        if (['sharevalue2', 'rolelevel'].includes(key)) {
            this.shareForm.role.push(item)
        }
        if (['jobtitlelevel', 'jobtitlesharevalue2', 'jobtitlesharevalue3'].includes(key)) {
            this.shareForm.post.push(item)
        }

    }

    @action
    exportShSelectedValue = (params) => {
        const {
            val,
            key
        } = params;

        this.shareForm[key] = val;
    }

    hideShareField = () => {
        const {
            permissiontype,
            jobtitlelevel,
        } = this.shareForm;

        let temp;

        if (permissiontype == '1') {
            temp = ['sharevalue6', 'sharevalue5', 'sharevalue2', 'sharevalue7', 'jobtitlesharevalue2', 'jobtitlesharevalue3'];
        }
        if (permissiontype == '6') {
            temp = ['sharevalue1', 'sharevalue5', 'sharevalue2', 'sharevalue7', 'jobtitlesharevalue2', 'jobtitlesharevalue3'];
        }
        if (permissiontype == '3') {
            temp = ['sharevalue1', 'sharevalue6', 'sharevalue5', 'sharevalue2', 'sharevalue7', 'jobtitlesharevalue2', 'jobtitlesharevalue3'];
        }
        if (permissiontype == '5') {
            temp = ['sharevalue1', 'sharevalue6', 'sharevalue2', 'sharevalue7', 'jobtitlesharevalue2', 'jobtitlesharevalue3'];
        }
        if (permissiontype == '2') {
            temp = ['sharevalue1', 'sharevalue6', 'sharevalue5', 'sharevalue7', 'jobtitlesharevalue2', 'jobtitlesharevalue3'];
        }
        if (permissiontype == '7') {
            if (jobtitlelevel == '1') {
                temp = ['sharevalue1', 'sharevalue6', 'sharevalue5', 'sharevalue2', 'jobtitlesharevalue2', 'jobtitlesharevalue3'];
            }
            if (jobtitlelevel == '2') {
                temp = ['sharevalue1', 'sharevalue6', 'sharevalue5', 'sharevalue2', 'jobtitlesharevalue3'];
            }
            if (jobtitlelevel == '3') {
                temp = ['sharevalue1', 'sharevalue6', 'sharevalue5', 'sharevalue2', 'jobtitlesharevalue2'];
            }
        }

        window.e9HideFormFieldKeys = temp;

    }

    saveShareScope = () => {
        Api.operateShareForm({
            operate: 'addShare',
            sysid: this.mainTable.id,
            ...this.shareForm.form.getFormParams(),
        }).then(cb => {
            const {
                status,
                msg,
            } = cb;

            if (status == '1') {
                if (msg && msg != 'success') {
                    message.warning(msg);
                    return
                }
                message.success(getLabel(22619, '保存成功'));

                this.getShareList();
                this.closeDialog();

            } else {
                message.warning(getLabel(22620, '保存失败'));
            }
        });
    }

    @action
    resetShareForm = () => {
        ['condition', 'role', 'post'].map(v => {
            this.shareForm[v] = [];
        });
        this.shareForm.form = new WeaForm();
        this.shareForm.jobtitlelevel = '';
    }

    //*************************Expression*******************************
    @observable expression = {
        allParams: [],
        value: '',
        txtAreaValue: '',
    }

    @action
    getAllParams = () => {
        const {
            form
        } = this.loginForm, {
            datas
        } = this.tableEdit;
        let temp = [];
        const formParams = form.getFormParams();
        let arr = [];

        if(formParams.typename == '2') {
          arr = ['baseparam1'];
        }else {
          arr = ['baseparam1', 'baseparam2'];
        }
        arr && arr.map(v => {
          formParams[v] && temp.push(formParams[v]);
        });

        datas && datas.map((data, index) => {
            if (index !== this.tableEdit.index && data.paramnames) {
                temp.push(data.paramnames)
            }
        });

        this.expression.allParams = temp;
    }

    @action
    exportDelimiter = (val) => {
        this.expression.value = val;
    }

    @action
    insertDelimiter = () => {
        const {
            value,
            txtAreaValue
        } = this.expression;

        if (!value) {
            return
        }
        this.expression.txtAreaValue = txtAreaValue ? `${txtAreaValue}+"${value}"` : `"${value}"`;
    }

    @action
    insertParams = (params) => {
        const {
            param
        } = params, {
            txtAreaValue
        } = this.expression;

        this.expression.txtAreaValue = txtAreaValue ? `${txtAreaValue}+${param}` : `${param}`;
    }

    @action
    exportTxtAreaValue = (val) => {
        this.expression.txtAreaValue = val;
    }

    @action
    writeExpToTable = () => {
        const {
            datas,
            index
        } = this.tableEdit, {
            txtAreaValue
        } = this.expression;

        datas && datas.map((d, i) => {
            if (i === index && d.cascader) {
                d.cascader[2] = txtAreaValue;
            }
        })

        this.closeDialog();
    }

    @action
    resetExpression = () => {
        this.expression.allParams = [];
        ['value', 'txtAreaValue'].map(v => {
            this.expression[v] = '';
        });
    }

    setSource = (source) => {
        this.source = source;
    }

    @action getListNum = (params={}, saveCallBack=null) => {
        this.mainTable.listTableStore = new TableStore();
        Api.getOutterSysList(params).then(result => {
            if (result.status) {
                this.mainTable.listTableStore.getDatas(result.sessionkey, 1);
                if(saveCallBack && typeof(saveCallBack) === "function") {
                    saveCallBack();
                }
            }
        })
    }

    @action createSecretKey = (params) => {
        params = params || {};
        Api.createSecretKey(params).then(result => {
            if (result.success) {
                result.pubKey && this.loginForm.form.updateFields({email163_pubkey: result.pubKey});
                result.priKey && this.loginForm.form.updateFields({email163_key: result.priKey});
            }
        })
    }

    // -------------------分类--------------

    @observable typeForm = {
        condition: [],
        form: new WeaForm(),
        loading: true,
        fields: [],
        filename: '',
        excelFileId: '',
        urllinkimagid: ''
    }

    @action
    resetTypeForm = () => {
        this.typeForm.condition = [];
        this.typeForm.form = new WeaForm();
        this.typeForm.fields = [];
        this.typeForm.loading = true;
        ['filename', 'excelFileId', 'urllinkimagid', 'isNotUnique0', 'isNotUnique1'].map(v => {
            this.typeForm[v] = '';
        });
    }

    // 分类
    @action operateTypeForm = () => {
        Api.operateTypeForm({
            operate: 'getForm',
            outterTypeid: this.mainTable.id,
        }).then(cb => {
            const {
                status,
                condition,
            } = cb;

            if (status == '1') {
                this.handleCondition({
                    condition: condition,
                    func: 'handlelfCondition'
                });
                this.typeForm.condition = condition;
                this.typeForm.form.initFormFields(condition);
                this.typeForm.loading = false;
                this.typeForm.urllinkimagid = cb.iconId ? cb.iconId : '';
            } else {
                message.error();
            }
        })
    }

    @action
    setHRMNetworkListVisible = (bool) => {
       this.HRMNetworkListVisible = bool;
    }

    @action
    saveTypeSet = () => {
        const {
            form,
            isNotUnique0,
            isNotUnique1,
        } = this.typeForm, {
            type
        } = this.mainDialog;

        const formParams = form.getFormParams();

        this.checkValueUnique({
            tableName: 'outter_sys_type',
            fieldName: 'fullName',
            fieldValue: formParams.fullName.replace(/^(\s*)|(\s*)$/g, ''),
            idValue: this.mainTable.id,
            idName: 'id'
        }).then(result => {
            if (result.isNotUnique) {
                this.typeForm.form.showError('fullName', getLabel('504676', '"全称" 已存在'));
            } else {
                this.checkValueUnique({
                    tableName: 'outter_sys_type',
                    fieldName: 'shortName',
                    fieldValue: formParams.shortName.replace(/^(\s*)|(\s*)$/g, ''),
                    idValue: this.mainTable.id,
                    idName: 'id'
                }).then(result => {
                    if (result.isNotUnique) {
                        this.typeForm.form.showError('shortName', getLabel('504677', '"简称" 已存在'));
                    } else {
                        Api.operateTypeForm({
                            operate: 'save',
                            outterTypeid: this.mainTable.id,
                            ...this.typeForm.form.getFormParams(),
                            ...this.getPicParams(),
                        }).then(cb => {
                            const {
                                status,
                                msg,
                            } = cb;

                            if (status == '1') {
                                if (msg != 'success') {
                                    message.warning(msg);
                                    return
                                }
                                message.success(getLabel(22619, '保存成功'));
                                this.getList();
                                this.closeDialog();
                            } else {
                                message.warning(getLabel(22620, '保存失败'));
                            }
                        });
                    }
                })
            }
        })
    }
}