/**
 * @Author: 程亮
 * @Date: 2022-05-26 14:05:59
 * @LastEditTime: 2023-08-14 11:39:45
 * @Description: 
 * @FilePath: /trunk/src4js/pc4mobx/organization/components/job/Job.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,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 NewAndEditDialog from '../NewAndEditDialog';
import NewWeaTableDialog from '../NewWeaTableDialog';
import { renderNoright } from '../../util';

const getLabel = WeaLocaleProvider.getLabel;


const toJS = mobx.toJS;
const confirm = Modal.confirm;
//const WeaTable = WeaTableNew.WeaTable


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

    componentWillMount() {
    }

    componentDidMount() {
        this.init();
    }

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

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

    init() {
        const {
            job
        } = this.props;
        job.initData();
    }

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

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

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

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

        job.setNeDialogTitle(i18n.label.newPost());
        job.setNewVisible(true);
        job.getJobForm();
    }


    refresh() {
        const {
            job
        } = this.props;

        job.refresh();
    }


    //联查人员
    select(id) {
        const {
            job
        } = this.props;

        job.setNeDialogTitle(getLabel(547609,'联查人员'));
        job.setVisible(true);
        job.getHrmTable(id);
    }

    merge(id) {
        const {
            job
        } = this.props;
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: this.getCopyForm({ isCopy: false }),
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                job.merge(id)
            },
            onCancel() {
                return false;
            },
        });
    }


    copy(id) {
        const {
            job
        } = this.props;
        const {
            selectedRowKeys,
        } = job;
        let keys = id == undefined ? toJS(selectedRowKeys).toString() : id;
        job.setIds(keys);
        confirm({
            title: i18n.confirm.defaultTitle(),
            content: this.getCopyForm({ isCopy: true }),
            okText: i18n.button.ok(),
            cancelText: i18n.button.cancel(),
            onOk() {
                job.copy()
            },
            onCancel() {
                return false;
            },
        });
    }

    getCopyForm(params) {
        const {
            job
        } = this.props;
        const {
            copyCondition,
            mergeCondition,
            form2,
        } = job;
        params.isCopy ? form2.initFormFields(copyCondition) : form2.initFormFields(mergeCondition);
        let formParams = form2.getFormParams();
        let condition = params.isCopy ? copyCondition : mergeCondition;
        const {
            isFormInit
        } = form2;
        let arr = [];
        isFormInit && condition.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;
    }

    batchDelete() {
        const {
            job
        } = this.props;
        const {
            selectedRowKeys
        } = job;
        let keys = toJS(selectedRowKeys).toString();
        job.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 {
            job
        } = this.props;
        job.delete();
    }


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

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

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

    updateForbiddenTag(checked, id) {
        const {
            job
        } = 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() {
                job.updateForbiddenTag(checked, id);
            },
            onCancel() {
                return false;
            },
        });
    }



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

        job.setJobName(val);
        !this.isEmptyObject(form.getFormParams()) && job.updateFields(val);
    }


    reRenderColumns(columns) {
        const {
            job
        } = this.props;
        let _this = this;
        columns.forEach((c, index) => {
            if (c.dataIndex == 'forbiddenTag') {
                c.render = function (text, record) {
                    return <Switch checked={record.forbiddenTag == "0" ? true : false} onChange={checked => _this.updateForbiddenTag(checked, record.id)} />
                }
            };
            if (c.dataIndex == 'jobTitleName') {
                c.render = function (text, record) {
                    return <a href='javascript:void(0);' onClick={() => {
                        window.open(`/spa/organization/static/index.html#/main/organization/jobExtend/${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">
                                <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.select(record.id)
                                }}>{i18n.button.joinPerson()}</a>
                            </Menu.Item>
                            {/* <Menu.Item key="3">
                                <a href='javascript:void(0);' onClick={() => { _this.merge(record.id) }}>合并</a>
                            </Menu.Item>
                            <Menu.Item key="4">
                                <a href='javascript:void(0);' onClick={() => { _this.copy(record.id) }}>复制</a>
                            </Menu.Item> */}
                        </Menu>
                    )
                    return <Dropdown overlay={menu}>
                        <i class="icon-coms-more" />
                    </Dropdown>
                }
            }
        })
        return columns;
    }


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

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


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

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

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

        const btn = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bx87i8`} type="primary" onClick={() => {
                job.setCurrent(1); job.setPageSize(10); job.getTableInfo(); job.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={() => job.setPanelStatus(false)}>{i18n.button.cancel()}</Button>),
        ];

        return btn;
    }

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

        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") {
                    job.getTableInfo();
                    job.setPanelStatus(false)
                }
            }}>{arr}</Row>
        }

    }

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

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

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


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



    render() {

        const {
            job
        } = this.props;
        const {
            isPanelShow, jobTitleName, conditionNum, visible, condition, form,
            tableStore, dataSource, columns, loading, date, nEdialogTitle, dialogLoading,
            form1, isEdit, newVisible, selectedRowKeys, total, current, pageSize, init,
            defaultShowLeft, form2, hasRight, jobtitleVisible
        } = job;

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


        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onChange(selectedRowKeys, selectedRows) {
                job.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.jobName()}
                        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()) ? jobTitleName : form.getFormParams().jobTitleName}
                                setShowSearchAd={bool => job.setPanelStatus(bool)}
                                hideSearchAd={() => job.setPanelStatus(false)}
                                searchsAd={isPanelShow ? this.getPanelComponents() : <div></div>}
                                advanceHeight={Math.ceil(conditionNum / 2) * 52 + 20}
                                hasMask={false}
                                buttonsAd={this.getTabBtn()}
                                onSearch={() => {
                                    job.setCurrent(1);
                                    job.setPageSize(10);
                                    job.getTableInfo()
                                }}
                                onSearchChange={val => this.onSearchChange(val)}
                            />
                            {
                                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) => {
                                            job.setSortParams(sorter);
                                            job.setCurrent(pagination.current);
                                            job.setPageSize(pagination.pageSize);
                                            job.getTableInfo();
                                        }}
                                        indentSize={15}
                                    />
                            }
                        </WeaLeftRightLayout>
                    </WeaTop>
                </WeaRightMenu>
                <NewWeaTableDialog ecId={`${this && this.props && this.props.ecId || ''}_NewTableDialog@q4rrwm`}
                    title={nEdialogTitle}
                    visible={visible}
                    height={400}
                    tableStore={tableStore}
                    onCancel={() => job.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={2}
                    save={() => this.handleSave()}
                    onCancel={() => job.setNewVisible(false)}
                    saveAndSetting={() => this.handleSaveAndSetting()}
                    moduleName={"job"}
                />
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@fw8u8f`}
                    onCancel={() => job.jobtitleVisible = false}
                    icon='icon-coms-hrm'
                    iconBgcolor='#217346'
                    title={"添加岗位"}
                    hasScroll={true}
                    callback={
                        datas => {
                            const {
                                id,
                                jobtitlemark
                            } = datas;

                            form1.updateFields({
                                ec_jobTitle: {
                                    value: id,
                                    valueSpan: jobtitlemark,
                                    valueObj: [{
                                        id,
                                        name: jobtitlemark
                                    }]
                                }
                            });

                            job.jobtitleVisible = false;

                        }
                    }
                    url={'/spa/hrm/engine.html#/hrmengine/posts?type=0'}
                    visible={jobtitleVisible}
                    style={{ width: 600, height: 500 }}
                />
            </div>
        )
    }
}