import React, { useEffect, useState } from 'react';
import './index.less';
import { Button, Carousel, Col, Form, Input, List, Modal, Radio, Row, Space, Spin, Tag, message } from 'antd';
import header from '@/assets/highQuality/header.jpg'
import flag from '@/assets/highQuality/flag.png'
import project_left from '@/assets/highQuality/project_left.jpg'
import material from '@/assets/highQuality/material.jpg'
import bottom_button from '@/assets/highQuality/bottom_button.png'
import partymember from '@/assets/highQuality/partymember.png'
import partybranch from '@/assets/highQuality/partybranch.png'
import star1 from '@/assets/highQuality/star1.png'
import star2 from '@/assets/highQuality/star2.png'
import star3 from '@/assets/highQuality/star3.png'
import card_img_2 from '@/assets/highQuality/card_img_2.png'
import card_img_3 from '@/assets/highQuality/card_img_3.png'
import card_img_4 from '@/assets/highQuality/card_img_4.png'
import card_img_5 from '@/assets/highQuality/card_img_5.png'
import card_img_6 from '@/assets/highQuality/card_img_6.png'
import card_img_7 from '@/assets/highQuality/card_img_7.png'
import card_img_8 from '@/assets/highQuality/card_img_8.png'
import card_img_9 from '@/assets/highQuality/card_img_9.png'
import topic_header_img from '@/assets/topic/topic_header_img.png'
import topic_banner_default from '@/assets/topic/topic_banner_default.jpg'
import topic_activity_default from '@/assets/topic/topic_activity_default.jpg'
import { downloadVideo, getClassroomList, getHomeBanner, getHomeContact, getHomeGraceful, getHomeProject, getHomeRight, submitAdvice } from './service';
import { chunk, formatTime, getImageUrl, isEmpty, isNotEmpty, managerAuthority } from '../utils';
import ExtendUpload from '@/utils/ExtendUpload';
import { getSessionUserData } from '@/utils/session';
import ReactPlayer from "react-player/file";

const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 17 },
};

//卡片头
const LeftCardTop = (props: any) => {
    return (
        <div className='left-card-top'>
            <div className='left-card-title'>
                <span>{props.title}</span>
            </div>
            <div className='left-card-content'>
                <div>
                    <img src={flag} className='left-card-flag' />
                </div>
                {props.url && <div onClick={() => window.open(props.url)}>
                    <span className='left-card-other'>更多</span>
                    <span className='left-card-icon'>&gt;&gt;&gt;</span>
                </div>}
            </div>
        </div>
    )
}

