import React from 'react'
import * as mobx from 'mobx'
import {
    inject,
    observer,
} from 'mobx-react'
import {
    WeaTop,
    WeaTab,
    WeaInput,
    WeaFormItem,
    WeaRightMenu,
    WeaLeftRightLayout,
    WeaOrgTree,
    WeaDropdown,
    WeaSelect,
    WeaSearchGroup,
    WeaLocaleProvider
} from 'ecCom'
import {
    Row,
    Col,
    Spin,
    Modal,
    Button,
    message,
    Switch,
    Select,
    Menu, Dropdown, Icon
} from 'antd'
import {
    WeaSwitch,
    WeaTableNew
} from 'comsMobx'
import {
    i18n
} from '../../public/i18n';


import NewAndEditDialog from '../NewAndEditDialog';
import { renderNoright } from '../../util';
import DatasImport from '../import/datasImport';
import SearchCustomDialog from './SearchCustomDialog';
import NewWeaTableEditDialog from '../NewWeaTableEditDialog';
import GroupList from './GroupList';

const toJS = mobx.toJS;
const confirm = Modal.confirm;
const WeaTable = WeaTableNew.WeaTable;
const { ButtonSelect } = WeaDropdown;
const getLabel = WeaLocaleProvider.getLabel;

const viewDepartment = (id) => {
    window.open(`/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=department&id=${id}`);
  }
  
const viewSubCompany = (id) => {
window.open(`/spa/hrm/engine.html#/hrmengine/organization?showTree=false&isView=1&type=subcompany&id=${id}`);
}

window.viewDepartment = viewDepartment;
window.viewSubCompany = viewSubCompany;

@inject('resource')
@inject('datasImport')
@observer
export default class Resource extends React.Component {
    constructor(props) {
        super(props);
    }

    componentWillMount() {
    }

    componentDidMount() {
        this.init();
    }

    componentWillReceiveProps(nextProps) {
        const {
            resource
        } = this.props;

        if (this.props.location.key !== nextProps.location.key) {
            this.init();
        }
    }

    init() {
        const {
            resource
        } = this.props;

        resource.getHasRight();
        //1.获取快捷搜索内容
        resource.getQuickSearchCondition();
        let { hash } = window.location;
        hash = hash.split("?")[1].split("&");
        if (hash.length >= 2) {
            let params = {};
            let arr = hash[0].split("=");
            params[arr[0]] = arr[1];
            resource.doSearch(params);
        } else {
            resource.getTableInfo();
        }
    }

