/**
 * @Author: 程亮
 * @Date: 2022-06-02 09:19:37
 * @LastEditTime: 2023-09-21 18:55:33
 * @Description: 
 * @FilePath: /trunk/src4js/pc4mobx/organization/components/department/department.js
 */

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

import '../../style/common.less';
import { renderNoright } from '../../util';

import NewAndEditDialog from '../NewAndEditDialog';
import NewTableDialog from '../NewTableDialog';
import NewPopconfirm from './NewPopconfirm'

const getLabel = WeaLocaleProvider.getLabel;
const toJS = mobx.toJS;
const confirm = Modal.confirm;


@inject('department')
@observer
export default class Department extends React.Component {
    constructor(props) {
        super(props);
    }

    componentWillMount() {
    }

    componentDidMount() {
        this.init();
    }

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

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

    init() {
        const {
            department
        } = this.props;
        department.getTableInfo();
        department.getHasRight();
        department.getCopyForm();
    }

    getTopMenuBtns() {
        const {
            department
        } = this.props;
        const {
            topMenu,
            selectedRowKeys,
            selectTreeNodeInfo
        } = department;

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

        });

        return btns;
    }

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

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

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

        department.setNeDialogTitle(i18n.label.newDept());
        department.setNewVisible(true);
        department.getDeptForm();
    }

    export() {
        const {
            department
        } = this.props;

        department.exportData();
    
    }

    //联查岗位
    select(id) {
        const {
            department
        } = this.props;

        department.setNeDialogTitle(i18n.button.associateJob());
        department.setVisible(true);
        department.setDialogLoadingStatus(true);
        department.getPostionTable(id);
    }


    //合并
    merge(id) {
        const {
            department
        } = this.props;

        department.setNeDialogTitle(i18n.label.mergeDept());
        department.setConfirmVisible(true);
        department.setIds(id);
        department.setIsMerge(true);
        department.getMergeForm(id);
    }

    //转移
    transfer(id) {
        const {
            department
        } = this.props;
        department.setNeDialogTitle(i18n.label.transferDept());
        department.setConfirmVisible(true);
        department.setIds(id);
        department.setIsMerge(false);
        department.getTransferForm(id);

    }

    //查看
    view(id) {
        window.open(`/spa/organization/static/index.html#/main/organization/departmentExtend/${id}`, "_blank")
    }

    copy(id) {
        const {
            department
        } = this.props;
        const {
            selectedRowKeys
        } = department;

        let keys = id == undefined ? toJS(selectedRowKeys).toString() : id;
        department.setIds(keys);
        confirm({
            width:'550px',
            title: i18n.confirm.defaultTitle(),
            content: this.getCopyForm(),
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                department.copy();
            },
            onCancel() {
                return false;
            },
        });
    }

    getCopyForm() {
        const {
            department
        } = this.props;
        const {
            copyCondition,
            form2,
        } = department;
        let formParams = form2.getFormParams();
        const {
            isFormInit
        } = form2;
        let arr = [];
        isFormInit && copyCondition.map(c => {
            c.items.map((field, index) => {
                arr.push(
                    <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>
                )
            })
        })
        return arr;
    }


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

    batchDelete() {
        const {
            department
        } = this.props;
        const {
            selectedRowKeys
        } = department;
        let keys = toJS(selectedRowKeys).toString();
        department.setIds(keys);
        this.showConfirm('batchDel');
    }
    showConfirm(v) {
        let _this = this;
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: (v == 'del') ? i18n.confirm.delete() : i18n.confirm.batchDeleteConfirm(),
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                _this.onOk();
            },
            onCancel() {
                return false;
            },
        });
    }
    onOk() {
        const {
            department
        } = this.props;
        department.delete();
    }


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

        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 {
            department
        } = this.props;
        const {
            isPanelShow
        } = department;

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

    updateForbiddenTag(checked, id) {
        const {
            department
        } = this.props;
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: (checked == true) ? i18n.confirm.enableTag() : i18n.confirm.forbiddenTag(),
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                department.updateForbiddenTag(checked, id);
            },
            onCancel() {
                return false;
            },
        });
    }



    onSearchChange(val) {
        const {
            department
        } = this.props;
        const {
            form
        } = department;

        department.setDepartmentName(val);
        !this.isEmptyObject(form.getFormParams()) && department.updateFields(val);
    }

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



    reRenderColumns(columns) {
        const {
            department
        } = this.props;
        let _this = this;
        columns.forEach((c, index) => {
            if (c.dataIndex == 'canceled') {
                c.render = function (text, record) {
                    return <Switch checked={record.canceled == "0" ? true : false} onChange={checked => _this.updateForbiddenTag(checked, record.id)} />
                }
            };
            if (c.dataIndex == 'departmentMark') {
                c.className = "wea-table-indent"
                c.render = function (text, record) {
                    return <a href='javascript:void(0);' onClick={() => {
                        window.open(`/spa/organization/static/index.html#/main/organization/departmentExtend/${record.id}`, "_blank")
                    }}>{text}</a>
                }
            }
            if (c.dataIndex == 'operate') {
                c.className = "wea-table-operates"
                c.width = 80
                c.render = function (text, record) {
                    const menu = (
                        <Menu>
                            <Menu.Item key="0">
                                <a href='javascript:void(0);' onClick={() => {
                                    _this.view(record.id)
                                }}>{i18n.button.view()}</a>
                            </Menu.Item>
                            <Menu.Item key="1" disabled={record.isUsed === 0 ? false : true} style={record.isUsed === 0 ? { display: 'block' } : { display: 'none' }}>
                                <a href='javascript:void(0);' onClick={() => {
                                    _this.doDel(record.id)
                                }}>{i18n.button.delete()}</a>
                            </Menu.Item>
                            <Menu.Item key="2">
                                <a href='javascript:void(0);' onClick={() => {
                                    _this.merge(record.id)
                                }}>{i18n.button.merge()}</a>
                            </Menu.Item>
                            <Menu.Item key="3">
                                <a href='javascript:void(0);' onClick={() => {
                                    _this.transfer(record.id)
                                }}>{i18n.button.transfer()}</a>
                            </Menu.Item>
                            <Menu.Item key="4">
                                <a href='javascript:void(0);' onClick={() => {
                                    _this.select(record.id)
                                }}>{i18n.button.associateJob()}</a>
                            </Menu.Item>
                            <Menu.Item key="5">
                                <a href='javascript:void(0);' onClick={() => {
                                    _this.copy(record.id)
                                }}>{i18n.button.copy()}</a>
                            </Menu.Item>
                            {/* <Menu.Item key="6">
                                <a href='javascript:void(0);' onClick={() => { _this.version(record) }}>另存为版本</a>
                            </Menu.Item> */}
                        </Menu>
                    )
                    return <Dropdown overlay={menu}>
                        <i class="icon-coms-more" />
                    </Dropdown>
                }
            }
        })
        return columns;
    }


    doDel(id) {
        const {
            department
        } = this.props;
        department.setIds(id);
        this.showConfirm('del');
    }


    handleSave() {
        const {
            department
        } = this.props;
        department.setSaveAndSetting(false);
        department.save();
    }

    handleSaveAndSetting() {
        const {
            department
        } = this.props;
        department.setSaveAndSetting(true);
        department.save();
    }

    PopconfirmSave() {
        const {
            department
        } = this.props;
        const { isMerge } = department;
        isMerge && department.merge();
        !isMerge && department.transfer();
    }

    getTabBtn() {
        const {
            department
        } = this.props;
        const {
            form
        } = department;

        const btn = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bx87i8`} type="primary" onClick={() => {
                department.setCurrent(1); department.setPageSize(10); department.getTableInfo(); department.setPanelStatus(false)
            }}>{i18n.button.search()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@218ju6`} onClick={() => form.reset()}>{i18n.button.reset()}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5u9mfz`} onClick={() => department.setPanelStatus(false)}>{i18n.button.cancel()}</Button>),
        ];

        return btn;
    }

    getPanelComponents() {
        const {
            department
        } = this.props;
        const {
            searchCondition,
            form,
            searchConditionLoading
        } = department;

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

        isFormInit && searchCondition.map(c => {
            c.items.map((field, index) => {
                arr.push(<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4cc308@${index}`} span={(index % 2 == 0) ? 10 : 11} offset={1}>
                    <div style={{ marginTop: 20 }}>
                        <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={form} formParams={formParams} />}
                        </WeaFormItem>
                    </div>
                </Col>)
            })
        })

        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 <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ppeb6z`} onKeyDown={(e) => {
                if (e.keyCode == 13 && e.target.tagName === "INPUT") {
                    department.getTableInfo();
                    department.setPanelStatus(false)
                }
            }}>{arr}</Row>
        }

    }

    //非空判断
    isEmptyObject(obj) {
        for (let key in obj) {
            return false;
        }
        return true;
    }

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

        let tree = (
            <WeaOrgTree ecId={`${this && this.props && this.props.ecId || ''}_WeaOrgTree@dhi1ro`}
                ref='WeaOrgTree'
                dataUrl={"/api/bs/hrmorganization/dept/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 {
            department
        } = this.props;
        const {
            form,
            companysId
        } = department;
        const type = event.node.props.type || '0';
        const id = event.node.props.id || '';
        let params = {};
        form.resetConditionValue();
        department.setPanelStatus(false)
        // department.tabkey = 'default_3';
        department.nodeType = type;
        if (type == '0') {
            params['virtualtype'] = companysId;
        }
        if (type == '1') {
            params['subcompanyid1'] = id;
        }
        if (type == '2') {
            params['departmentid'] = id;
        }
        department.doSearch(params);
    }



    render() {

        const {
            department
        } = this.props;
        const {
            isPanelShow, departmentName, conditionNum, visible, condition, form,
            tableStore, dataSource, columns, loading, date, nEdialogTitle, dialogLoading,
            form1, isEdit, newVisible, jobDataSource, jobColumns, selectedRowKeys, total, current, pageSize, init,
            defaultShowLeft, confirmVisible, confirmLoading, postionDataSource, postionColumns, isMerge, hasRight,exSpinning
        } = department;

        if (hasRight === false) {
            return renderNoright();
        }

        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            type: "checkbox",
            onChange(selectedRowKeys, selectedRows) {
                department.setSelectedRowKeys(selectedRowKeys);
            },
            getCheckboxProps: record => ({
                disabled: record.isUsed === 1,    // 配置无法勾选的列
            }),
        };

        const pagination = {
            current: current,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            onShowSizeChange(current, pageSize) {
            },
            onChange(current) {
            },
            showTotal(total) {
                return `${i18n.label.total()} ${total} ${i18n.label.items()}`
            }
        };


        return (
            hasRight && <div ref='page' style={{ height: '100%' }} className = 'organization-scrollable-table'>
                <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.deptManage()}
                        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(form.getFormParams()) ? departmentName : form.getFormParams().departmentName}
                                setShowSearchAd={bool => department.setPanelStatus(bool)}
                                hideSearchAd={() => department.setPanelStatus(false)}
                                searchsAd={isPanelShow ? this.getPanelComponents() : <div></div>}
                                advanceHeight={Math.ceil(conditionNum / 2) * 52 + 20}
                                hasMask={false}
                                buttonsAd={this.getTabBtn()}
                                onSearch={() => {
                                    department.setCurrent(1);
                                    department.setPageSize(10);
                                    department.getTableInfo()
                                }}
                                onSearchChange={val => this.onSearchChange(val)}
                            />
                            <Spin size="large" spinning={exSpinning} tip={getLabel(547647,'正在导出请稍候....')} className="hrm-loading-center-small"/>
                            {
                                init ? <div className='hrm-new-weatable-spin'>
                                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@4ygl4a`} spinning={init}></Spin>
                                </div> :
                                    <WeaTable rowKey={record => record.id} ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@pgmg3x`}
                                        loading={loading}
                                        dataSource={dataSource} childrenColumnName="children"
                                        columns={this.reRenderColumns(columns)}
                                        rowSelection={rowSelection}
                                        pagination={pagination}
                                        onChange={(pagination, filters, sorter) => {
                                            department.setSortParams(sorter);
                                            department.setCurrent(pagination.current);
                                            department.setPageSize(pagination.pageSize);
                                            department.getTableInfo();
                                        }}
                                        indentSize={15}
                                    />
                            }
                        </WeaLeftRightLayout>
                    </WeaTop>
                </WeaRightMenu>
                <NewTableDialog ecId={`${this && this.props && this.props.ecId || ''}_NewTableDialog@q4rrwm`}
                    title={nEdialogTitle}
                    visible={visible}
                    loading={dialogLoading}
                    height={400}
                    dataSource={postionDataSource} //联查岗位数据
                    columns={postionColumns}
                    onCancel={() => department.setVisible(false)}
                />
                <NewAndEditDialog ecId={`${this && this.props && this.props.ecId || ''}_NewAndEditDialog@q4rrwm`}
                    title={nEdialogTitle}
                    visible={newVisible}
                    condition={toJS(condition)}
                    form={form1}
                    isFormInit={form1.isFormInit}
                    loading={dialogLoading}
                    isEdit={isEdit}
                    height={400}
                    conditionLen={1}
                    save={() => this.handleSave()}
                    onCancel={() => department.setNewVisible(false)}
                    saveAndSetting={() => this.handleSaveAndSetting()}
                    moduleName={"department"}
                    bindChangeEnvent={val => department.updateConditions(val)}
                >
                </NewAndEditDialog>
                <NewPopconfirm ecId={`${this && this.props && this.props.ecId || ''}_NewPopconfirm@q4rrwm`}
                    title={nEdialogTitle}
                    visible={confirmVisible}
                    condition={toJS(condition)}
                    form={form1}
                    isFormInit={form1.isFormInit}
                    loading={confirmLoading}
                    height={150}
                    width={650}
                    isMerge={isMerge}
                    defaultValue={"0"}
                    save={() => this.PopconfirmSave()}
                    onCancel={() => department.setConfirmVisible(false)}
                />
            </div>
        )
    }
}