import React from 'react'
import * as mobx from 'mobx'
import {
    inject,
    observer
} from 'mobx-react'
import {
    WeaTop,
    WeaTab,
    WeaFormItem,
    WeaRightMenu,
    WeaAlertPage,
    WeaNewScrollPagination,
    WeaSlideModal,
    WeaLocaleProvider
} from 'ecCom'
import {
    Row,
    Col,
    Spin,
    Modal,
    Button,
    message,
    Switch,
    Menu, Dropdown, Icon, Anchor
} from 'antd';

import {
    WeaSwitch,
    WeaTableNew
} from 'comsMobx';
import {
    i18n
} from '../../public/i18n';


import FormItem from './FormItem';
import IframeItem from './IframeItem';
import AnchorDetect from './AnchorDetect';
import { renderNoright } from '../../util'; // 从util文件引入公共的方法
import VersionsSlider from '../VersionsSlider';
import isEmpty from 'lodash/isEmpty'


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

@inject('resourceCard')
@observer
export default class ResourceCard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            activity: 0,//激活的锚点
        }
        
    }

    componentWillMount() {
    }

    componentDidMount() {
        this.init();
    }

    // componentDidUpdate(prevProps) {
    //     // 判断items是否更新
    //     if (prevProps.items !== this.props.items
    //         && this.isDiff(prevProps.items, this.props.items)) {
    //         // 重新生成受监控元素
    //         this.buildDetectElements(this.props.items);
    //     }
    // }

    // // 判断两数组是否一摸一样
    // isDiff = (before, after) => {
    //     if (before.length !== after.length) return false;
    //     // 先对数组进行排序
    //     const beforeTemp = [...before].sort(), afterTemp = [...after].sort();
    //     for (let i = 0; i < beforeTemp.length; i++) {
    //         if (beforeTemp[i] !== afterTemp[i]) {
    //             return false;
    //         }
    //     }
    //     return true;
    // };

    componentWillUnmount() {
    }


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

    init() {
        const {
            resourceCard
        } = this.props;
        let { hash } = window.location;
        hash = hash.split("?")[0];
        let id = hash.match("[^/]+(?=/$|$)")[0];
        resourceCard.userid = id;
        resourceCard.init();
    }

    onScrollEnd = () => {
        // resourceCard.scrollLoading = true;

        // setTimeout(() => {
        //     // resourceCard.data.iframeList.push({
        //     //     id: "job",
        //     //     title: "岗位管理",
        //     //     url: '/spa/organization/static/index.html#/main/organization/companyExtend/7'
        //     // })
        //     resourceCard.scrollLoading = false;
        // }, 2000);

    };

    //  buildDetectElements = () => {
    //     const {
    //         resourceCard
    //     } = this.props,{
    //         data
    //     } =resourceCard;

    //     !this.isEmptyObject(data) && data.anchorList.map((item, index) => {
    //         item.activity = index;
    //         item.offset = document.getElementById(item.id).offsetTop + document.getElementById(item.id).clientHeight;
    //     })
    //     resourceCard.setDetectElements(data.anchorList);
    // }

    handleMenuClick = (e) => {
        const {
            resourceCard
        } = this.props, {
            data
        } = resourceCard;
        window.open(e.item.props.url.replaceAll("${id}",data.user.id),"_blank")
    }

    view = () => {
        const { resourceCard } = this.props;
        resourceCard.selectVersions();
    }

    onClose = () => {
        const { resourceCard } = this.props;
        resourceCard.open = false;
    }

    onScroll = (event) => {
        const {
            resourceCard
        } = this.props,{
            detectElements,
            flag
        } = resourceCard;
        const postion = event.target.scrollTop;
        let getActivityCurrent = this.state.activity;
        detectElements.map((item, index) => {
            if (postion >= document.getElementById(item.id).offsetTop && postion <= item.offset) {
                return getActivityCurrent = item.activity;
            }
        })
        
        if(event.target.scrollHeight == postion + event.target.clientHeight) {
            getActivityCurrent = detectElements.length - 1
        }

        this.setState({
            activity: getActivityCurrent
        })
       
     }

    scrollToAnchor = (anchorName, index) => {
        const {
            resourceCard
        } = this.props;
        
        let _this = this;
        if (anchorName) {
            // 找到锚点
            let anchorElement = document.getElementById(anchorName);
            // 如果对应id的锚点存在，就跳转到锚点
            if (anchorElement) {
 anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' }); 
}
        }
    }

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

    render() {
        const {
            resourceCard
        } = this.props, {
            height,
            scrollLoading,
            offset,
            overtime,
            intervalTime,
            data,
            versionList,
            open
        } = resourceCard;
        const menu = (
            <Menu onClick={this.handleMenuClick}>
                {
                    !this.isEmptyObject(data) && data.buttons.slice(3).map((item,index) => {
                        return (
                            <Menu.Item key="1" url={item.url}>{item.name}</Menu.Item>
                        )
                    })
                }
            </Menu>
        );

        return (
               !this.isEmptyObject(data) &&  <WeaNewScrollPagination
                    height='100%'
                    onScrollEnd={this.onScrollEnd}
                    onScroll={this.onScroll}
                >
                    <div className="gutter-resource-card">
                        <div className="gutter-row">
                            <div className='top'>
                                <img src={data.user.image} />
                                <div className='user'>
                                    <div className='name'>{data.user.name}
                                        <span>{data.user.sex == 0 ? <i className="icon-coms-men" /> : <i className="icon-coms-women" />}</span>
                                    </div>
                                    {/* <div className='icon-info'>
                                        <i className="icon-coms-Send-message" />
                                        <i className="icon-coms-message-o" />
                                        <i className="icon-coms-Send-emails" />
                                        <i className="icon-coms-New-schedule-o" />
                                    </div> */}
                                    <div className='content'>
                                        <div>
                                            <span className='label'><i className="icon-portal-email-o" /></span>
                                            <span className='value'>{data.user.email}</span>
                                            <span className='label'><i className="icon-coms-contact" /></span>
                                            <span className='value'>{data.user.phone}</span>
                                        </div>
                                        <div style={{ marginTop: '10px' }}>
                                            <span className='label'>{getLabel(547239,'账号类型')}:</span>
                                            <span className='value'>{data.user.accountType}</span>
                                            <span className='label'>{getLabel(547240,'状态')}:</span>
                                            <span className='value'>{data.user.status}</span>
                                        </div>
                                    </div>
                                </div>
                                <div className='right-button'>
                                <Button  className='item' onClick={this.view} >{i18n.button.version()}</Button>
                                    {
                                        data.buttons.slice(0,3).map((item,index) => {
                                            return (
                                                <Button className='item' onClick={() => {
 window.open(item.url.replaceAll("${id}",data.user.id),"_self")
}}>{item.name}</Button>
                                            )
                                        })                               
                                    }
                                    {
                                        data.buttons.length > 3 ? <Dropdown overlay={menu}>
                                            <Button style={{ marginLeft: 8 }} className='item'>
                                            {getLabel(547658,'更多操作')} <Icon type="down" />
                                            </Button>
                                        </Dropdown> : ''
                                    }
                                </div>

                            </div>
                            <div className='data'>
                                <Row type="flex" justify="space-between" style={{ height: '100%' }}>
                                    <Col className='ant-col' span={4} onClick={() => {
 window.open(`/spa/workflow/static/index.html#/main/workflow/listDoing?resourceid=${data.user.ecId}`)
}}>
                                        <img src="/hrm/hrm_e9/image/workflow.png" alt="" />
                                        <div>
                                            <p>{getLabel(547241,'流程总数')}</p>
                                            <p>{data.statistical.workflowCount}</p>
                                        </div>
                                    </Col>
                                    <Col className='ant-col' span={4} onClick={() => {
 window.open(`/spa/document/static/index.html#/main/document/search?viewcondition=2&doccreaterid=${data.user.ecId}`)
}}>
                                        <img src="/hrm/hrm_e9/image/doc.png" alt="" />
                                        <div >
                                            <p>{getLabel(547243,'文档总数')}</p>
                                            <p>{data.statistical.docCount}</p>
                                        </div>
                                    </Col>
                                    <Col className='ant-col' span={4} onClick={() => {
 window.open(`/spa/crm/static/index.html#/main/crm/customer/hrmView?searchHrmId=${data.user.ecId}`)
}}>
                                        <img src="/hrm/hrm_e9/image/custom.png" alt="" />
                                        <div>
                                            <p>{getLabel(547244,'我的客户')}</p>
                                            <p>{data.statistical.cusCount}</p>
                                        </div>
                                    </Col>
                                    <Col className='ant-col' span={4} onClick={() => {
 window.open(`/spa/cowork/static/index.html#/main/cowork/hrmview?searchHrmid=${data.user.ecId}`) 
}}>
                                        <img src="/hrm/hrm_e9/image/cowork.png" alt="" />
                                        <div>
                                            <p>{getLabel(547245,'我的协作')}</p>
                                            <p>{data.statistical.collaborationCount}</p>
                                        </div>
                                    </Col>
                                    <Col className='ant-col' span={4} onClick={() => {
 window.open(`/spa/blog/static/index.html#/user/${data.user.ecId}`) 
}}>
                                        <img src="/hrm/hrm_e9/image/weibo.png" alt="" />
                                        <div>
                                            <p>{getLabel(547246,'我的协作')}</p>
                                            <p>{data.statistical.weiboCount}</p>
                                        </div>
                                    </Col>
                                </Row>
                            </div>
                            {
                                data.formItems.map((item, index) => {
                                    return (
                                        <FormItem groupInfo={item} />
                                    )
                                })
                            }
                            {
                                data.iframeList.map((item, index) => {
                                    return (
                                        <IframeItem iframeInfo={item} userid={data.user.ecId} />
                                    )
                                })
                            }
                        </div>
                        <div className="gutter-row">
                            <AnchorDetect
                                anchorList={data.anchorList}
                                container={window}
                                activity={this.state.activity}
                                onChange={this.scrollToAnchor}
                            />
                        </div>
                    </div>
                    <Spin size="large" tip="" className='scroll-spin' spinning={scrollLoading} />
                    <WeaSlideModal visible={open}
                        // top={6}
                        width={40}
                        height={100}
                        direction={'right'}
                        measure={'%'}
                        content={!isEmpty(versionList) ? <VersionsSlider versionList={versionList} handleChange={val => resourceCard.changeVersion(val)}/> : <div style={{"textAlign":"center","color":"red","fontSize":"20px","marginTop": "50px"}}> {getLabel(547659,'暂无历史版本')} </div>} 
                        onClose={this.onClose}
                        onAnimationEnd={() => console.log('onAnimationEnd')} />
                </WeaNewScrollPagination>
        )
    }

}