//右侧专业线内容
const RightDisplayContent = (props: any) => {
    const displayContentClick = () => {
        window.open("/highQualityOperation/partyBranch");
    }
    return (
        props.data?.length > 0 ? (
            <div className='right-display-content right-display-content-pointer' onClick={() => displayContentClick()}>
                <img src={props.img} className='right-display-content-img' />
                <div className='right-display-content-right'>
                    <div className='right-display-content-title'>
                        <span>{props.data[props.index].dataName}</span>
                    </div>
                    <div className='right-display-content-content'>
                        <span className={`right-display-content-number ${props.color}`}>{props.data[props.index].dataValue}</span>
                        <span className='right-display-content-unit'>{props.data[props.index].dataType}</span>
                    </div>
                </div>
            </div>
        ) : null
    )
}
//右侧专业线卡片标题
const RightCardTitle = (props: any) => {
    return (
        <>
            <div className={props?.onClick ? 'right-card-title right-card-title-click' : 'right-card-title'} onClick={props?.onClick ? props.onClick : () => { }} >
                <span>{props.title}</span>
            </div>
            <div className='right-card-title-line'></div>
        </>
    )
}
//右侧专业线卡片内容
const RightCardContent = (props: any) => {
    return (
        props.data?.length > 0 ? (
            <div className='right-card-content'>
                <div className='right-card-content-img'>
                    <img src={props.img} />
                </div>
                <div className='right-card-content-right'>
                    <span className='right-card-content-title'>{props.data[props.index].dataName}</span>
                    <div className='right-card-content-content'>
                        <span className={`right-card-content-number ${props.color}`}>{props.data[props.index].dataValue}</span>
                        <span className='right-card-content-unit'>{props.data[props.index].dataType}</span>
                    </div>
                </div>
            </div>
        ) : null
    )
}
//接口人信息卡片内容
const BottomCardContent = (props: any) => {
    return (
        <Col span={6}>
            <div className='bottom-card'>
                <div className='bottom-card-title'>
                    <span>{props.data.contactName}</span>
                    <div>
                        <img src={bottom_button} onClick={() => props.onClick()} />
                    </div>
                </div>
                {/* <div className='bottom-card-remark'>
                    <span className='bottom-card-remark-text'>{props.data.remark}</span>
                </div> */}
                <div className='bottom-card-content'>
                    <p>邮箱：{props.data.contactEmail}</p>
                    <p>电话：{props.data.contactMobiphone}</p>
                    <p>部门：{props.data.contactDepartment}</p>
                </div>
            </div>
        </Col>
    )
}
//接口人信息-我要提意见Modal
const CommentModal = (props: any) => {
    const { TextArea } = Input;
    const [form] = Form.useForm();
    const [modalLoading, setModalLoading] = useState<boolean>(false);
    const onCancel = () => {
        props.closeModal();
    }

    const onSubmit = () => {
        form.submit();
    }

    const onFinish = async (values: any) => {
        setModalLoading(true);
        const params = {
            ...values,
        }
        await submitAdvice(params).then(res => {
            if (res?.code == 200) {
                message.success("提交成功");
                onCancel();
            }
        }).finally(() => {
            setModalLoading(false);
        })
    };
    useEffect(() => {
        form.setFieldsValue({
            ...props.data,
            name: props.userData?.fullName,
            company: props.userData?.organizationName,
        })
    }, [props.data?.id])

    return (
        <Modal
            className='h-topic-home-modal'
            title={
                <div className='bottom-modal-header'>
                    <img src={topic_header_img} />
                    <div className='bottom-modal-headertext'>
                        <span>我要提意见</span>
                    </div>
                </div>
            }
            visible={props.visible}
            onCancel={onCancel}
            destroyOnClose
            closable={false}
            footer={null}
            centered
            maskStyle={{ backgroundColor: 'rgba(0, 0, 0, 0.3)' }}
            width={800}
        >
            <Spin spinning={modalLoading}>
                <div className='bottom-modal-body'>
                    <Form
                        {...formItemLayout}
                        form={form}
                        name="register"
                        className='modal-form'
                        onFinish={onFinish}
                        preserve={false}
                    >
                        <Form.Item
                            name="contactName"
                            hidden
                        >
                            <Input />
                        </Form.Item><Form.Item
                            name="contactId"
                            hidden
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="suggestionType"
                            label="意见类型"
                            rules={[{ required: true, message: '请选择意见类型！', whitespace: true }]}
                        >
                            <Radio.Group>
                                <Radio value="采购需求提出" className="radio-content radio-right59">采购需求提出</Radio>
                                <Radio value="采购方案编制和实施" className="radio-content">采购方案编制和实施</Radio>
                                <Radio value="采购合同上架" className="radio-content">采购合同上架</Radio>
                                <Radio value="采购合同执行及评价" className="radio-content">采购合同执行及评价</Radio>
                                <Radio value="物资到货与调拨" className="radio-content radio-right41">物资到货与调拨</Radio>
                                <Radio value="退库和物资处置" className="radio-content">退库和物资处置</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item
                            name="suggestionContent"
                            label="意见内容"
                            rules={[{ required: true, message: '请填写意见内容！', whitespace: true }]}
                        >
                            <TextArea
                                rows={4}
                                maxLength={50}
                                placeholder="在这里输入我要提出的意见（最多输入50字）"
                            />
                        </Form.Item>
                        <Form.Item
                            name="attachmentImage"
                            label="附件"
                        >
                            <ExtendUpload bid={''} btnName="上传" maxCount={1} maxSize={30} uploadProps={{ name: "file", disabled: false, accept: ".png,.jpg,.jpeg,.rar,.zip,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.pdf" }} />
                        </Form.Item>
                        <Form.Item
                            name="instructions"
                            label="补充信息"
                        >
                            <TextArea
                                rows={3}
                                maxLength={30}
                                placeholder="在这里输入我要补充的信息（最多输入30字）"
                            />
                        </Form.Item>
                        <Form.Item
                            label="填写人员"
                        >
                            <Row>
                                <Col span={4}>
                                    <Form.Item
                                        name="name"
                                    >
                                        <Input readOnly />
                                    </Form.Item>
                                </Col>
                                <Col span={19} offset={1}>

                                    <Form.Item
                                        name="company"
                                        label="所在公司"
                                    >
                                        <Input readOnly />
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form.Item>
                    </Form>
                    <div className='bottom-modal-submit'>
                        <Space>
                            <Button type='primary' className='submit-button' onClick={onSubmit}>
                                提交
                            </Button>
                            <Button onClick={onCancel}>
                                取消
                            </Button>
                        </Space>
                    </div>
                </div>
            </Spin>
        </Modal>
    )
}

