import {
    observable,
    action,
    computed
} from 'mobx';
import {
    WeaForm,
    WeaTableNew,
    WeaSwitch
} from 'comsMobx';
import {
    WeaHelpfulTip,
    WeaError,
    WeaLocaleProvider
} from 'ecCom';
import {
    Button,
    message
} from 'antd';
import {
    has,
    cloneDeep
} from 'lodash';
import HrmBaseStore from './baseStore';
import * as api from '../apis/roleSetting';
import {
    authorized
} from '../apis/common';
import {
    i18n
} from '../public/i18n';
import {
    calFormHeight
} from '../util/index';
import classnames from 'classnames';
const getLabel = WeaLocaleProvider.getLabel;

const {
    TableStore
} = WeaTableNew;

/**
 * export 功能  author f
 */

export class HrmRoleSetting extends HrmBaseStore {
    /********************* unobservable list *********************/
    detachable = false;
    topBtnAndMenu = () => {
        if (!this.authorizationInfo.canEdit)
            return {
                btns: [],
                menus: [...this.getBasicMenus()]
            }
        return {
            btns: [
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cz3him`} type='primary' onClick={this.createRole}>{i18n.button.create()}</Button>,
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@drmye7`} type='primary' onClick={this.removeRole} disabled={this.roleListMultiRemoveable}>{i18n.button.multiDelete()}</Button>
            ],
            menus: [{
                key: '1',
                content: i18n.button.create(),
                icon: <i className={this.menuIconCollection.create}/>,
                onClick: this.createRole
            }, {
                key: '2',
                content: i18n.button.multiDelete(),
                icon: <i className={this.menuIconCollection.remove}/>,
                onClick: this.removeRole,
                disabled: this.roleListMultiRemoveable
            }, {
                key: '4',
                content: i18n.button.columnVisibleSetting(),
                icon: <i className={this.menuIconCollection.setting}/>,
                onClick: () => this.definedColumn(this.roleListTable)
            }, ...this.getBasicMenus('HRM_ENGINE_ROLESET')]
        }
    }

    orgTreeProps = {
        needSearch: true,
        isLoadSubDepartment: false,
        topPrefix: 'hrmSearch',
        inputLeftDom: `<b>${i18n.label.organization()}</b>`,
        // needDropMenu: true,
        treeNodeClick: this.treeNodeClick,
        params: {
            rightStr: 'HrmRolesAdd:Add'
        }
    }

    tabConfig = {
        tabs: [{
            color: '#000000',
            groupId: 'roleList',
            title: '',
            viewCondition: '1',
            searchType: ['base', 'advanced'],
            searchKey: 'roleName',
            doSearch: (params) => this.getRoleList(params)
        }],
        keyParam: 'viewCondition',
        activeTabKey: '1'
    }

    tabDef = [{
        color: '#000000',
        groupId: 'roleInfo',
        title: i18n.label.basicSetting
    }, {
        color: '#000000',
        groupId: 'setting',
        title: '',
        searchType: ['base', 'advanced'],
        searchKey: '',
        doSearch: (params) => {},
        tabButtonDef: [{
            comType: 'button',
            icon: 'icon-coms-Add-to-hot',
            label: i18n.button.create,
            rightMenuIcon: this.menuIconCollection.create,
            onClickHandle: () => this.doAction('create')
        }, {
            comType: 'button',
            icon: 'icon-coms-BatchEditing-Hot',
            label: i18n.button.multiModify,
            rightMenuIcon: this.menuIconCollection.multiModify,
            onClickHandle: () => this.doAction('modify'),
            checkAction: 'dataRemoveable'
        }, {
            comType: 'button',
            icon: 'icon-coms-form-delete-hot',
            label: i18n.button.multiDelete,
            rightMenuIcon: this.menuIconCollection.remove,
            onClickHandle: () => this.doAction('remove'),
            checkAction: 'dataRemoveable'
        },  {
            comType: 'button',
            icon: 'icon-coms-export',
            label: i18n.button.export,
            rightMenuIcon: this.menuIconCollection.export,
            onClickHandle: () => this.doAction('export'),
        }]
    }]

    roleEditTabConfig = {
        tabs: [],
        keyParam: 'viewCondition',
        activeTabKey: '1'
    }

    activeTabInfo = {}
    selectedRole = {}
    single = false;

    formItemRender = {
        roletype: (field, textAreaProps, form, formParams) => {
            const tips = (
                <div>
                    <p style={{fontWeight: 'bold'}}>{i18n.label.explain()}</p>
                    <p>{i18n.label.authRole()}</p>
                    <p>{i18n.label.detachRole()}</p>
                </div>
            )
            return (
                <div>
                    <div style={{float: 'left', width: 'auto'}}>
                        <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@xtj4gl`} fieldConfig={{...field, ...textAreaProps}} form={form} formParams={formParams}/>
                    </div>
                    <div style={{float: 'left', paddingTop: '3px'}}>
                        <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@n7s94q`} title={tips} />
                    </div>
                </div>
            )
        },
        type: (field, textAreaProps, form, formParams) => {
            return (
                <div>
                    <div style={{float: 'left', width: '30%'}}>
                        <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ogh30b`} 
                            fieldConfig={{...field, ...textAreaProps}} 
                            form={form} 
                            formParams={formParams} 
                            onChange={() => this.refreshAddAuthDialog = new Date().getTime()}/>
                    </div>
                    {
                        formParams.type === '2' &&
                        <div style={{float: 'left', width: '68%', marginLeft: '2%'}}>
                            <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@zree7z`} tipPosition='bottom' ref={(ref) => this.weaError = ref} error={i18n.message.dataEmpty()}>
                                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@cz3h6i`} style={{width: '100%'}}
                                    fieldConfig={{...form.fieldArr[1], ...textAreaProps}} 
                                    form={form} 
                                    formParams={formParams}/>
                            </WeaError>
                        </div>
                    }
                </div>
            )
        },
        rightid: (field, textAreaProps, form, formParams) => {
            return;
        }
    }

    weaError;
    selectedSubCompany;
    canEdit = false;
    /********************* unobservable list *********************/

    /********************* dialog info setting *********************/
    editorDialogRightMenu = [];
    getDialogOpButtons = () => { //获取权限组编辑对话框按钮列表
        let buttons = [];
        this.editorDialogRightMenu.length = 0;
        if(this.addRoleSingle){
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@l9cbd3`} type="primary" op="create" onClick={() => this.saveRoleBySingle()}>{i18n.button.save()}</Button>);
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@z1vdr3`} type="primary" op="entry" onClick={() => this.saveRoleBySingle(true)}>{i18n.button.saveAndSetting()}</Button>);
        } else if (this.dialogParams.add.visible) {
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@uytjay`} type="primary" op="create" onClick={() => this.saveRole(false,true,true)}>{i18n.button.save()}</Button>);
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@q2s0k6`} type="primary" op="entry" onClick={() => this.saveRole(true,true,true)}>{i18n.button.saveAndSetting()}</Button>);
        } else if (this.dialogParams.edit.visible && this.roleEditTabConfig.activeTabKey === '1') {
            if (this.canEdit) buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wnntep`} type="primary" op="save" onClick={() => this.saveRole(false, false)}>{i18n.button.save()}</Button>)
        } else if (this.dialogParams.saveAs.visible) {
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ua1mus`} type="primary" op="create" onClick={() => this.saveAs()}>{i18n.button.save()}</Button>);
            buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w2rkiw`} type="primary" op="entry" onClick={() => this.saveAs(true)}>{i18n.button.saveAndSetting()}</Button>);
        }
        buttons.map((btn, index) => {
            const {
                props
            } = btn;
            this.editorDialogRightMenu.push({
                key: index.toString(),
                content: props.children,
                icon: <i className={this.menuIconCollection[props.op]}/>,
                onClick: props.onClick
            });
        })

        return buttons;
    }

    showRoleEditDialog = (params, tabKey, record) => { 
        authorized('role', {
            subCompanyId: record.subcompanyid
        }).then((data) => {
            if (data.status === '1') {
                // this.authorizationInfo = data;
                this.getTabInfo(null, data.canEdit);

                this.roleEditDialogParams = {
                    params,
                    tabKey
                };
                this.refreshDialog = new Date().getTime();
            }
        }, error => {});
    }

    initRoleEditDialog = (params, tabKey) => {
        if (has(params, 'roleId') && !this.dialogParams.edit.visible) {
            api.getDetachable().then(data => {
                if (data.status === '1')
                    this.detachable = data.detachable === '1';
                else
                    this.detachable = null;
            })
            this.selectedRole = params;
            this.setActiveTab(this.roleEditTabConfig, tabKey);
            let dTitle = i18n.label.modifyRole();
            if(has(params, 'targetName'))
                dTitle += `-${params.targetName}`;
            this.setDialogVisible('edit', true, dTitle);
        }
    }

    initRoleInfoData = async (params, tab) => {
        const data = await api.getDetachable();
        this.containerInitFinished.detachable = data.detachable === '0' ? false : true
        this.containerInitFinished.init = true;
        this.selectedRole = params;
        this.single = true;
        authorized('role', params).then((data) => {
            if (data.status === '1') {
                this.getTabInfo(() => this.setActiveTab(this.roleEditTabConfig, tab), data.canEdit);
            }
        }, error => {});
    }

    roleEditDialogParams = {
        params: {},
        tabKey: ''
    }

    cloneFormTarget = {

    }

    opAction = {
        type: '',
        target: null,
        selectedAuthIds: '',
        selectedSubCompanyIds: '',
        isCreate: () => this.opAction.type === 'create',
        isModify: () => this.opAction.type === 'modify',
        isRemove: () => this.opAction.type === 'remove',
        isExport: () => this.opAction.type === 'export',
    }

    saveAsFields = [{
        "title": "基本信息",
        "defaultshow": true,
        "items": [{
            "colSpan": 2,
            "conditionType": "INPUT",
            "detailtype": 1,
            "domkey": ["roleName"],
            "fieldcol": 12,
            "isQuickSearch": false,
            "label": "角色名称",
            rules: "required|string",
            "labelcol": 6,
            "precision": 0,
            "viewAttr": 3,
            otherParams: {
                ...window.inputType
            }
        }]
    }]
    /********************* dialog info setting *********************/

    /********************* observable list *********************/
    dialogParams = { //override baseStore.dialogParams
        add: {
            visible: false,
            title: '',
            height: 600
        },
        edit: {
            visible: false,
            title: ''
        },
        saveAs: {
            visible: false,
            title: '另存为',
            height: 90
        }
    }

    @observable editDialogParams = {
        icon: "icon-coms-hrm",
        iconBgcolor: "#217346",
        style: {
            width: 540,
            height: 300
        },
        visible: false,
        title: '',
        buttons: [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zoan1w`} type="primary" onClick={() => this.doSave()}>{i18n.button.save()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@08esww`} disabled>{i18n.button.more()}</Button>)
        ],
        onCancel: () => {
            this.editDialogParams.visible = false;
        },
    }

    conditions = [];
    @observable memberAuthParams = {
        icon: "icon-coms-hrm",
        iconBgcolor: "#217346",
        title: i18n.label.addMemberAuth(),
        visible: false,
        onOk: (data) => this.doSaveMember({ ...this.selectedRole,
            ...data,
            cmd: 'addRolesMembers'
        }),
        onCancel: () => this.memberAuthParams.visible = false
    }

    @observable roleListTable = new TableStore();
    @observable authListTable = new TableStore();
    @observable detachListTable = new TableStore();
    @observable memberListTable = new TableStore();

    @observable refreshDialog = new Date().getTime();
    @observable refreshTab = new Date().getTime();
    @observable refreshAddAuthDialog = new Date().getTime();
    @observable activeTabKey = '2';
    @observable refreshTopBtn = new Date().getTime();
    /********************* observable list *********************/

    /********************* computed list *********************/
    @computed get roleListMultiRemoveable() {
        return this.roleListTable.selectedRowKeys.length === 0;
    }

    @computed get dataRemoveable() {
        switch (this.activeTabKey) {
            case '2':
                return this.authListTable.selectedRowKeys.length === 0;
            case '3':
                return this.detachListTable.selectedRowKeys.length === 0;
            case '4':
                return this.memberListTable.selectedRowKeys.length === 0;
            default:
                break;
        }
    }
    /********************* computed list *********************/

    /********************* action list *********************/
    @action initData = () => {
        api.initData().then(rs => {
            try {
                rs.map((result, index) => {
                    if (result.status === '1') {
                        switch (index) {
                            case 0:
                                this.detachable = result.detachable === '1';
                                break;
                            case 1:
                                this.setFormData('conditionForm', result.formField);
                                this.containerInitFinished = {
                                    ...this.containerInitFinished,
                                    init: true
                                }
                                break;
                            case 2:
                                this.roleListTable = new TableStore();
                                this.roleListTable.getDatas(result.sessionkey, 1);
                                break;
                            case 3:
                                this.cloneFormTarget.roleInfoFormFields = cloneDeep(result.formField);
                                this.setFormData('roleInfoForm', result.formField);
                                this.dialogParams.add.height = this.formTarget.roleInfoForm.fieldArr.length * 45 + 30; // _.keys(this.formTarget.roleInfoForm.getFormParams()).length * 45 + 20
                                break;
                            default:
                                break;
                        }
                    }
                });
            } catch (e) {}
        })
    }

    @action treeNodeClick = (event, ids, nodeids, nodes) => {
        const {
            data: nodeData
        } = event.node.props;
        this.selectedSubCompany = nodeData;
        // this.getRoleList({
        //     subCompanyId: nodeData.id
        // });
        authorized('role', {
            subCompanyId: nodeData.id
        }).then((data) => {
            if (data.status === '1') {
                this.authorizationInfo = data;
                this.getTabInfo(null, data.canEdit);
                this.getRoleCondition(() => {
                    this.getRoleList({
                        subCompanyId: nodeData.id
                    });
                },nodeData.id)
                this.refreshTopBtn = new Date().getTime();
            }
        }, error => {});
    }

    @action getRoleCondition = (cb,subCompanyId) => {
        const params = { subCompanyId };
        api.getRoleCondition(params).then(res => {
            this.setFormData('conditionForm', res.formField);
            this.containerInitFinished = {
                ...this.containerInitFinished,
                init: true
            };
            cb && cb();
        })
    }

    @action clearData = () => {
        this.selectedRole = {};
        this.roleEditDialogParams = {
            params: {},
            tabKey: ''
        }
    }

    @action clearOperationData = () => {
        this.opAction = {
            ...this.opAction,
            type: '',
            target: null,
            selectedAuthIds: '',
            selectedSubCompanyIds: ''
        }
    }

    @action getRoleInfo = (params) => {
        api.getRoleInfo(params).then(data => {
            if (data.status === '1') {
                this.setFormData('roleInfoForm', data.formField);
                this.refreshTab = new Date().getTime();
            } else {
                message.error(data.message);
            }
        })
    }

    @action initAuthData = (params) => {
        api.initAuthData(params).then(rs => {
            try {
                rs.map((result, index) => {
                    if (result.status === '1') {
                        switch (index) {
                            case 0:
                                this.setFormData('dialogConditionForm', result.formField);
                                break;
                            case 1:
                                let fields = result.formField[0].items;
                                fields[1].title = i18n.label.selectAuthorization();
                                fields[1].viewAttr = 3;
                                this.cloneFormTarget.authInfoFormFields = cloneDeep(result.formField);
                                this.setFormData('authInfoForm', result.formField);
                                break;
                            case 2:
                                this.authListTable = new TableStore();
                                this.authListTable.getDatas(result.sessionkey, 1);
                                break;
                            default:
                                break;
                        }
                    }
                });
                this.refreshTab = new Date().getTime();
            } catch (e) {}
        })
    }

    @action initDetachData = (params) => {
        api.initDetachData(params).then(rs => {
            try {
                rs.map((result, index) => {
                    if (result.status === '1') {
                        switch (index) {
                            case 0:
                                this.setFormData('dialogConditionForm', result.formField);
                                break;
                            case 1:
                                let fields = result.formField[0].items;
                                this.cloneFormTarget.detachInfoFormFields = cloneDeep(result.formField);
                                this.setFormData('detachInfoForm', result.formField);
                                break;
                            case 2:
                                this.detachListTable = new TableStore();
                                this.detachListTable.getDatas(result.sessionkey, 1);
                                break;
                            default:
                                break;
                        }
                    }
                });
                this.refreshTab = new Date().getTime();
            } catch (e) {}
        })
    }

    @action initMemberData = (params) => {
        api.initMemberData(params).then(rs => {
            try {
                rs.map((result, index) => {
                    if (result.status === '1') {
                        switch (index) {
                            case 0:
                                this.setFormData('dialogConditionForm', result.formField);
                                break;
                            case 1:
                                this.memberAuthParams.conditions = result.conditions;
                                const fields = [{
                                    "title": "基本信息",
                                    "defaultshow": true,
                                    "items": [{
                                        "colSpan": 2,
                                        "conditionType": "SELECT",
                                        "detailtype": 1,
                                        "domkey": ["rolelevel"],
                                        "fieldcol": 12,
                                        "isQuickSearch": false,
                                        "label": getLabel('515605','成员级别') ,
                                        "labelcol": 6,
                                        "options": [{
                                            "key": "2",
                                            "selected": false,
                                            "showname": getLabel("140","总部")
                                        }, {
                                            "key": "1",
                                            "selected": false,
                                            "showname": getLabel("33553","分部")
                                        }, {
                                            "key": "0",
                                            "selected": true,
                                            "showname": getLabel("126029","部门")
                                        }],
                                        "precision": 0,
                                        "viewAttr": 3
                                    }]
                                }]
                                this.cloneFormTarget.memberInfoFormFields = cloneDeep(fields);
                                break;
                            case 2:
                                this.memberListTable = new TableStore();
                                this.memberListTable.getDatas(result.sessionkey, 1);
                                break;
                            default:
                                break;
                        }
                    }
                });
                this.refreshTab = new Date().getTime();
            } catch (e) {}
        })
    }

    @action setActiveTab = (tabConfig, key) => {
        tabConfig.activeTabKey = key || tabConfig.tabs[0].viewCondition;
        const tabIndex = this.getTabIndex(tabConfig.tabs, key);
        if (tabIndex < 0) return;
        this.activeTabKey = key;
        switch (key) {
            case '1':
                this.getRoleInfo({
                    id: this.selectedRole.roleId
                });
                break;
            case '2':
                this.initAuthData(this.selectedRole);
                break;
            case '3':
                this.initDetachData(this.selectedRole);
                break;
            case '4':
                this.initMemberData(this.selectedRole);
                break;
            default:
                break;
        }
    }

    @action getTabInfo = (callback, canEdit = false) => {
        this.canEdit = canEdit;
        api.getTabInfo().then(data => {
            if (data.status === '1') {
                this.roleEditTabConfig.tabs.length = 0;
                data.tabs.map(tab => {
                    let tabInfo = {}
                    if (tab.key === '1') {
                        tabInfo = {
                            ...this.tabDef[0],
                            title: tab.title,
                            viewCondition: tab.key
                        }
                    } else {
                        tabInfo = {
                            ...cloneDeep(this.tabDef[1]),
                            title: tab.title,
                            groupId: tab.key,
                            viewCondition: tab.key,
                        }
                        if (!canEdit)
                            delete tabInfo.tabButtonDef;
                        switch (tab.key) {
                            case '2':
                                if (canEdit) tabInfo.tabButtonDef[1].label = i18n.button.multiModifyAuthRoleLevel();
                                tabInfo.searchKey = 'roleName';
                                tabInfo.doSearch = (params) => this.getAuthList(params)
                                break;
                            case '3':
                                if (canEdit) tabInfo.tabButtonDef[1].label = i18n.button.multiModifyDetachRoleLevel();
                                if (canEdit) tabInfo.tabButtonDef[2].label = i18n.button.removeRef();
                                tabInfo.doSearch = (params) => this.getDetachList(params)
                                tabInfo.searchKey = 'subcompanyname';
                                break;
                            case '4':
                                if (canEdit) tabInfo.tabButtonDef[1].label = i18n.button.multiModifyMemberRoleLevel();
                                if (canEdit) tabInfo.tabButtonDef[2].label = i18n.button.removeRef();
                                tabInfo.doSearch = (params) => this.getMemberList(params)
                                tabInfo.searchKey = 'hrmName';
                                break;
                        }
                    }
                    this.roleEditTabConfig.tabs.push(tabInfo);
                })
                callback && callback();
                this.refreshTab = new Date().getTime();
            } else {
                message.error(data.message)
            }
        })
    }

    @action getAuthList = (params) => {
        api.getAuthList({ ...params,
            ...this.selectedRole
        }).then(data => {
            if (data.status === '1')
                this.authListTable.getDatas(data.sessionkey, 1);
            else
                message.error(data.message);
        })
    }

    @action getDetachList = (params) => {
        api.getDetachList({ ...params,
            ...this.selectedRole
        }).then(data => {
            if (data.status === '1')
                this.detachListTable.getDatas(data.sessionkey, 1);
            else
                message.error(data.message);
        })
    }

    @action getMemberList = (params) => {
        api.getMemberList({ ...params,
            ...this.selectedRole
        }).then(data => {
            if (data.status === '1')
                this.memberListTable.getDatas(data.sessionkey, 1);
            else
                message.error(data.message);
        })
    }

    @action createRole = () => {
        if (this.selectedSubCompany != null && this.detachable) {
            let fields = cloneDeep(this.cloneFormTarget.roleInfoFormFields);
            fields.map(f => {
                f.items.map(item => {
                    if (item.domkey[0] === 'structureid') {
                        item.browserConditionParam.replaceDatas = [{
                            id: this.selectedSubCompany.id.toString(),
                            name: this.selectedSubCompany.name
                        }]
                    }
                    if (['idname', 'roletype', 'structureid'].indexOf(item.domkey[0]) >= 0)
                        item.viewAttr = 3;
                    else
                        item.viewAttr = 2;
                })
            })
            this.setFormData('roleInfoForm', fields);
        } else {
            this.setFormData('roleInfoForm', cloneDeep(this.cloneFormTarget.roleInfoFormFields));
        }
        this.setDialogVisible('add', true, i18n.label.createRole());
    }

    @action saveRole = (setting = false, closeDialog = true,needId) => {
        this.formTarget.roleInfoForm.validateForm().then(f => {
            if (f.isValid) {
                let params = {
                    ...this.formTarget.roleInfoForm.getFormParams(),
                    id:needId ? null:this.selectedRole.roleId                
                }
                api.saveRoleInfo(params).then(data => {
                    if (data.status === '1') {
                        message.success(i18n.message.saveSuccess());
                        this.getRoleList();
                        this.dialogParams.add.visible && this.setDialogVisible('add', false, '');
                        if (!setting) {
                            this.dialogParams.edit.visible && closeDialog && this.setDialogVisible('editGroupInfo', false, '', () => this.getTableData('groupTable'));
                        } else {
                            this.initRoleEditDialog({
                                roleId: data.id
                            }, '1');
                        }
                    } else
                        message.error(data.message);
                }, error => {
                    message.error(i18n.message.actionError());
                });
            } else {
                f.showErrors();
                this.showError = new Date().getTime();
            }
        });
    }

    @action saveAsRole = (params) => {
        if (has(params, 'roleId') && !this.dialogParams.saveAs.visible) {
            this.selectedRole = params;
            this.saveAsFields[0].items[0].label = i18n.label.roleName();
            this.saveAsFields[0].items[0].otherParams = {...window.inputType};
            this.setFormData('saveAsForm', cloneDeep(this.saveAsFields));
            this.setDialogVisible('saveAs', true, i18n.label.saveAs());
        }
    }

    @action saveAs = (setting = false) => {
        this.formTarget.saveAsForm.validateForm().then(f => {
            if (f.isValid) {
                let params = {
                    ...this.formTarget.saveAsForm.getFormParams(),
                    ...this.selectedRole
                }
                api.saveAs(params).then(data => {
                    if (data.status === '1') {
                        message.success(i18n.message.saveSuccess());
                        this.dialogParams.saveAs.visible && this.setDialogVisible('saveAs', false, '', () => this.getRoleList());
                        if (!setting) {} else {
                            this.initRoleEditDialog({
                                roleId: data.id
                            }, '1');
                        }
                    } else
                        message.error(data.message);
                }, error => {
                    message.error(i18n.message.actionError());
                });
            } else {
                f.showErrors();
                this.showError = new Date().getTime();
            }
        });
    }

    @action removeRole = (params = {}) => {
        let content;
        if (!has(params, 'id')) {
            content = i18n.confirm.deleteSelected();
            params = {
                id: this.roleListTable.selectedRowKeys
            }
        } else {
            content = i18n.confirm.delete();
        }

        this.confirmInfo({
            content,
            onOk: () => {
                api.removeRoleInfo(params).then(data => {
                    if (data.status === '1') {
                        message.success(i18n.message.deleteSuccess());
                        this.roleListTable.getDatas();
                    } else
                        message.error(data.message);
                }, error => {
                    message.error(i18n.message.actionError());
                });
            }
        });
    }

    @action getRoleList = (params) => {
        this.roleListTable = new TableStore();
        this.requestTableData(this.roleListTable, api.getRoleList, params);
    }

    @action showEditDialog = (isCreate, record) => {
        let formName = '',
            title = '',
            props = {},
            dk = '';
        switch (this.roleEditTabConfig.activeTabKey) {
            case '2':
                formName = 'authInfoForm';
                dk = 'rolelevel';
                if (isCreate)
                    title = i18n.label.addRoleAuth();
                else if (record != null)
                    title = `${i18n.label.editRoleAuth()}:${record.rightidspan}`;
                else
                    title = i18n.label.editRoleAuth();
                Object.assign(props, {
                    style: {
                        height: isCreate ? 130 : 90,
                        width: 540
                    },
                    title:<div dangerouslySetInnerHTML={{ __html: title }} />
                })
                break;
            case '3':
                formName = 'detachInfoForm';
                dk = 'rightlevel';
                if (isCreate)
                    title = i18n.label.addDetachAuth();
                else if (record != null)
                    title = `${i18n.label.editDetachAuth()}:${record.subcompanynamespan}`;
                else
                    title = i18n.label.editDetachAuth();
                Object.assign(props, {
                    style: {
                        height: isCreate ? 170 : 90,
                        width: 540
                    },
                    title:<div dangerouslySetInnerHTML={{ __html: title }} />
                })
                break;
            case '4':
                if (isCreate) {
                    this.memberAuthParams.visible = true;
                    return;
                } else {
                    formName = 'memberInfoForm';
                    dk = 'rolelevel';
                    if (record != null)
                        title = `${i18n.label.editMemberAuth()}:${record.resourcetypespan} ${record.resourceidspan} ${record.seclevelfromspan}`;
                    else
                        title = i18n.label.editMemberAuth();
                    Object.assign(props, {
                        style: {
                            height: isCreate ? 170 : 90,
                            width: 540
                        },
                        title:<div dangerouslySetInnerHTML={{ __html: title }} />
                    })
                }
                break;
        }

        if (isCreate) {
            this.formTarget[formName].resetForm();
            this.setFormData(formName, cloneDeep(this.cloneFormTarget[`${formName}Fields`]));
        } else {
            let cloneFields = cloneDeep(this.cloneFormTarget[`${formName}Fields`]);
            let fieldsSize = cloneFields[0].items.length;
            cloneFields[0].items.splice(0, fieldsSize - 1);
            if (record != null) {
                cloneFields[0].items[0].options.map(option => {
                    option.selected = option.key === record[dk];
                })
            }
            this.setFormData(formName, cloneFields);
        }
        let buttons = [];
        if (this.canEdit)
            buttons = [
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@aan2in`} type="primary" op='save' onClick={() => this.doSave()}>{i18n.button.save()}</Button>),
            ]
        let rightMenu = [];
        buttons.map((btn, index) => {
            const {
				props
			} = btn;
			rightMenu.push({
				key: index.toString(),
				content: props.children,
				icon: <i className={this.menuIconCollection[props.op]}/>,
				onClick: props.onClick
			});
        })
        this.editDialogParams = {
            ...this.editDialogParams,
            visible: true,
            buttons,
            moreBtn: {datas: rightMenu},
            ...props
        }
    }

    //添加/修改/删除 功能权限、成员、分权
    @action doAction = (action, target) => {
        this.opAction = {
            ...this.opAction,
            type: action,
            target: target
        }
        let cloneFields = null;
        if (this.opAction.isRemove()) {
            this.doRemove(target);
        } else if(this.opAction.isExport()){
            this.doExport();
        } else {
            this.showEditDialog(this.opAction.isCreate(), target);
        }
    }

    spinning = false;
    @action doSaveAuth = (params) => {
        if (this.spinning)
            return;
        this.spinning = true;
        api.saveAuth(params).then(data => {
            if (data.status === '1') {
                this.clearOperationData();
                this.initAuthData(this.selectedRole);
                !this.single && this.roleListTable.getDatas();
                this.editDialogParams.visible = false;
                message.success(i18n.message.saveSuccess());
            } else{
                message.error(data.message);
            }
            this.spinning = false;
        }, error => {
            this.spinning = false;
        })
    }

    @action doSaveDetachAuth = (params) => {
        api.saveDetachAuth(params).then(data => {
            if (data.status === '1') {
                this.clearOperationData();
                this.initDetachData(this.selectedRole);
                this.editDialogParams.visible = false;
                message.success(i18n.message.saveSuccess());
            } else
                message.error(data.message);
        })
    }

    @action doSaveMember = (params) => {
        api.saveMemberAuth(params).then(data => {
            if (data.status === '1') {
                this.clearOperationData();
                this.initMemberData(this.selectedRole);
                !this.single && this.roleListTable.getDatas();
                this.editDialogParams.visible = false;
                message.success(i18n.message.saveSuccess());
                this.memberAuthParams.onCancel();
            } else{
                message.error(data.message);
                this.editDialogParams.visible = false;
                this.memberAuthParams.onCancel();
            }
        })
    }

    @action doSave = () => {
        let formParams = null;
        const isCreate = this.opAction.isCreate();
        let params = {};
        switch (this.roleEditTabConfig.activeTabKey) {
            case '2':
                formParams = this.formTarget.authInfoForm.getFormParams();
                params = {
                    ...this.selectedRole,
                    cmd: isCreate ? 'addRoleRight' : 'editRoleRight',
                    roleLevel: formParams.rolelevel
                }
                if (isCreate) {
                    Object.assign(params, {
                        rightid: formParams.type === '1' ? 'all' : formParams.rightid
                    })
                    if (params.rightid === '') {
                        this.weaError.showError();
                        return;
                    }
                } else {
                    Object.assign(params, {
                        rightid: has(this.opAction.target, 'rightid') ? this.opAction.target.rightid : this.authListTable.selectedRowKeys
                    })
                }
                this.doSaveAuth(params);
                break;
            case '3':
                this.formTarget.detachInfoForm.validateForm().then(f => {
                    if (f.isValid) {
                        formParams = this.formTarget.detachInfoForm.getFormParams();
                        params = {
                            ...this.selectedRole,
                            cmd: isCreate ? 'addRoleSubCom' : 'editRoleSubCom',
                            ...formParams
                        }
                        isCreate && Object.assign(params, {
                            id: formParams.subcompanyid
                        });
                        !isCreate && Object.assign(params, {
                            id: has(this.opAction.target, 'id') ? this.opAction.target.id : this.detachListTable.selectedRowKeys
                        });
                        this.doSaveDetachAuth(params);
                    } else {
                        f.showErrors();
                        this.showError = new Date().getTime();
                    }
                });

                break;
            case '4':
                formParams = this.formTarget.memberInfoForm.getFormParams();
                params = {
                    ...this.selectedRole,
                    cmd: 'editRolesMembers',
                    ...formParams
                };
                !isCreate && Object.assign(params, {
                    id: has(this.opAction.target, 'id') ? this.opAction.target.id : this.memberListTable.selectedRowKeys
                });
                this.doSaveMember(params);
                break;
        }
    }

    @action removeItem = (params = {}, tableName) => {
        let apiFunc = null;
        switch (tableName) {
            case 'authListTable':
                apiFunc = api.removeAuth;
                break;
            case 'detachListTable':
                apiFunc = api.removeDetachAuth;
                break;
            case 'memberListTable':
                apiFunc = api.removeMemberAuth;
                break;
        }
        apiFunc(params).then(data => {
            if (data.status === '1') {
                this.clearOperationData();
                this[tableName].getDatas();
                this.editDialogParams.visible = false;
                message.success(i18n.message.deleteSuccess());
                !this.single && this.roleListTable.getDatas();
            } else
                message.error(data.message);
        })
    }

    @action doRemove = (target) => {
        let params = {};
        this.confirmInfo({
            content: target != null ? i18n.confirm.delete() : i18n.confirm.deleteSelected(),
            onOk: () => {
                switch (this.roleEditTabConfig.activeTabKey) {
                    case '2':
                        params = {
                            ...this.selectedRole,
                            rightId: target != null ? target.rightid : this.authListTable.selectedRowKeys
                        }
                        this.removeItem(params, 'authListTable');
                        break;
                    case '3':
                        params = {
                            ...this.selectedRole,
                            id: target != null ? target.id : this.detachListTable.selectedRowKeys
                        }
                        this.removeItem(params, 'detachListTable');
                        break;
                    case '4':
                        params = {
                            ...this.selectedRole,
                            id: target != null ? target.id : this.memberListTable.selectedRowKeys
                        }
                        this.removeItem(params, 'memberListTable');
                        break;
                }
            }
        });
    }

    @action doExport = () => {
        switch (this.roleEditTabConfig.activeTabKey) {
            case '2':
                this.authListTable.exportAll();
                break;
            case '3':
                this.detachListTable.exportAll();
                break;
            case '4':
               this.memberListTable.exportAll();
                break;
        }
    }
    /********************* action list *********************/

    //适配单页
    // @observable roleInfoTopButtons = [];
    getTabDef = () => {
        let tabInfo = {
            color: '#000000',
            groupId: 'setting',
            title: '',
            searchType: ['base', 'advanced'],
            tabButtonDef: [{
                comType: 'button',
                icon: 'icon-coms-Add-to-hot',
                label: i18n.button.add(),
                rightMenuIcon: this.menuIconCollection.create,
                onClickHandle: () => this.doAction('create')
            }, {
                comType: 'button',
                icon: 'icon-coms-BatchEditing-Hot',
                label: i18n.button.multiModify(),
                rightMenuIcon: this.menuIconCollection.multiModify,
                onClickHandle: () => this.doAction('modify'),
                checkAction: 'dataRemoveable'
            }, {
                comType: 'button',
                icon: 'icon-coms-form-delete-hot',
                label: i18n.button.multiDelete(),
                rightMenuIcon: this.menuIconCollection.remove,
                onClickHandle: () => this.doAction('remove'),
                checkAction: 'dataRemoveable'
            }]
        }
        switch (this.roleEditTabConfig.activeTabKey) {
            case '2':
                tabInfo.searchKey = 'roleName';
                tabInfo.doSearch = (params) => this.getAuthList(params)
                break;
            case '3':
                tabInfo.doSearch = (params) => this.getDetachList(params)
                tabInfo.searchKey = 'subcompanyname';
                break;
            case '4':
                tabInfo.doSearch = (params) => this.getMemberList(params)
                tabInfo.searchKey = 'hrmName';
                break;
        }
        return {
            tabs: [tabInfo],
            keyParam: 'viewCondition',
            activeTabKey: '1'
        }
    }

    getTabBtnDef = () => {
        let tabBtnDef = [];
        this.tabDef[1].tabButtonDef.map((def, idx) => { //组织WeaTab按钮
            switch (def.comType) {
                case 'button':
                    let disabled = false;
                    if (def.checkAction)
                        disabled = this[def.checkAction];
                    const classes = classnames({
                        [def.icon]: true,
                        'tabBtn': true,
                        'tabBtn-active': !disabled,
                        'tabBtn-disable': disabled
                    });
                    tabBtnDef.push(
                        <i
                          className={classes}
                          title={def.label}
                          onClick={!disabled ? def.onClickHandle : null} 
                        />
                    );
            }
        })
        return tabBtnDef;
    }
    getRoleInfoTopButtons = () => { //获取权限组编辑对话框按钮列表
        let buttons = [];
        this.editorDialogRightMenu.length = 0;
        this.roleEditTabConfig.activeTabKey === '1' && buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@d2t9f0`} type="primary" op="save" onClick={() => this.saveRole()}>{i18n.button.save()}</Button>);
        buttons.map((btn, index) => {
            const {
                props
            } = btn;
            this.editorDialogRightMenu.push({
                key: index.toString(),
                content: props.children,
                icon: <i className={this.menuIconCollection[props.op]}/>,
                onClick: props.onClick
            });
        })

        return buttons;
    }

    getInfo = async (key, params) => {
        const data = await authorized('role', {roleId: this.selectedRole.roleId});
        this.canEdit = data.canEdit;
        this.single = true;
        this.selectedRole = params;
        this.activeTabKey = this.roleEditTabConfig.activeTabKey = key;
        switch (key) {
            case '1':
                this.getRoleInfo({
                    id: this.selectedRole.roleId
                });
                break;
            case '2':
                this.initAuthData(this.selectedRole);
                break;
            case '3':
                this.initDetachData(this.selectedRole);
                break;
            case '4':
                this.initMemberData(this.selectedRole);
                break;
            default:
                break;
        }
        this.containerInitFinished.init = true;
    }

    //新建角色单页
    addRoleSingle = false;
    saveCallback;
    @action initAddRole = (saveCallback) => {
        this.saveCallback = saveCallback;
        this.addRoleSingle = true;
        api.getRoleInfo().then(data => {
            if(data.status === '1'){
                this.setFormData('roleInfoForm', data.formField);
                this.containerInitFinished.init = true;
            }else{
                message.error(data.message);
            }
        })
    }

    @action saveRoleBySingle = (setting = false) => {
        this.formTarget.roleInfoForm.validateForm().then(f => {
            if (f.isValid) {
                let params = {
                    ...this.formTarget.roleInfoForm.getFormParams()
                }
                api.saveRoleInfo(params).then(data => {
                    if (data.status === '1') {
                        message.success(i18n.message.saveSuccess());
                        this.saveCallback && this.saveCallback({id:data.id, name: data.roleName}, setting);
                    } else
                        message.error(data.message);
                }, error => {
                    message.error(i18n.message.actionError());
                });
            } else {
                f.showErrors();
                this.showError = new Date().getTime();
            }
        });
    }

    @action destoryMessage = () => {
        message.destroy();
    }
}