import { observable, action, computed } from 'mobx';
import { AuthorityStore, TopStore, SearchStore, TableListStore, DialogStore, FormStore, OrgTreeStore, ImportCommon } from '../../public/valhalla/stores/index';
import { i18n } from '../../public/i18n';
import { WeaButtonIcon } from 'ecCom';
import { Button, message } from 'antd';
import { capitalize } from 'lodash';
import * as api from '../../apis/sensitiveWord.js';

export default class ListStore {
    searchGroupProps = { col: 1 };
    
    @observable authorityStore = new AuthorityStore(api.hasRight);
    @observable topStore = new TopStore(this);
    @observable searchStore = new SearchStore(this);
    @observable secSearchStore = new SearchStore(this);
    @observable tableListStore = new TableListStore(this);
    @observable secTableListStore = new TableListStore(this);
    @observable dialogStore = new DialogStore(this);
    @observable secDialogStore = new DialogStore(this);
    @observable formStore = new FormStore(this);
    @observable secFormStore = new FormStore(this);
    @observable importCommon = new ImportCommon();
    @observable orgTreeStore = new OrgTreeStore(this);

    @observable pageType = '';
    @observable dialogType = '';

    @observable authVisible = false;
    @observable isDetachable = false;
    @observable canEdit = false;

    @computed get pageDialogType() {
        return `${this.pageType}${capitalize(this.dialogType)}`;
    }

    @computed get btnMenu() {
        const menus = {
            'word': [{
                "isTop": "1",
                "menuFun": "add",
                "menuIcon": "icon-coms-plus",
                "menuName": i18n.button.add(),
                "type": "BTN_Save"
            }, {
                "isTop": "1",
                "menuFun": "import",
                "menuIcon": "icon-coms-leading-in",
                "menuName": i18n.button.import(),
                "type": "BTN_Import"
            }],
            'wordType': [{
                "isTop": "1",
                "menuFun": "add",
                "menuIcon": "icon-coms-plus",
                "menuName": i18n.button.create(),
                "type": "BTN_Save"
            }, {
                "isTop": "1",
                "menuFun": "batchDelete",
                "menuIcon": "icon-coms-Batch-delete",
                "menuName": "批量删除",
                "type": "BTN_BatchDelete"
            }],
            'intercept': [],
            'approval': []
        } [this.pageType];
        menus.push({
            "isTop": "1",
            "menuFun": "exportExcel",
            "menuIcon": "icon-coms-export",
            "menuName": i18n.button.export(),
            "type": "BTN_export"
        },{
            "isTop": "0",
            "menuFun": "log",
            "menuIcon": "icon-coms-Print-log",
            "menuName": i18n.button.log(),
            "type": "BTN_log"
        });
        return menus;
    }

    @computed get topTitle() {
        return {
            'word': i18n.label['531343'](),
            'wordType': i18n.label['531347'](),
            'intercept': i18n.label['531350'](),
            'approval': i18n.label['531352']()
        } [this.pageType];
    }

    @computed get buttonSelectDatas() {
        const pageType = this.pageType;
        const bsd = {
            'word': [{
                key: '1',
                show: i18n.label['531344'](),
            }, {
                key: '2',
                show: i18n.button.multiDelete()
            }],
            'wordType': [],
            'intercept': [],
            // 'intercept': [{
            //     key: '1',
            //     show: i18n.label['531351']()
            // }, {
            //     key: '2',
            //     show: i18n.button.multiDelete()
            // }],
            'approval': [{
                key: '1',
                show: i18n.label['531353']()
            }, {
                key: '2',
                show: i18n.button.multiDelete()
            }]
        } [pageType];

        if (this.pageType == 'intercept') {
            const { selectedKey } = this.searchStore;
            return (selectedKey != '1') ? bsd : [];
        } else {
            return bsd;
        }

    }

    @computed get topConf() {
        return {
            btnMenu: this.btnMenu,
            title: this.topTitle,
            additionalTopProps: {
                icon: <i className='icon-coms-currency'/>
            }
        }
    }