const Home: React.FC<{}> = () => {
    //banner data
    const [bannerList, setBannerList] = useState<any[]>([]);
    //graceful data
    const [gracefulList, setGracefulList] = useState<any[]>([]);
    //classroom data
    const [classroomList, setClassroomList] = useState<any[]>([]);
    //project data
    const [projectList, setProjectList] = useState<any[]>([]);
    //right data
    const [rightList, setRightList] = useState<any[]>([]);
    //right local data
    const [contactData, setContactData] = useState<any[]>([]);
    //right total data
    const [totalContactData, setTotalContactData] = useState<any[]>([]);
    //bottom advice modalvisible
    const [adviceVisible, setAdviceVisible] = useState<boolean>(false);
    //bottom advice modal data
    const [adviceItemData, setAdviceItemData] = useState<Object>({});
    //bottom tags select
    const [selectedTag, setSelectedTag] = useState<string>('');
    //user data
    const userData = getSessionUserData();
    //video Carousel
    const [autoplay, setAutoplay] = useState<boolean>(true);
    const [videoPlayKey, setVideoPlayKey] = useState<string>("");
    const { CheckableTag } = Tag;

    const openModal = (item: any) => {
        setAdviceItemData(item);
        setAdviceVisible(true);
    }

    const closeModal = () => {
        setAdviceVisible(false);
        setAdviceItemData({});
    }

    //get banner
    const getBannerList = () => {
        getHomeBanner().then(async res => {
            if (res?.code == 200) {
                setBannerList(res?.data);
            }
        })
    }

    //get graceful
    const getGracefulList = () => {
        getHomeGraceful(null).then(async res => {
            if (res?.code == 200) {
                const arrayData = chunk(res?.data, 6);//分组
                setGracefulList(arrayData);
            }
        })
    }

    //get classroom
    const getHomeClassroomList = () => {
        getClassroomList(null).then(async res => {
            if (res?.code == 200) {
                const arrayData = chunk(res?.data, 3);//分组
                setClassroomList(arrayData);
            }
        })
    }

    //get project
    const getProjectList = () => {
        getHomeProject(null).then(res => {
            if (res?.code == 200) {
                let data: any[] = [];
                if (res?.data.length > 10) {
                    data = res?.data.slice(0, 10);
                } else {
                    data = res?.data;
                }
                setProjectList(data);
            }
        })
    }

    //get right
    const getRightList = () => {
        getHomeRight().then(res => {
            if (res?.code == 200) {
                if (res?.data.length > 0) {
                    setRightList(res?.data);
                }
            }
        })
    }

    //get contact
    const getContactList = (param: string) => {
        getHomeContact({ param }).then(res => {
            if (res?.code == 200) {
                const data = Object.entries(res?.data);
                if (data.length > 3) {
                    setContactData(data.slice(0, 3));
                    setTotalContactData(data);
                } else {
                    setContactData(data);
                }
            }
        })
    }

    //to detail
    const detailClick = (data: any) => {
        sessionStorage.setItem("detailData", JSON.stringify(data));
        window.open("/highQualityOperation/detail");
        sessionStorage.removeItem("detailData");
    }

    //other buttom onclick
    const bottomOtherClick = (param: string) => {
        if (param == '0') {
            setContactData([...totalContactData]);
        } else {
            setContactData([...totalContactData.slice(0, 3)]);
        }
    }
    //right learn click
    const learnClick = (rightData: any[], index: number) => {
        if (rightData && rightData.length > 0 && START_ENV == "PROD") {
            window.open(rightData[index].dataValue);
        }
    }
    const handleChange = (tag: string, checked: boolean) => {
        const nextSelectedTag = checked ? tag : '';
        getContactList(nextSelectedTag);
        setSelectedTag(nextSelectedTag);
    };

    useEffect(() => {
        getBannerList();
        getGracefulList();
        getHomeClassroomList();
        getProjectList();
        getRightList();
        getContactList('');
    }, [])

    return (
        <div className="h-topic-global">
            <div className="topic-background">
                <div className="top-picture">
                    <img src={header} />
                </div>
                <div className="top-global">
                    <div className='left-global'>
                        <Carousel className='left-carousel' autoplay autoplaySpeed={5000}>
                            {bannerList?.length > 0 && bannerList.map(item => (
                                <div key={item.id}>
                                    <div className='carousel-content' style={{ backgroundImage: `url(${getImageUrl(item.filePath, topic_banner_default)})` }} onClick={() => detailClick(item)}>
                                        <div className='carousel-textbg'>
                                            <div className='carousel-text'>
                                                <span>{item.imageWord}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </Carousel>
                        <div className='left-activity'></div>
                        <div className='left-card'>
                            <div className='left-project'>
                                <LeftCardTop title="工作风采" url="/highQualityOperation/jobStyleList" />
                                <Carousel autoplay autoplaySpeed={5000} effect="fade" dots={false}>
                                    {gracefulList?.length > 0 && gracefulList.map((array, index) => (
                                        <div key={index}>
                                            <Row gutter={[24, 24]}>
                                                {array.map((item: any, index: any) => (
                                                    <Col span={8} key={index}>
                                                        <div className='left-graceful-bg' style={{ backgroundImage: `url(${getImageUrl(item.filePath, topic_activity_default)})` }} onClick={() => detailClick(item)}>
                                                            <div className='left-graceful-textbg'>
                                                                <span className='left-graceful-text'>{item.title}</span>
                                                            </div>
                                                        </div>
                                                    </Col>
                                                ))}
                                            </Row>
                                        </div>
                                    ))}
                                </Carousel>
                            </div>
                            <div className='left-project'>
                                <LeftCardTop title="运营提升小课堂" url="/highQualityOperation/classroomList" />
                                <Carousel autoplay={autoplay} autoplaySpeed={5000} effect="fade" dots={false}>
                                    {classroomList.length > 0 && classroomList.map((array, index) => (
                                        <div key={index}>
                                            <Row gutter={[24, 24]}>
                                                {array.map((item: any, index: any) => (
                                                    <Col span={8} key={index}>
                                                        <div className='left-classroom'>
                                                            <div className='left-classroom-bg' >
                                                                <ReactPlayer
                                                                    url={downloadVideo + item.image}
                                                                    playing={false}
                                                                    controls={isEmpty(videoPlayKey) || item.id === videoPlayKey}
                                                                    muted={true}
                                                                    width="100%"
                                                                    height="100%"
                                                                    style={{}}
                                                                    onPlay={() => { setAutoplay(false); setVideoPlayKey(item.id) }}
                                                                    onPause={() => { setAutoplay(true); setVideoPlayKey("") }}
                                                                />
                                                            </div>
                                                            <div className='left-classroom-textbg'>
                                                                <span onClick={() => detailClick(item)}>{item.title}</span>
                                                            </div>
                                                        </div>
                                                    </Col>
                                                ))}
                                            </Row>
                                        </div>
                                    ))}
                                </Carousel>
                            </div>
                            <div className='left-project'>
                                <LeftCardTop title="高质量运营标杆项目" url="/highQualityOperation/markProjectList" />
                                <div className='left-project-content'>
                                    <img src={project_left} />
                                    <div className='left-project-content-list'>
                                        <List
                                            size='small'
                                            split={false}
                                            dataSource={projectList}
                                            renderItem={item => (
                                                <List.Item>
                                                    <div className='left-project-content-item'>
                                                        <a onClick={() => detailClick(item)} className='left-project-content-item-title'>{item.title}</a>
                                                        <span className='left-project-content-item-time'>{formatTime(item.createTime, 'MM-DD HH:mm')}</span>
                                                    </div>
                                                </List.Item>
                                            )}
                                        />
                                    </div>
                                </div>
                            </div>
                            <div className='left-project'>
                                <LeftCardTop title="接口人信息" />
                                <div className='bottom-select'>
                                    <span className='bottom-select-label'>按省分查询：</span>
                                    <div>
                                        {totalContactData.length > 0 && totalContactData.map(([name, value]) => (
                                            <CheckableTag
                                                className='bottom-select-tag'
                                                key={name}
                                                checked={selectedTag === name}
                                                onChange={checked => handleChange(name, checked)}
                                            >
                                                {name}
                                            </CheckableTag>
                                        ))}
                                    </div>
                                </div>
                                {contactData.length > 0 && contactData.map(([name, value], index) => (
                                    <div key={index}>
                                        <div className='bottom-title'>{name}</div>
                                        <div className='bottom-content'>
                                            <Row gutter={[14, 12]}>
                                                {value.map((item: any) => (
                                                    <BottomCardContent data={item} key={item.id} onClick={() => openModal(item)} />
                                                ))}
                                            </Row>
                                        </div>
                                    </div>
                                ))}
                                {contactData.length != 0 && contactData.length > 2 && (
                                    <div className='bottom-other'>
                                        <div>
                                            <span className='bottom-other-text' onClick={() => bottomOtherClick(contactData.length > 3 ? '1' : '0')}>{contactData.length > 3 ? '收起' : '更多'}</span>
                                            <span className='bottom-other-icon'>{contactData.length > 3 ? <>&lt;&lt;&lt;</> : <>&gt;&gt;&gt;</>}</span>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                    <div className='right-global'>
                        <div>
                            <img src={material} className='right-material' onClick={() => window.open("/highQualityOperation/partyBranch")} />
                        </div>
                        <div className='right-display'>
                            <div className='right-display-title'>
                                党员及支部数量情况
                            </div>
                            <RightDisplayContent index={1} data={rightList} img={partybranch} color="number-blue" />
                            <RightDisplayContent index={0} data={rightList} img={partymember} color="number-blue" />
                        </div>
                        <div className='right-learn'>
                            <div className='right-learn-title' onClick={() => learnClick(rightList, 10)}>
                                <span>学习园区</span>
                            </div>
                            <div className='right-learn-test' onClick={() => learnClick(rightList, 11)}>
                                <span>自测学习</span>
                            </div>
                            <div className='right-learn-exam' onClick={() => learnClick(rightList, 12)}>
                                <span>集中考试</span>
                            </div>
                            <div className='right-learn-rank'>
                                <div className='right-learn-rank-title'>
                                    <span>排名榜</span>
                                </div>
                                <div className='right-learn-rank-content'>
                                    <div className='rank-title'>
                                        <span>分子公司榜</span>
                                    </div>
                                    <div className='rank-list'>
                                        <img src={star1} className='rank-list-star1' />
                                        <img src={star2} className='rank-list-star2' />
                                        <img src={star3} className='rank-list-star3' />
                                        {new Array(10).fill(0).map((item, index) => (
                                            <p>
                                                <span className={`star${index}`}>{index + 1}</span>
                                                <span>山东</span>
                                                <span>99</span>
                                            </p>
                                        ))}
                                    </div>
                                </div>
                                <div className='right-learn-rank-content'>
                                    <div className='rank-title-people'>
                                        <span>个人榜</span>
                                    </div>
                                    <div className='rank-list'>
                                        <img src={star1} className='rank-list-star1' />
                                        <img src={star2} className='rank-list-star2' />
                                        <img src={star3} className='rank-list-star3' />
                                        {new Array(10).fill(0).map((item, index) => (
                                            <p>
                                                <span className={`people-rank star${index}`}>{index + 1}</span>
                                                <span>山东</span>
                                                <span className='people-rank'>张三&nbsp;99</span>
                                            </p>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className='right-card'>
                            <RightCardTitle title="高质量运营指标" />
                            <RightCardContent index={6} data={rightList} img={card_img_6} color="number-green" />
                            <RightCardContent index={7} data={rightList} img={card_img_7} color="number-green" />
                            <RightCardContent index={8} data={rightList} img={card_img_8} color="number-green" />
                            <RightCardContent index={9} data={rightList} img={card_img_9} color="number-green" />
                        </div>
                        <div className='right-card'>
                            <RightCardTitle title="2023年订单交易情况" />
                            <RightCardContent index={2} data={rightList} img={card_img_2} color="number-blue" />
                            <RightCardContent index={3} data={rightList} img={card_img_3} color="number-blue" />
                            <RightCardContent index={4} data={rightList} img={card_img_4} color="number-blue" />
                            <RightCardContent index={5} data={rightList} img={card_img_5} color="number-blue" />
                        </div>
                        {managerAuthority("ebtp-party-admin") ? null : (
                            <div className='right-card'>
                                <RightCardTitle title="高质量运营配置管理" onClick={() => window.open("/highQualityOperation/manage")} />
                            </div>
                        )}
                    </div>
                </div>
                <div className='bottom-global'></div>
                <CommentModal visible={adviceVisible} closeModal={() => closeModal()} data={adviceItemData} userData={userData} />
            </div>
        </div>
    );
};

export default Home;