import {
    inject,
    observer,
} from 'mobx-react'
import {
    toJS
} from 'mobx'
import {
    WeaUpload,
    WeaDialog,
    WeaFormItem,
    WeaNewScroll,
    WeaTableEdit,
    WeaSearchGroup,
    WeaMoreButton,
    WeaLocaleProvider,
} from 'ecCom'
import {
    Spin,
    Button,
    message
} from 'antd'
import {
    WeaSwitch
} from 'comsMobx'
import {
    i18n
} from '../../public/i18n';
import {
    IEVersion
} from '../../public/pulic-func'
import ImportResult from './ImportResult';
const getLabel = WeaLocaleProvider.getLabel;

@inject('hrmSalaryIndexMaintenance')
@observer
export default class Editor extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            width: 900,
            height: 900,
        }
    }

    getButtons = () => {
        const {
            hrmSalaryIndexMaintenance
        } = this.props, {
            editor,
            editorSave,
        } = hrmSalaryIndexMaintenance, {
            floading,
            isImportFinish,
            formType
        } = editor;

        let buttons = [
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@253qh9`} type="primary" disabled={floading} onClick={() => editorSave()} >{i18n.button.save()}</Button>),
            (<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@xtfxo8`} />)
        ];

        return buttons;
    }

    render() {
        const {
            hrmSalaryIndexMaintenance
        } = this.props, {
            editor,
            resultDialog,
            setEditorDialogVisible
        } = hrmSalaryIndexMaintenance, {
            title,
            visible,
        } = editor, {
            width,
            height,
        } = this.state;

        return (
            <div>
				<WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@ikxrp9`}
	                scalable
                    title={title}
                    hasScroll
	                icon="icon-coms-hrm"
	                iconBgcolor="#217346"
	                visible={visible}
	                closable={true}
	                onCancel={() => setEditorDialogVisible(false)}
	                buttons={this.getButtons()}
	                style={{width: width, height: height}}
	                onChangeHeight={(h) => this.setState({height: h})}
	            >
	            	<Ec ecId={`${this && this.props && this.props.ecId || ''}_Ec@t2ywqb`} height={height}/>
	            </WeaDialog>
	            {resultDialog.visible && <ImportResult ecId={`${this && this.props && this.props.ecId || ''}_ImportResult@neaqso`} />}
            </div>
        )

    }
}

@inject('hrmSalaryIndexMaintenance')
@observer
class Ec extends React.Component {
	constructor(props) {
        super(props);
        this.state = {
            height: 900,
            list: [],
            upStatus: '',
            h: 277,
            t:46,
            b:42,
            sgVisbile:true
        }
    }

    componentDidUpdate(prevProps, prevState) {
    	const h = $(".wea-search-group").height();
    	const t = $(".wea-title").height() ;
    	const b = $(".ant-table-thead").height() ;
    	if (h !== null && h != prevState.h  ) {
    		this.setState({h})
    	}
    	if (t !== null && t != prevState.t) {
    		this.setState({t})
    	}
    	if (b !== null && b != prevState.b) {
    		this.setState({b})
    	}
    }

     handleUploading = (status) => {
        this.setState({
            upStatus: status
        });

        if (status == 'uploading') {
            this.setState({
                list: []
            });
        }
    }


	getClassName = () => {
        const {
            hrmSalaryIndexMaintenance
        } = this.props, {
            editor
        } = hrmSalaryIndexMaintenance, {
            formType
        } = editor;

        if (formType == 'new') {
            if (IEVersion() == '-1') {
                return 'hrm-salary-editor'
            } else {
                return 'hrm-salary-editor hrm-salary-editor-ie'
            }
        } else {
            if (IEVersion() == '-1') {
                return 'hrm-salary-table-edit'
            } else {
                return 'hrm-salary-table-edit hrm-salary-table-edit-ie'
            }
        }
    }

    getBasicInfoItems = () => {
        const {
            hrmSalaryIndexMaintenance
        } = this.props, {
            editor,
            setExcelFileId,
            submit,
            getImportTemplate,
            handleFormChange,
        } = hrmSalaryIndexMaintenance, {
            form,
            condition,
            hasImportRight,
            url,
            formType,
            floading,
            tloading,
        } = editor, {
            isFormInit
        } = form, {
            list,
            upStatus
        } = this.state;

        let arr = [];
        isFormInit && toJS(condition).map(c => {
            c.items.map((field, index) => {
                arr.push({
                    com: (
                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@na9bgt@${index}`}
                            label={ `${field.label}`}
                            labelCol={{span: 6,offset: 4}}
                            wrapperCol={{span:9}}>
                                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@4yjflo@${index}`} fieldConfig={field} form={form} formParams={form.getFormParams()} onChange={handleFormChange}/> 
                        </WeaFormItem>
                    ),
                    colSpan: 1,
                })
            });
        })

        const templateElement = (url) => {
            return {
                com: (
                    <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@rwzr9z`}
                    	label={i18n.label.downloadExcelTemplate()}
                    	labelCol={{span: 6,offset: 4}}
                        wrapperCol={{span: 13}}>
                        	<p style={{paddingTop: 5}}><a onClick={getImportTemplate}>{i18n.label.templateFile()}</a><span style={{marginLeft: 20}}>{`（${i18n.label.downloadExcelFileBeforeImport()}）`}</span></p>
                	</WeaFormItem>
                ),
                colSpan: 1,
            }
        }

        // const submitButton = () => {
        //     return {
        //         com: (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3ffz2p`} onClick={()=> submit()} disabled={upStatus === 'uploaded' ? false : true} style={{top: -38,left: 603}} title={upStatus === 'uploaded' ? '' : i18n.label.uploadFileFirst()}>{i18n.button.import()}</Button>),
        //         colSpan: 1
        //     }
        // }


        const uploadComponent = () => {
            return {
                com: (
                    <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@h8uyuq`}
                    	label={i18n.label.excelFileImport()}
                    	labelCol={{span: 6,offset: 4}}
                        wrapperCol={{span: 13}}>
		                    <div style={{float: 'left'}}>
		                        <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@49niix`}
		                            uploadUrl='/api/doc/upload/uploadFile'
		                            category='string'
		                            limitType='xls,xlsx'
		                            datas={upStatus === 'uploaded'  ? list : []}
		                            onChange={(id, list) => {this.setState({list:list}); setExcelFileId(id)}}
		                            onUploading={status => this.handleUploading(status)}
		                        >
		                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6ggz2f`}>{i18n.button.selectFile()}</Button>
		                        </WeaUpload>
		                    </div>
		                    <div style={{float: 'left', paddingLeft: 10, paddingTop: 6}}>
		                        { list.length == 0 ? <p>{i18n.label.noFileSelected()}</p> : list.map(file => {
		                        	const {filename} = file;
		                        	return <p>{filename.length > 21 ? filename.slice(0, 21) + '...' : filename }</p>
		                        }) }
		                    </div>
                            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3ffz2p`} style={{marginLeft:10}} onClick={()=> submit()} disabled={upStatus === 'uploaded' ? false : true} title={upStatus === 'uploaded' ? '' : i18n.label.uploadFileFirst()}>{i18n.button.import()}</Button>
                	</WeaFormItem>
                ),
                colSpan: 1,
            }
        }
        
        if (hasImportRight && !(floading || tloading)) {
            arr.push(templateElement(url));
            arr.push(uploadComponent());
            // arr.push(submitButton());
        }
        return arr;
    }

    getTableEdit = () => {
        const {
            hrmSalaryIndexMaintenance,
            height
        } = this.props, {
            editor,
            setTableEditDatas,
            setTableEditRef,
            pageSize,
            currentPage,
            setPageSize,
            setCurrentPage,
            getTableEditDatas,
        } = hrmSalaryIndexMaintenance, {
            columns,
            datas,
            total,
        } = editor, {
            h,
            t,
            b
        } = this.state;

        const scroll = {
            x: columns.length * 120,
        }

        const innerHeight =  window.innerHeight || 657;
        if (innerHeight > 700) {
            scroll.y = height - h - t - b - 68
        }

        return (<WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@3zycur`}
					ref={com => setTableEditRef(com)}
          			columns={toJS(columns)}
          			datas={toJS(datas)}
          			showTitle={false}
          			getRowSelection ={rowSelection => null}
					tableProps = {{
							scroll,
							pagination: {
								total,
								pageSize,
								showSizeChanger:true,
								showQuickJumper:true,
								current:currentPage,
								pageSizeOptions: [10, 20, 50, 100],
								showTotal: total => getLabel("385617", "共$s条").replace(/\$s/, total),
								onShowSizeChange: 
									(page, pagesize) => {
										setPageSize(pagesize);
										setCurrentPage(1);
										getTableEditDatas();
									},
								onChange: page=>{
									setCurrentPage(page);
									getTableEditDatas();
								}
							}
					}}
          			onChange={datas => setTableEditDatas(datas)}
        		/>)

    }

    handleVisibleChange = (b) => {
        this.setState({sgVisbile:b});
    }

    render() {
        const { hrmSalaryIndexMaintenance: { editor: { floading, tloading } } } = this.props;
        const { sgVisbile } = this.state;

        return (
            (floading || tloading) ? <div className='hrm-loading-center-small'>
                       					<Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@8p38p4`} spinning={floading || tloading}></Spin>
                    				</div> :
                <div className={this.getClassName()}>
				<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@8pfdrm`} title={i18n.label.basicInfo()} items={this.getBasicInfoItems()} showGroup={sgVisbile} col={1} onVisibleChange={this.handleVisibleChange}/>
					<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@68k2vk`} title={i18n.label.salaryIndex()} children={this.getTableEdit()} showGroup={true} col={1}/>
				</div>
        );
    }
}