    @computed get rightMenuStates() {
        const disabled = !this.selectedRowIds;
        return {
            'wordType': [false, disabled]
        } [this.pageType]
    }

    @computed get btnProps() {
        return !this.selectedRowIds;
    }

    @computed get secSearchButtons() {
        const disabled = (this.selectedRowIds == '');
        return [
            <WeaButtonIcon buttonType="add" type="primary" onClick={this.addRemainObj} />,
            <WeaButtonIcon buttonType="del" type="primary" disabled={disabled} onClick={this.delRemainObj} />
        ]
    }

    @computed get tabConf() {
        const conf = { _handleSearch: this._handleSearch };
        const tagetConf = {
            'word': {
                api: api.getSensitiveWordCondition,
                linkageFieldName: 'word',
                 advanceHeight: 120,
                tabApi: '',
            },
            'wordType': {
                api: api.getSensitiveWordTypeCondition,
                linkageFieldName: 'name',
                advanceHeight: 80,
                tabApi: '',
            },
            'intercept': {
                api: api.getSensitiveWordLogCondition,
                linkageFieldName: 'doccontent',
                tabApi: api.getSensitiveWordLogTab,
                advanceHeight: 170,
                _handleTabChange: this._handleTabChange,
            },
            'approval': {
                api: api.getSensitiveWordApproveCondition,
                linkageFieldName: 'word',
                advanceHeight: 170,
                tabApi: '',
                _handleTabChange: this._handleTabChange,
            },
            'wordTypeRemainset': {
                searchType: ['base'],
                mark: 'sec',
                value:'',
            }
        } [this.pageDialogType];
        return Object.assign({}, conf, tagetConf);
    }

    @computed get searchParams(){
        const {type,id} = this.orgTreeStore;
        if (['intercept','approval'].includes(this.pageType) && this.isDetachable && type!= '0') {
            return {
                subcompanyid: id
            }
        }
    }

    @computed get tabParams(){
        return this.searchStore.form.getFormParams()
    }

    @computed get targetSearchStore() {
        return (this.pageDialogType == 'wordTypeRemainset') ? this.secSearchStore : this.searchStore;
    }

    @computed get tableConf() {
        const conf = {
            _onOperatesClick: this._onOperatesClick,
            _reRenderColumns: this._reRenderColumns
        }
        const tagetConf = {
            'word': { api: api.getSensitiveWordList },
            'wordType': { api: api.getSensitiveWordTypeList },
            'intercept': { api: api.getSensitiveWordLogList },
            'approval': { api: api.getSensitiveWordApproveList },
            'wordTypeRemainset': { api: api.getSensitiveWordTypeScopeList }
        } [this.pageDialogType]
        return Object.assign({}, conf, tagetConf);
    }

    @computed get targetTableListStore() {
        return (this.pageDialogType == 'wordTypeRemainset') ? this.secTableListStore : this.tableListStore;
    }

    @computed get tableParams() {
        let params, pageDialogType = this.pageDialogType;
        if (pageDialogType == 'wordTypeRemainset') {
            params = {
                name: this.secSearchStore.value,
                id: this.dataId
            };
        } else {
            params = this.searchStore.form.getFormParams();
            if (['intercept', 'approval'].includes(pageDialogType)) {
                Object.assign(params, {
                    key: this.searchStore.selectedKey,
                    // subcompanyid: this.orgTreeStore.id
                });
            }
        }
        return params;
    }

    @computed get selectedRowIds() {
        return this.targetTableListStore.tableStore.selectedRowKeys.join(',');
    }

    @computed get isInitTable() {
        return ['wordAdd', 'wordEdit', 'wordHandleway', 'wordTypeAdd', 'wordTypeEdit', 'wordTypeRemainset','approvalEdit'].includes(this.pageDialogType);
    }

    @computed get tableDelApi() {
        return {
            'word': api.delSensitiveWord,
            'wordType': api.delSensitiveWordType,
            'wordTypeRemainset': api.delSensitiveWordTypeScope,
            'intercept': api.processSensitiveWordLog,
            'interceptEdit': api.processSensitiveWordLog,
            'approval': api.delSensitiveWordApprove,
        } [this.pageDialogType]
    }

