import React, { Component } from "react";
import moment from "moment";
import { message } from 'antd';
import { WeaTools, WeaPopoverHrm,WeaLocaleProvider } from "ecCom";
import { getImgUrl, formParamsTransToStyle } from "./util/index";
import "./style/index.less";
const getLabel = WeaLocaleProvider.getLabel;

export default class HappyBirthday extends Component {
    constructor(props) {
        super(props);

        this.today = moment().format("YYYY-MM-DD")

        this.isCardShowedToday = this.today === WeaTools.ls.getStr("hrm-birthday-date")

        this.dialogStyle = { width: 475, height: 500 }

        this.state = {
            visible: false,
            bg_datas: {},
            congratulation_datas: {},
            date_data: {},
            head_bar_datas: {
                form_params: {
                    content: [],
                    fields: []
                }
            },
            head_datas: {},
            img_datas: {},
            person_datas: {},
            personList: [],
            createDate: "",
            defaultImg: "",
            displaySetting: "1;1"
        }
    }

    componentDidMount() {
        const { params: { id } } = this.props;
        this.getBirthInfo(id);
    }


    getBirthInfo = (recordId) => {
        WeaTools.callApi("/api/hrm/birthday/readBirthdayRemindData", "GET", { recordId }).then(res => {
            if (res.status == "1") {
                Object.keys(this.state).forEach(key => {
                    if (res[key]) {
                        this.setState({
                            [key]: res[key]
                        })
                    }
                });
                this.setState({ visible: true });
            } else {
                message.error(res.message);
            }
        })
    }


    render() {
        const { visible, bg_datas, img_datas, head_datas, congratulation_datas, date_data, person_datas, displaySetting, createDate, personList, defaultImg, head_bar_datas: { form_params: { content, fields } } } = this.state;

        const isBirthDateShow = content.includes("2");

        if (!visible) return null;

        return (
            <div className="hbOutter">
                <div className="happy-birthday">
                    <Bg ecId={`${this && this.props && this.props.ecId || ''}_Bg@d3ldhq`} datas={{bg_datas, defaultImg,...this.dialogStyle}}/>
                    <Img ecId={`${this && this.props && this.props.ecId || ''}_Img@j4ups0`} datas={img_datas}/>
                    <Text ecId={`${this && this.props && this.props.ecId || ''}_Text@abjx33`} datas={head_datas}/>
                    <Congratulation ecId={`${this && this.props && this.props.ecId || ''}_Congratulation@kbym9k`} datas={congratulation_datas}/>
                    <BirthDate ecId={`${this && this.props && this.props.ecId || ''}_BirthDate@ie3qqz`} datas={date_data} isShow={isBirthDateShow} date={createDate}/>
                    <PersonInfo ecId={`${this && this.props && this.props.ecId || ''}_PersonInfo@z2vol2`} datas={person_datas} personList={personList} displaySetting={fields} date={createDate} {...this.props}/>
                </div>
            </div>
        );
    }
}

const getStyle = (datas) => {
    const { formParams, id, isAbsolute, defaultImg } = datas;
    const style = {};
    if (isAbsolute) {
        style.position = "absolute";
    }
    if (id) {
        style.backgroundImage = `url(${getImgUrl(id,defaultImg)})`
    }
    if (formParams) {
        Object.keys(formParams).forEach(key => {
            Object.assign(style, formParamsTransToStyle(key, formParams))
        });
    }
    return style;
}

class Bg extends Component {
    render() {
        const { datas: { bg_datas: { form_params, selectedid } = {}, defaultImg, width, height } } = this.props;

        const style = { width, height };
        Object.assign(style, getStyle({ formParams: form_params, id: selectedid, isAbsolute: true, defaultImg }));
        return <div style={style}/>
    }
}


class Img extends Component {
    render() {
        const { datas: { form_params, id } } = this.props;

        return id ? <div style={{...getStyle({formParams:form_params,id, isAbsolute:true}), backgroundSize: "100%"}}/> : null;
    }
}

class Text extends Component {
    render() {
        const { datas: { form_params, title } } = this.props;

        return title ? <div style={getStyle({formParams:form_params,isAbsolute:true})} dangerouslySetInnerHTML = {{ __html: title }}/> : null;
    }
}

class Congratulation extends Component {
    render() {
        const { datas: { form_params, paragraph } } = this.props;

        return paragraph ? <div style={getStyle({formParams:form_params,isAbsolute:true})} dangerouslySetInnerHTML = {{ __html: paragraph }}/> : null;

    }
}

class BirthDate extends Component {
    render() {
        const { datas: { form_params }, date, isShow } = this.props;

        return isShow ? <div style={getStyle({formParams:form_params,isAbsolute:true})}>{date}</div> : null;
    }
}