    //左侧树
    getTree = () => {
        const {
            resource
        } = this.props;
        const {
            companysId,
        } = resource

        let tree = (
            <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@dhi1ro`}
                ref='WeaOrgTree'
                dataUrl={"/api/bs/hrmorganization/hrmresource/getSearchTree"}
                loading
                needSearch
                noCache={true}
                needDropMenu={false}
                //onSelect={this.selectVirtual}  //组织维度回调函数
                isLoadSubDepartment={true}
                topPrefix={'hrmSearch'}
                companysId={companysId}
                inputLeftDom={`<b>${i18n.label.organization()}</b>`}
                treeNodeClick={this.treeNodeClick}
                expandAllChildrenOnSearch={true}
                renderNode={item => this.renderNode(item)}
            />
        )

        return tree;
    }

    renderNode(item) {
        return <div className='text-elli' title={item.name}>
            <i className={item.icon} style={{ marginRight: '5px' }}></i>
            {item.name}
            {item.canceled && <span style={{ color: 'red' }}>({i18n.label.forbidden()})</span>}
        </div>
    }

    treeNodeClick = (event, ids, nodeids, nodes) => {
        const {
            resource
        } = this.props;
        const {
            form2,
            companysId
        } = resource;
        const type = event.node.props.type || '0';
        const id = event.node.props.id || '';
        let params = {};
        form2.resetForm();
        resource.setPanelStatus(false)
        // resource.tabkey = 'default_3';
        resource.nodeType = type;
        if (type == '0') {
            params['virtualtype'] = companysId;
        }
        if (type == '1') {
            params['companyId'] = id;
        }
        if (type == '2') {
            params['departmentId'] = id;
        }
        if (type == '3') {
            params['jobTitle'] = id;
        }
        resource.doSearch(params);
    }

    getTopMenuBtns() {
        const {
            resource
        } = this.props;
        const {
            topMenu,
            tableStore
        } = resource;

        let btns = [];
        topMenu.map((item, i) => {
            if (item.menuFun !== 'batchDelete') {
                btns.push(<Button type='primary' onClick={() => this.handleClick(item)}>{item.menuName}</Button>);
            } else {
                btns.push(<Button type='primary' onClick={() => this.handleClick(item)} disabled={tableStore.selectedRowKeysAllPages.length > 0 ? false : true} >{item.menuName}</Button>);
            }

        });

        const datas = [
            {
                key: "1", show: (<span>{i18n.button.allExport()}</span>), text: `${i18n.button.allExport()}`, selected: true
            },

            {
                key: "2", show: (<span>{i18n.button.batchExport()}</span>), text: `${i18n.button.batchExport()}`
            }
        ];
        btns.push(<ButtonSelect
            datas={datas}
            btnOnClick={key => {
                if (key == "1") {
                    tableStore.selectedRowKeysAllPages = [];
                    resource.export();
                }
                if (key == "2") {
                    tableStore.selectedRowKeysAllPages.length > 0 ? resource.export() : message.error(`${i18n.message.checkExport()}`)
                }
            }}
            menuOnClick={(key, e) => key == '1' ? tableStore.selectedRowKeysAllPages = [] : ''}
        />)

        return btns;
    }

    handleClick(item) {
        const {
            resource
        } = this.props;
        const {
            isPanelShow
        } = resource;

        isPanelShow && resource.setPanelStatus(false);
        this[item.menuFun] && this[item.menuFun]();
    }


    log = () => {
        window.setLogViewProp({
            logMoudleType: 11,
            keys: new Date().getTime(),
        });
    }

    new() {
        const {
            resource
        } = this.props;

        // resource.setNeDialogTitle(i18n.label.newPeople());
        // resource.setIsNew(true);
        // resource.setVisible(true);
        // resource.getForm();
        window.open("/spa/hrm/index_mobx.html#/main/hrm/add", "_blank")
    }

    // import() {
    //     const {
    //         datasImport
    //     } = this.props;
    //     datasImport.visible = true;
    //     datasImport.title = i18n.button.importResource();
    //     datasImport.importType = 'resource';
    //     datasImport.getImportForm();
    // }

    getDropMenuDatas() {
        const {
            resource
        } = this.props;
        const {
            rightMenu
        } = resource;

        let menus = [];
        toJS(rightMenu).map((item, index) => {
            let obj = {
                key: item.menuFun,
                icon: <i className={`${item.menuIcon}`} />,
                content: item.menuName,
            }
            if (item.menuFun == 'collection' || item.menuFun == 'help' || item.menuFun == 'pageAddress') {
                obj.disabled = true;
            }
            menus.push(obj);
        })
        return menus;
    }

    handleMenuClick(key) {
        const {
            resource
        } = this.props;
        const {
            isPanelShow
        } = resource;

        isPanelShow && resource.setPanelStatus(false);
        this[key] && this[key]();
    }

    //列定制
    customization() {
        const {
            resource
        } = this.props;

        resource.openCustomDialog();
    }

    //存为模板
    saveTemplate() {
        const {
            resource
        } = this.props, {
            searchTemplateName
        } = resource;

        confirm({
            title: getLabel(547548,'存为模板'),
            content:
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@62kt85`}
                    label= {getLabel(547654,'搜索模板名称')}
                    labelCol={{ span: 10 }}
                    wrapperCol={{ span: 14 }}>
                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@j9bmvw`} viewAttr="3" value={searchTemplateName} {...window.inputType} onChange={v => resource.searchTemplateName = v} />
                </WeaFormItem>,
            okText: i18n.button.save(),
            cancelText: i18n.button.cancel(),
            onOk() {
                resource.saveTemplate();
            },
            onCancel() {
                return false;
            },
        });
    }

    getTabBtn() {
        const {
            resource
        } = this.props;
        const {
            form2
        } = resource;

        const btn = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bx87i8`} type="primary" onClick={() => {
                resource.isBaseValue = false;
                resource.selectTreeNodeInfo = {}; resource.setPanelStatus(false);resource.getTableInfo(); 
            }}>{i18n.button.search()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@218ju6`} type="primary" onClick={() => this.saveTemplate()}>{i18n.button.saveTemplate()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@218ju7`} type="primary" onClick={() => resource.openSearchDialog()}>{i18n.button.conditionSet()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@218ju8`} onClick={() => form2.reset()}>{i18n.button.reset()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5u9mfz`} onClick={() => resource.setPanelStatus(false)}>{i18n.button.cancel()}</Button>),
        ];

        return btn;
    }

    custom = () => {
        const {
            resource
        } = this.props, {
            tableStore,
        } = resource;

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

    onSearchChange(val) {
        const {
            resource
        } = this.props;
        const {
            form2
        } = resource;

        resource.setLastName(val);
        !this.isEmptyObject(form2.getFormParams()) && resource.updateFields(val);
    }

    reRenderColumns(columns) {
        let _this = this;
        columns.forEach((c, index) => {
            c.className = "wea-table-indent"
            if (c.dataIndex == 'lastname') {
                c.render = function (text, record) {
                    return <a href='javascript:void(0);' onClick={() => {
                        window.open(`/spa/organization/static/index.html#/main/organization/resourceCard/${record.id}`);
                    }}>{text}</a>
                }
            }
        })
    }


    onOperatesClick(record, rowIndex, operate) {
        const {
            index
        } = operate;
        (index == '0') && this.view(record.randomFieldId);
        (index == '1') && this.version(record);
    }

    view(id) {
        window.open(`/spa/organization/static/index.html#/main/organization/resourceCard/${id}`);
    }

    version(record) {
        const {
            resource
        } = this.props;
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: `确认将{${record.lastname}}存为新版本？`,
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                resource.version(record.id);
            },
            onCancel() {
                return false;
            },
        });
    }

    handleSave() {
        const {
            resource
        } = this.props;
        const {
            isNew
        } = resource;

        isNew && resource.save();
        !isNew && resource.edit();
    }


    getPanelComponents() {
        const {
            resource
        } = this.props;
        const {
            defaultCondition,
            form2,
            searchConditionLoading,
            templates,
            searchTemplateId
        } = resource;

        let arr = [];
        let formParams = form2.getFormParams();
        const {
            isFormInit
        } = form2;

        arr.push(<Row style={{ marginTop: 20 }}>
            <Col offset={1} span={2}><span style={{ "lineHeight": "30px", "color": "red" }}>{getLabel(547655,'模板选择')}</span></Col>
            <Col span={6} offset={1}>
                <WeaSelect
                    style={{ width: "100%" }}
                    options={templates}
                    value={searchTemplateId}
                    onChange={v => {
                        resource.changeSearchTemplate(v)
                    }}
                />
            </Col>
            <Col offset={1} span={2}><Button onClick={() => resource.deleteSearchTemplate()}>{getLabel(547656,'删除模板	')}</Button></Col>
        </Row>)

        isFormInit && templates.length > 0 && defaultCondition.map((c, i) => {
            let _arr = [];
            c.items.map((field, index) => {
                _arr.push({
                    com: (
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@u6ex85@${index}`}
                            label={`${field.label}`}
                            labelCol={{ span: `${field.labelcol}` }}
                            wrapperCol={{ span: `${field.fieldcol}` }}>
                            {<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@p7d3td@${index}`} fieldConfig={field} form={form2} formParams={formParams} />}
                        </WeaFormItem>
                    ),
                })
            })
      
    
            arr.push(<WeaSearchGroup className='organization-search' ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@qaih5l@${i}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={_arr} col={2} />)
        })


        if (searchConditionLoading) {
            return (
                <div className='hrm-loading-center-small' style={{ top: '25%' }}>
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@lbktzb`} spinning={searchConditionLoading}></Spin>
                </div>
            )
        } else {
            return <div onKeyDown={(e) => {
                if (e.keyCode == 13 && e.target.tagName === "INPUT") {
                    rankScheme.getTableInfo();
                    rankScheme.setPanelStatus(false)
                }
            }}>{arr}</div>
        }

    }

    isEmptyObject(obj) {
        for (let key in obj) {
            return false;
        }
        return true;
    }

    getTableWidth = (columns) => {
        const columnLength = columns.filter((col)=>col.display === 'true').length;
        if(columnLength>10){
          return columnLength*100;
        }else{
          return '100%' 
        }
      }


    render() {

        const {
            resource: store
        } = this.props;
        const {
            isPanelShow, form2, lastName, conditionNum, tableStore, nEdialogTitle, visible, condition,
            form, dialogLoading, isEdit, date, hasRight, defaultShowLeft,enable,exSpinning
        } = store;

        if (hasRight === false) {
            return renderNoright();
        }
        
        return (
            hasRight && <div ref='page' style={{ height: '100%' }}>
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@k6oc4u`}
                    datas={this.getDropMenuDatas()}
                    onClick={key => this.handleMenuClick(key)}
                >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@bj98s7`}
                        title={i18n.label.resourceMange()}
                        icon={<i className='icon-coms-hrm' />}
                        iconBgcolor='#217346'
                        loading={true}
                        buttons={this.getTopMenuBtns()}
                        showDropIcon={true}
                        dropMenuDatas={this.getDropMenuDatas()}
                        onDropMenuClick={(e) => this.handleMenuClick(e)}
                    >
                        <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@7muhhb`} isNew={true} showLeft={defaultShowLeft} leftCom={this.getTree()}>
                            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@9c3zts`}
                                searchType={['base', 'advanced']}
                                showSearchAd={isPanelShow}
                                searchsBaseValue={this.isEmptyObject(form2.getFormParams()) ? lastName : form2.getFormParams()["-1_hrm_lastname"]}
                                searchsBasePlaceHolder=''
                                setShowSearchAd={bool => store.setPanelStatus(bool)}
                                hideSearchAd={() => store.setPanelStatus(false)}
                                searchsAd={isPanelShow ? this.getPanelComponents() : <div></div>}
                                advanceHeight={Math.ceil(conditionNum / 2) * 52 + 20}
                                hasMask={false}
                                buttonsAd={this.getTabBtn()}
                                onSearch={() => {
                                    store.isBaseValue = true;
                                    store.hideRadioGroup();store.getTableInfo();
                                    }}
                                onSearchChange={val => this.onSearchChange(val)}
                            />
                            <Spin size="large" spinning={exSpinning} tip={getLabel(547647,'正在导出请稍候....')} className="hrm-loading-center-small"/>
                            {enable && <GroupList ecId={`${this && this.props && this.props.ecId || ''}_GroupList@2le78y`} store={store} />}
                            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@pgmg3x`}
                                comsWeaTableStore={tableStore}
                                hasOrder={true}
                                needScroll={true}
                                getColumns={c => this.reRenderColumns(c)}
                                onOperatesClick={(record, index, operate) => this.onOperatesClick(record, index, operate)}
                                tableWidth={this.getTableWidth}
                            />
                        </WeaLeftRightLayout>
                    </WeaTop>
                </WeaRightMenu>
                <NewAndEditDialog ecId={`${this && this.props && this.props.ecId || ''}_NewAndEditDialog@q4rrwm`}
                    title={nEdialogTitle}
                    visible={visible}
                    condition={toJS(condition)}
                    form={form}
                    isFormInit={form.isFormInit}
                    loading={dialogLoading}
                    isEdit={isEdit}
                    height={400}
                    conditionLen={2}
                    save={() => this.handleSave()}
                    onCancel={() => resource.setVisible(false)}
                />
                <DatasImport ecId={`${this && this.props && this.props.ecId || ''}_DatasImport@q4rrwm`} />
                <SearchCustomDialog ecId={`${this && this.props && this.props.ecId || ''}_SearchCustomDialog@q4rrwm`}
                    store={store} />
                <NewWeaTableEditDialog ecId={`${this && this.props && this.props.ecId || ''}_NewWeaTableEditDialog@q4rrwm`}
                    store={store} />
            </div>
        )
    }
}