    @computed get dialogTitle() {
        return {
            'wordAdd': i18n.label['531346'](),
            'wordEdit': i18n.label['531345'](),
            'wordCreate': i18n.label['531348'](),
            'wordHandleway': i18n.label['531344'](),
            'wordTypeAdd': i18n.label['531348'](),
            'wordTypeEdit': i18n.label['531349'](),
            'wordTypeRemainset': i18n.label['531584'](),
            'wordTypeRemainsetadd': i18n.label['531602'](),
            'interceptEdit': i18n.label['531603'](),
            'approvalEdit': i18n.label['531609'](),
            'approvalCreate': i18n.label['531348'](),
        } [this.pageDialogType];
    }

    @computed get dialogStyle() {
        const style = {
            'wordCreate': { width: 540, height: 280 },
            'wordTypeRemainset': { width: 800, height: 600 },
            'wordTypeRemainsetadd': { width: 610, height: 300 },
            'approvalCreate': { width: 540, height: 280 },
        } [this.pageDialogType];

        return style || { width: 600, height: 300 };
    }

    @computed get DialogButtons() {
        const pageDialogType = this.pageDialogType;
        if (pageDialogType.includes('wordTypeRemainset')) {
            return [];
        }
        if (pageDialogType == 'interceptEdit') {
            return this.canEdit && [
                <Button type='primary' onClick={()=> this.singleDesensitization(this.dataId)}>{i18n.label['531731']()}</Button>,
                <Button type='primary' onClick={() => this.singleDel(this.dataId)}>{i18n.label['531732']()}</Button>
            ]
        }
        const btnArr = [<Button type='primary' onClick={this.handleSave}>{i18n.button.save()}</Button>]
        if (pageDialogType == 'approvalEdit') {
            btnArr.push(<Button type='primary' onClick={() => this.handleSave('saveAndProcess')}>{i18n.label['531728']()}</Button>)
        }
        return btnArr;
    }

    @computed get secDialogButtons() {
        return [<Button type='primary' onClick={this.handleSave}>{i18n.button.save()}</Button>]
    }

    @computed get dialogConf() {
        return {
            title: this.dialogTitle,
            style: this.dialogStyle,
            moduleName: 'currency',
            _closeDialog: this._closeDialog,
        }
    }

    @computed get targetDialogStore() {
        return ['wordCreate', 'wordTypeRemainsetadd', 'approvalCreate'].includes(this.pageDialogType) ? this.secDialogStore : this.dialogStore;
    }

    @computed get formConf() {
        const conf = {
            isCustomRender: false,
            hasTitle: false,
        };
        conf.api = {
            'wordAdd': api.getSensitiveWordForm,
            'wordEdit': api.getSensitiveWordForm,
            'wordCreate': api.getSensitiveWordTypeForm,
            'wordHandleway': api.getSensitiveWordDefaultHandleWayForm,
            'wordTypeAdd': api.getSensitiveWordTypeForm,
            'wordTypeEdit': api.getSensitiveWordTypeForm,
            'wordTypeRemainsetadd': api.getSensitiveWordTypeScopeForm,
            'interceptEdit': api.getSensitiveWordLogForm,
            'approvalEdit': api.getSensitiveWordApprovalForm,
            'approvalCreate': api.getSensitiveWordTypeForm,
        } [this.pageDialogType];
        return conf;
    }

    @computed get formSaveApi() {
        return {
            'wordAdd': api.saveSensitiveWord,
            'wordEdit': api.saveSensitiveWord,
            'wordCreate': api.saveSensitiveWordType,
            'wordHandleway': api.saveSensitiveWordDefaultHandleWay,
            'wordTypeAdd': api.saveSensitiveWordType,
            'wordTypeEdit': api.saveSensitiveWordType,
            'wordTypeRemainsetadd': api.saveSensitiveWordTypeScope,
            'interceptEdit': api.saveSensitiveWordLog,
            'approvalEdit': api.saveSensitiveWordApprove,
            'approvalCreate': api.saveSensitiveWordType,
        } [this.pageDialogType];
    }

