import React from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Spin, Icon } from 'antd'
import isEmpty from 'lodash/isEmpty'
import { WeaDialog, WeaSearchGroup, WeaTools, WeaNewScroll, WeaFormItem,WeaDialogFooter } from 'ecCom';
import { WeaSwitch } from 'comsMobx'
import UploadAvatar from '../../../../pc4public/hrm/uploadAvatar'
const getKey = WeaTools.getKey;
import * as mobx from 'mobx';
import { i18n } from '../../public/i18n';
import { AttachToNumberField } from '../../../../pc4backstage/hrmengine/util/index.js'
import {addContentPath} from '../../util/index.js'
const verificationCode = '/weaver/weaver.file.MakeValidateCode?isView=1&validatetype=0&validatenum=4&seriesnum_=';

@inject('hrmAdd')
@observer
class Simple extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            time: new Date().getTime(),
        }
        this.deptInfo=null;
    }

    componentWillMount() {
      const {location,hrmAdd } = this.props;
      if (location && location.query && location.query.name) {
        hrmAdd.isUsedAsSingle = true;
        this.deptInfo = location.query;
      }
    }

    componentWillReceiveProps (nextProps) {
        const { hrmAdd } = this.props;
        const { conditionInfo } = hrmAdd;
        if ('visible' in nextProps && this.props.visible !== nextProps.visible) {
            if (nextProps.visible) {
                if (isEmpty(conditionInfo)) this.init();
                hrmAdd.updateScroll = true;
                hrmAdd.canSave = true;
            } else {
                hrmAdd.conditionInfo = [];
            }
        }
    }
    componentDidUpdate () {
        const { hrmAdd } = this.props;
        const { updateScroll,formSimple } = hrmAdd;
        if (updateScroll) {
            if (this.refs.scrollBar) {
                setTimeout(() => {
                    this.refs.scrollBar.scrollerToTop();
                }, 0);
            }
            hrmAdd.updateScroll = false;
        }
        setTimeout(() => {
            $(".input-tip").attr("title", $(".input-tip").text())
        }, 0)

        if (this.deptInfo) {
             const {id,name}= this.deptInfo;
            formSimple.updateFields({
                departmentid:{
                     value: id,
                    valueSpan: name,
                    valueObj: [
                      {
                        id,
                        name
                      }
                    ]
                }
            })
        }
    }
    componentDidMount () {
        this.init();
        console.log(self.frameElement);
    }

    init = () => {
        const { hrmAdd } = this.props;
        hrmAdd.getHrmResourceAddForm({ 'type': 'simple' });
    }

    save = () => {
        const { hrmAdd } = this.props;
        hrmAdd.save(this.refreshVerificationCode);
    }

    doSaveAndNew = () => {
        const { hrmAdd } = this.props;
        hrmAdd.doSaveAndNew(this.refreshVerificationCode);
    }

    more = () => {

    }

    openFullmode = () => {
        const { hrmAdd } = this.props;
        hrmAdd.openFullmode();
    }

    refreshVerificationCode = () => this.setState({ time: new Date().getTime() });

    getSearchs = () => {
        const { time } = this.state;
        const { hrmAdd } = this.props;
        const { formSimple, conditionInfo } = hrmAdd;
        const { isFormInit } = formSimple;
        const formParams = formSimple.getFormParams();
        let group = [];
        window.e9HideFormFieldKeys = [];
        isFormInit && conditionInfo && conditionInfo.forEach((c, i) => {
            let items = [];
            c.items.forEach((field, j) => {
                let hide = false;
                if ((!formParams.accounttype || formParams.accounttype == '0') && field.domkey[0] == 'belongto') hide = true;
                if (formParams.accounttype == '1' && (field.domkey[0] == 'loginid' || field.domkey[0] == 'password' || field.domkey[0] == 'password1')) hide = true;
                let dom;
                if (field.conditionType == 'RESOURCEIMG') {
                    const key = getKey(field);
                    const bindObj = formSimple.$(key);
                    dom = <UploadAvatar ecId={`${this && this.props && this.props.ecId || ''}_UploadAvatar@7oueyr@${j}`} {...bindObj.bind()} />
                } else if (field.domkey[0] == 'validatecode') {
                    dom = (
                        <div>
                            <div style={{ float: 'left', width: '45%' }}>
                                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@oad99v@${j}`} fieldConfig={field} form={formSimple} />
                            </div>
                            <img style={{ marginLeft: '16px' }} border="0" align='absmiddle' src={addContentPath(`${verificationCode}${time}`)} onClick={() => this.refreshVerificationCode()} title={i18n.label.preview()} />
                        </div>
                    )
                } else {
                    dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@veevm0@${j}`} fieldConfig={mobx.toJS(field)} form={formSimple} />;
                }
                if (c.hide || !isEmpty(field.otherParams) && field.otherParams.hide) {
                    window.e9HideFormFieldKeys.push(field.domkey[0]);
                } else {
                    items.push({
                        com: <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@bfqj2o@${j}`}
                            label={`${field.label}`}
                            labelCol={{ span: `${field.labelcol}` }}
                            wrapperCol={{ span: `${field.fieldcol}` }}>
                            {dom}
                            {field.domkey[0] == 'workcode' && <AttachToNumberField ecId={`${this && this.props && this.props.ecId || ''}_AttachToNumberField@zowvrn`} field={field} form={formSimple}/>}
                        </WeaFormItem>,
                        colSpan: 1,
                        hide: hide
                    });
                }
            });
            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@42wafs@${i}`} className='hrm-center' hide={c.hide}
                needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} col={1} />)
        });
        return group;
    }

    render () {
        const { hrmAdd } = this.props;
        const { title, loading,isUsedAsSingle,jobtitleVisible,formSimple,closeJobtitleDialog} = hrmAdd;
        let dialogHeight = window.innerHeight - 250;
        if (dialogHeight > 660) dialogHeight = 660;

        let scrollProps = {};
        if (!isUsedAsSingle) {
            scrollProps.height = dialogHeight
        }

        let com = this.getSearchs()
        if (!isUsedAsSingle) {
            return <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@5hvnq9`}
                {...this.props}
                closable
                className="hrm-addsimple"
                style={{ width: 800, height: dialogHeight }}
                title={title()}
                icon="icon-coms-hrm"
                iconBgcolor='#217346'
                buttons={this.getBtns()}
                moreBtn={{ datas: [] }}
            >
               <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@gfpue4`} spinning={loading}>
                <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@56svjo`} {...scrollProps} ref="scrollBar">
                    {com}
                </WeaNewScroll>
            </Spin>
            </WeaDialog>
        }else{
            return (
                <div className="hrm-addsimple-single">
                    <div>{com}</div>
                    <WeaDialogFooter ecId={`${this && this.props && this.props.ecId || ''}_WeaDialogFooter@tsmpx0`} buttons={this.getBtns()}/>
                    {
                        jobtitleVisible && (
                            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@fw8u8f`}
                                onCancel={closeJobtitleDialog}
                                icon='icon-coms-hrm'
                                iconBgcolor='#217346'
                                title={i18n.label['531838']()}
                                callback={
                                    datas => {
                                        const {
                                            id,
                                            jobtitlemark
                                        } = datas;

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

                                        closeJobtitleDialog();

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

    getBtns = () => {
        const { hrmAdd } = this.props;
        const { canSave,isUsedAsSingle } = hrmAdd;
        return [
            (!isUsedAsSingle && <div className="ext-link" style={{ float: 'left', cursor: 'pointer' }} onClick={this.openFullmode}>{i18n.button.fullModle()}<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@u1u3nk@0`} type="double-right" />
            </div>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@whckot@1`} type="primary" disabled={!canSave} onClick={this.save}>{i18n.button.save()}</Button>),
            (!isUsedAsSingle && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ybuf84@2`} type="primary" disabled={!canSave} onClick={this.doSaveAndNew}>{i18n.button.saveAndCreate()}</Button>),
        ]
        return btns;
    }
}

export default Simple