class PersonInfo extends Component {
    constructor(props) {
        super(props);
        this.interval = null;
        this.viewportHeight = 210;
        this.state = {
            bottom: 0,
            isOverflow: false
        }
    }

    componentDidMount() {
        this.cHeight = $('.person-content').height()
        const isOverflow = this.cHeight > this.viewportHeight

        this.setState({ isOverflow })
        isOverflow && this.startScroll();
    }

    componentWillUnmount() {
        this.stopScroll();
    }

    startScroll = () => {
        this.interval = setInterval(() => {
            if (this.state.bottom > this.viewportHeight) {
                this.setState({
                    bottom: -this.cHeight
                });
            }
            this.setState((prevState) => ({
                bottom: prevState.bottom + 1
            }))
        }, 100);
    }

    stopScroll = () => {
        if (this.interval) {
            clearInterval(this.interval)
        }
    }

    handleMouseOver = () => {
        this.stopScroll();
    }

    handleMouseOut = () => {
        this.startScroll();
    }

    sendLove = (id) => {
        const { personList, date, params} = this.props;

        ecCom.WeaTools.createDialog({
            title: getLabel(526781, '送祝福'),
            icon: "icon-coms-hrm",
            iconBgcolor: "#217346",
            url: `/spa/hrm/index_mobx.html#/main/hrm/sendBless?datas=${JSON.stringify( personList.map(data => ({id:data.id,name:data.lastname}) ) )}&targetId=${id}&createDate=${date}&recordId=${params.id}`,
            style: { width: 760, height: 610 },
            callback: (datas) => { // 数据通信
                const { msg } = datas;
                if (msg) message.success(msg);
            },
            onCancel: () => { // 关闭通信
            }
        }, null, dialog => {
            dialog.show();
        })
    }

    render() {
        const { datas: { form_params }, personList, displaySetting } = this.props;
        const { bottom, isOverflow } = this.state;

        const displayItems = [];

        const obj = {
            "1": "lastname",
            "2": "departmentName",
            "3": "subCompanyName",
            "4": "sendLove"
        };

        displaySetting.sort().forEach(v => {
            if (["1", "4"].includes(v)) {
                displayItems.push(obj[v]);
            }
            if (["2", "3"].includes(v)) {
                const tarIndex = displayItems.findIndex(item => typeof item == "object");
                if (tarIndex == -1) {
                    displayItems.push([obj[v]]);
                } else {
                    const tarArr = displayItems[tarIndex];
                    tarArr.push("connector");
                    tarArr.push(obj[v]);
                }
            }
        })
         const style = {...getStyle({formParams: form_params, isAbsolute: true}), overflow: "hidden"}
        if (!isOverflow) {
            style.display = 'table'
        }

        let orgWidth;
        if (['2','3'].every(v => displaySetting.includes(v))) {
            orgWidth = 0.7
        }else if(['2','3'].some(v => displaySetting.includes(v))){
            orgWidth = 0.5
        }else{
            orgWidth = 0
        }
        let num = displaySetting.includes('4') ? 2 : 1;

        return personList.length > 0 && (
            <div style={style} className="person-view" onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut}>
                <div className="person-content" style={isOverflow ? {bottom} : {verticalAlign:style.verticalAlign,position:'relative',display: 'table-cell'}}>
                    {personList.map(info => {
                        const _info = Object.assign({}, info, {
                            sendLove: getLabel(526781, '送祝福'),
                            connector: "-"
                        })
                        return (
                            <p>
                                {displayItems.map(v => {
                                    if (typeof v == "string") {
                                        const style = {
                                            width:`${ ((1-orgWidth)/num)*100}%`
                                        };
                                        if (v == 'sendLove') {
                                            style.color = form_params["btn-color"]
                                        }
                                        if (displayItems.length == 2 && v == 'sendLove') {
                                            style.marginLeft = 20
                                        }
                                        return (
                                            <span className={v} onClick={() =>(v == "sendLove") && this.sendLove(info.id) }  style={style} title={_info[v]}>
                                                <WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@vn69p1@1`} />
                                                { (v == "sendLove")  ? _info[v] : <a href={`javaScript:openhrm(${_info.id})`} onClick={e => window.pointerXY(e)}>{_info[v]}</a>}
                                            </span>
                                        )
                                    }else{
                                        return (
                                            <span className="org" style={{width:`${orgWidth*100}%`}}>
                                                {v.map(key => {
                                                    return (
                                                        <span className={key} title={_info[key]}>{_info[key]}</span>
                                                    )
                                                })}
                                            </span>
                                        )
                                    }
                                })}
                            </p>
                        )
                    })}
                </div>
            </div>
        )
    }
}