    @computed get formSaveParams() {
        const params = this.targetFormStore.form.getFormParams();
        if (['wordEdit', 'wordTypeEdit', 'approvalEdit'].includes(this.pageDialogType)) {
            params.id = this.dataId;
        }
        if (this.pageDialogType == 'wordHandleway') {
            params.ids = this.selectedRowIds;
        }
        return params;
    }

    @computed get targetFormStore() {
        return (['wordCreate', 'approvalCreate'].includes(this.pageDialogType)) ? this.secFormStore : this.formStore;
    }

    @computed get orgTreeMoreProps(){
        if (this.isDetachable) {
            return {
                'intercept':{
                    params:{
                        rightStr:'SensitiveWordLog:Manage'
                    }
                },
                'approval':{
                    params:{
                        rightStr: 'SensitiveWordApprove:Manage'
                    } 
                }
            }[this.pageType]
        }
    }

    init = () => {
        this.reset();
        this.authorityStore.fetchAuthority({type:this.pageType}).then(()=>{
            this.initTop();
            this.initTab();
            if (['intercept', 'approval'].includes(this.pageType)) {
                this.getDetachable();
            }
        })
    }

    initTop = () => {
        const ts = this.topStore;
        ts.init(this.topConf).fetchRightMenu()
    }

    initTab = () => {
        const ss = this.targetSearchStore;
        ss.init(this.tabConf).fetchSearchForm(this.searchParams).then(() => ss.fetchTabs(this.tabParams)).then(this.initTable);
    }

    getTabs = () => {
        const ss = this.targetSearchStore;
        ss.fetchTabs(this.tabParams).then(this.initTable);
    }

    initTable = () => {
        this.targetTableListStore.init(this.tableConf).fetchTableList(this.tableParams);
    }

    initForm = () => {
        const exportDatas = (datas) => {
            datas.conditions && datas.conditions[0].items && this.addBtn(datas.conditions);
            this.canEdit = datas.canEdit;
        }
        let params = {};
        if (this.dataId) {
            params = { id: this.dataId }
        }
        if (this.pageDialogType == 'approvalEdit') {
            params.isManager = '1';
        }
        this.targetFormStore.init(this.formConf).fetchForm(params, exportDatas)
    }

    initDialog = (name) => {
        let conf = this.dialogConf;
        if (name) {
            conf = Object.assign({}, this.dialogConf, { title: `${this.dialogConf.title}: ${name}` });
        }
        this.targetDialogStore.init(conf).openDialog();
    }

    getDetachable = () => {
        api.getDetachable().then(res => {
            const { status, detachable } = res;
            if (status == '1') {
                this.isDetachable = (detachable == '1');
                if ( this.isDetachable) {
                    this.resetTree()
                }
            } else {
                message.error(res.message);
            }
        })
    }

    resetTree = () => {
        this.orgTreeStore.trigger();
    }

    add = () => {
        this.dataId = '';
        this.dialogType = 'add';
        this.initDialog();
        this.initForm();
    }

    edit = (id) => {
        this.dataId = id;
        this.dialogType = 'edit';
        this.initDialog();
        this.initForm();
    }

    create = () => {
        this.dataId = '';
        this.dialogType = 'create';
        this.initDialog();
        this.initForm();
    }

    remind = (id, name) => {
        this.dataId = id;
        this.dialogType = 'remainset';
        this.initDialog(name);
        this.initTab();
    }

    addRemainObj = () => {
        this.authVisible = true;
        this.dialogType = 'remainsetadd';
        this.prevDialogType = 'remainset';
        this.initForm();
    }

    delRemainObj = () => {
        this.batchDelete();
    }

    _handleSearch = () => {
        if (this.pageType == 'intercept') {
            this.getTabs();
        }else{
            this.initTable();
        }
    }

    handleSave = (type) => {
        const { validateForm } = this.targetFormStore;

        validateForm().then(() => {
            this.formSaveApi(this.formSaveParams).then(res => {
                const { status, id, name } = res;
                if (status == '1') {
                    if (type == 'saveAndProcess') {
                        this.processSensitiveWordApprove(this.dataId,i18n.label['531607']()).then(() => {
                            this.targetDialogStore.closeDialog()
                        })
                    } else {
                        message.success(res.message || i18n.message.saveSuccess())
                        this.isInitTable && this.initTable();
                        this.targetDialogStore.closeDialog();
                        if (id && name) {
                            this.targetFormStore.form.updateFields({
                              wordtype: {
                                value: id,
                                valueSpan: name,
                                valueObj: [
                                  {
                                    id,
                                    name
                                  }
                                ]
                              }
                            })
                        }
                    }

                } else {
                    message.error(res.message || i18n.message.saveFailed());
                }
            })
        })
    }

    saveAuth = (params) => {
        params = {
            ...params,
            id: this.dataId
        }
        this.formSaveApi(params).then(res => {
            const { status } = res;
            this._closeDialog();
            this.authVisible = false;
            if (status == '1') {
                message.success(i18n.message.saveSuccess());
                this.isInitTable && this.initTable();
            } else {
                message.error(res.message || i18n.message.saveFailed());
            }
        })
    }

    addBtn = (conditions) => {
        conditions.map(c => c.items.map(item => {
            const { domkey: [key] } = item;
            if (key == 'wordtype') {
                item.hasAddBtn = true;
                item.addOnClick = () => {
                    this.prevDialogType = this.dialogType;
                    this.dialogType = 'create';
                    this.create();
                };
            }
        }))
    }

    import = () => {
        const { setSourceStore, setTempletName, setImportDialogTitle, setImportType, setImportDialogVisible } = this.importCommon

        setTempletName(i18n.label.importTemplate());
        setImportDialogTitle(i18n.label['531439']());
        setImportType('sensitiveword');
        setImportDialogVisible(true);
        setSourceStore(this);
    }

    _onOperatesClick = (record, rowIndex, operate) => {
        const id = record.id,
            index = operate.index,
            pageDialogType = this.pageDialogType,
            selectedKey = this.searchStore.selectedKey;
        if (['word', 'wordType'].includes(pageDialogType)) {
            [this.edit, this.singleDel,this.log][index](id)
        }
        if (pageDialogType == 'intercept') {
            [this.singleDesensitization, this.singleDel,this.log][index](id)
        }
        if (pageDialogType == 'approval') {
            [this.singleAddToSenstiveWarehouse, this.edit, this.singleDel,this.log][index](id)
        }
        if (pageDialogType == 'wordTypeRemainset') {
            this.singleDel(id);
        }
    }

    _reRenderColumns = (columns) => {
        columns.map(c => {
            const { dataIndex } = c;
            if (dataIndex == 'word') {
                c.render = (text, record) => {
                    return <a onClick={() => this.edit(record.id)}>{text}</a>
                }
            }
            if (this.pageType == 'wordType') {
                if (dataIndex == 'wordtype') {
                    c.render = (text, record) => {
                        const { id, name,wordtype } = record;
                        return (
                            <span>
                                <a onClick={() => this.remind(id, name)}>{i18n.label['531584']()}</a>
                                { wordtype != '0' &&  <i className="icon-coms-complete" style={{color:'#4CAF50'}}/>}
                            </span>
                        )
                    }
                }
                if (dataIndex == 'name') {
                    c.render = (text, record) => {
                        return <a onClick={() => this.edit(record.id)}>{text}</a>
                    }
                }
            }
            if (this.pageType == 'intercept' && dataIndex == 'sensitivewords') {
                c.render = (text, record) => {
                    return <a onClick={() => this.edit(record.id)}>{text}</a>
                }
            }
        })
    }

    _handleTabChange = () => {
        this.initTable();
    }

    btnOnClick = (key) => {
        if (key == '1') {
            const fn = {
                'word': this.batchSetHandleWay,
                'intercept': this.batchDesensitization,
                'approval': this.batchAddToSenstiveWarehouse
            } [this.pageType];
            fn();
        }
        if (key == '2') {
            this.batchDelete();
        }
    }

    menuOnClick = () => {
        this.closePanel();
        this.initTable();
    }

    singleDel = (id) => {
        this.del(id, false);
    }

    batchDelete = () => {
        this.del(this.selectedRowIds, true);
    }

    batchSetHandleWay = () => {
        this.dialogType = 'handleWay';
        this.initDialog();
        this.initForm();
    }

    singleDesensitization = (id) => {
        this.processSensitiveWordLog(id);
    }

    batchDesensitization = () => {
        this.processSensitiveWordLog(this.selectedRowIds);
    }

    processSensitiveWordLog = (id) => {
        const getStyle = code => (code == '531605') ? { color: 'red' } : {};
        const msg = <div>{['531604','531605'].map(code => <p style={{...getStyle(code),textAlign:'center'}}>{i18n.label[code]()}</p>)}</div>
        this.targetTableListStore.showConfirm(msg).then(res => {
            const params = { ids: id, handleway: '2' };
            api.processSensitiveWordLog(params).then(res => {
                const { status } = res;
                if (status == '1') {
                    if (this.pageDialogType == 'interceptEdit') {
                        this.targetDialogStore.closeDialog();
                    }
                    this.initTable();
                    this.initTab();
                    message.success(res.message);
                } else {
                    message.error(res.message);
                }
            })
        })
    }

    singleAddToSenstiveWarehouse = (id) => {
        const msg = i18n.label['531607']();
        this.processSensitiveWordApprove(id,msg);
    }

    batchAddToSenstiveWarehouse = () => {
        const msg = i18n.label['532024']();
        this.processSensitiveWordApprove(this.selectedRowIds,msg);
    }

    processSensitiveWordApprove = (id,msg) => {
        return new Promise((resolve, reject) => {
            this.targetTableListStore.showConfirm(msg).then(res => {
                const params = { ids: id };
                api.processSensitiveWordApprove(params).then(res => {
                    const { status } = res;
                    if (status == '1') {
                        this.initTable();
                        message.success(res.message);
                        resolve();
                    } else {
                        message.error(res.message);
                        reject();
                    }
                })
            })
        })
    }

    handleOrgTreeNodeClick = () => {
        this.initTab();
    }

    del = (id, isMulti) => {
        const params = { ids: id };
        if (this.pageType == 'intercept') {
            params.handleway = '1';
        }
        if (this.pageDialogType == 'wordTypeRemainset') {
            params.id = this.dataId;
        }
        let msg;
        if (this.pageType == 'intercept') {
            msg = i18n.label['531606']();
        } else {
            msg = isMulti ? i18n.confirm.deleteSelected() : i18n.confirm.delete();
        }
        this.targetTableListStore.showConfirm(msg).then(() => {
            this.tableDelApi(params).then(res => {
                const { status } = res;
                if (status == '1') {
                    message.success(res.message);
                    this.initTable();
                } else {
                    message.error(res.message);
                }
            })
        })
    }

    closePanel = () => {
        this.targetSearchStore.setShowSearchAd(false);
    }

    _closeDialog = () => {
        if (['wordCreate', 'wordTypeRemainsetadd', 'approvalCreate'].includes(this.pageDialogType)) {
            this.dialogType = this.prevDialogType;
        }
        if (!this.targetDialogStore.visible) {
            this.dialogType = '';
        }
        if (this.pageDialogType == 'wordType') {
            this.initTable();
        }
    }

    log = (id) => {
        const logSmallType = {
            'word': '2',
            'wordType': '3',
            'intercept':'5',
            'approval': '1'
        } [this.pageType];
        const params = {
            logSmallType,
            logType: '38'
        };
        if (id) {
            params.targetId = id;
        }
        window.setLogViewProps(params);
    }

    exportExcel = () => {
        this.targetTableListStore.exportExcel();
    }

    setAuthVisible = (b) => {
        this.authVisible = b;
        this._closeDialog();
    }

    reset = () => {
        this.closePanel();
        this.orgTreeStore.id = '';
        this.orgTreeStore.type = '0';
    }

    getSearchList = () => {
        this.initTable();
    }

    @action setPageType = (type) => {
        this.pageType = type;
    }
}