import './head.css'
import { useDispatch } from 'react-redux'
import BalanceHead from '../../components/balance/BalanceHead.tsx';
import RechargeHead from '../../components/recharge/RechargeHead.tsx';
import { Dropdown, MenuProps, message, Modal, Space, Spin, Input } from "antd";
import { DownOutlined, UserOutlined, QuestionCircleOutlined, BellOutlined, KeyOutlined, LogoutOutlined, GiftOutlined, AccountBookOutlined, ContainerOutlined, MenuFoldOutlined, UsergroupAddOutlined } from "@ant-design/icons";
import { useContext, useEffect, useState } from "react";
import { put, get, post,getUseUrl } from "../../util/AjaxUtils.ts";
import { GlobalContext, GlobalDispatchContext, reloadUser } from "../../context/GlobalContext.ts";
import UserEdit from "../../components/user/UserEdit.tsx";
import PasswordChange from "../../components/password/PasswordChange.tsx";
// import headRightBg from '../../assets/head-right-bg.png';
import InvoiceList from "../../components/invoice/InvoiceList.tsx";
import logoImg from '../../static/head/logo.png'
import userImg from '../../static/homeimg/userimg.png'
import { reMenuActive } from '../../util/cache';
// import BelongPeople from '../../components/BelongPeople/BelongPeople.tsx'
import BelongPeople from '../../components/BelongPeople/BelongPeople.tsx'
import ContactPeople from '../../components/ContactPeople/ContactPeople.tsx'
import inv from '../../static/inv.png'
import MyOrder from '../../components/myOrder/MyOrder.tsx'
import NoticeModal from '../../components/NoticeModal/NoticeModal.tsx';
// import HeadCouponModal from '../../components/CouponModal/HeadCouponModal.tsx'
export default function Head() {
    // const redxuState: any = useSelector(state => state)
    // const couponModal = redxuState.couponModal
    // 消息通知弹窗
    const [noticeModal, setNoticeModal] = useState(false)
    // 未读消息数
    const [unRead, setUnRead] = useState(0)
    // 获取未读消息总数
    const getUnRead = () => {
        get<any>({
            messageApi,
            url: '/api/user-msg/count-un-read/self',
            onSuccess({ data }) {
                // console.log(data);
                setUnRead(data.data)
            }
        })
    }

    // 邀请码弹窗
    const [invitationModal, setinvitationModal] = useState(false)
    // 邀请码弹窗加载
    const [isLoading, setisLoading] = useState(false)
    // 解除绑定邀请码弹窗
    // const [relieveModal, setRelieveModal] = useState(false)
    // 申请的邀请码
    const [invNum, setInvNum] = useState('')
    // 输入的邀请码
    const [inInvNum, setInInvNum] = useState('')
    // 已绑定的邀请码
    const [bindingInvNum, setBindingInvNum] = useState('')
    // 邀请码申请状态
    const [icStatus, setIcStatus] = useState('')
    // 邀请码返利比例
    const [icRebateRatio, seticRebateRatio] = useState('')
    // 全托管分账
    const [icPriceAll, seticPriceAll] = useState(0)
    // 写材料分账
    const [icPriceMaterial, seticPriceMaterial] = useState(0)
    // 获取邀请码申请状态
    const getIcStatus = () => {
        get<any>({
            messageApi,
            url: '/api/ic/apply/get/self',
            onSuccess({ data }) {
                // console.log(data);
                if (data) {
                    setIcStatus(data.applyStatus)
                }
            }
        })
    }
    // 获取邀请码信息
    const getIc = () => {
        get<any>({
            messageApi,
            url: '/api/ic/get/self',
            onBefore() {
                setisLoading(true)
            },
            onSuccess({ data }) {
                // console.log(data);
                setInvNum(data.ic)
                setBindingInvNum(data.relationIc)
                seticRebateRatio(data.icRebateRatio)
                seticPriceAll(Number(data.icPriceAll) / 100 * Number(data.icRebateRatio) / 100)
                seticPriceMaterial(Number(data.icPriceMaterial) / 100 * Number(data.icRebateRatio) / 100)
                if (data.ic == '') {
                    getIcStatus()
                }
            },
            onFinally() {
                setisLoading(false)
            }
        })
    }
    // 绑定邀请码
    const putIc = () => {
        put<any>({
            messageApi,
            url: `/api/ic/update-relation-ic`,
            body: {
                value: inInvNum
            },
            onBefore() {

            },
            onSuccess() {
                // messageApi.success('保存成功,点击编辑按钮可继续修改项目简介');
                //    console.log(data);
                getIc()
            },
            onFinally() {

            }
        })
    }
    // 确定输入的邀请码事件
    const postInvNum = () => {
        if (!inInvNum) {
            messageApi.open({
                type: 'error',
                content: '请输入邀请码'
            })
        } else {
            // setBindingInvNum(inInvNum)
            // messageApi.open({
            //     type: 'success',
            //     content: '已绑定邀请码'
            // })
            putIc()
        }
    }
    // 点击获取邀请码
    const getInvNum = () => {
        post<any>({
            messageApi,
            url: `/api/ic/apply/apply`,
            onBefore() {

            },
            onSuccess() {
                messageApi.success('已申请')
                getIcStatus()
            },
            onFinally() {

            }
        })
        // setInvNum('RSDNQ5H7')
    }
    // 复制邀请码
    const copyInvNum = () => {
        // navigator.clipboard.writeText(invNum)
        // messageApi.open({
        //     type: 'success',
        //     content: '已复制到剪切板'
        // })
        // 创建一个临时的 input 元素
        const tempInput = document.createElement('input');
        document.body.appendChild(tempInput);
        tempInput.value = invNum;

        // 选中 input 中的内容
        tempInput.select();
        tempInput.setSelectionRange(0, 99999); // 对于移动设备的支持

        // 执行复制操作
        try {
            document.execCommand('copy');
            messageApi.open({
                type: 'success',
                content: '已复制到剪切板'
            })
        } catch (err) {
            messageApi.open({
                type: 'error',
                content: '复制失败,请手动复制'
            })
        }

        // 移除临时的 input 元素
        document.body.removeChild(tempInput);
    }

    const dispath = useDispatch()
    // 更新所属者表格储存至redux 
    const upBelongArray = () => {
        get({
            messageApi,
            url: `/api/proj-owner/list/self`,
            onBefore() {

            },
            onSuccess(data: any) {
                // console.log('所属者表格', data.data);
                // setBelongPeopleArray(data.data)
                // 存redux的belongArray
                dispath({
                    type: 'uparray',
                    val: data.data
                })
            },
            onFinally() {

            }
        })
    }
    const globalContext = useContext(GlobalContext);
    const globalDispatchContext = useContext(GlobalDispatchContext);
    const [messageApi, contextHolder] = message.useMessage();
    const [modal, modalHolder] = Modal.useModal();
    const [loading, setLoading] = useState<boolean>(false);
    const [isSelfModalOpen, setIsSelfModalOpen] = useState(false);
    const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(false);
    const [isInvoiceModalOpen, setIsInvoiceModalOpen] = useState(false);
    // 我的订单弹窗
    const [myorderModal, setMyorderModal] = useState(false)
    // 所属者弹窗
    const [belongModal, setBelongModal] = useState(false)
    const [belongPeopleInfo, setBelongPeopleInfo] = useState({
        authorName: '',
        authorType: '',
        authorIdCardType: '',
        authorIdCard: '',
        authorCrcAccount: '',
        authorId: '',
        authorProvinceCity: ''
    })

    const setValue = () => {
        // console.log(value);
    }
    const setConcatValue = () => {

    }
    // 联系人弹窗
    const [contactModal, setContactModal] = useState(false)
    const [concatPeopleInfo, setConcatPeopleInfo] = useState({
        applyConcatId: '',
        applyContactCsaNo: '',
        applyContactEmail: '',
        applyContactName: '',
        applyContactPhone: '',
        applyContactCompany: ''
    })
    // 优惠券弹窗
    // const [couponModal, setCouponModal] = useState(false)
    // const [belongArray,setBelongArray] = useState([])
    // // 获取初始所属者数组
    // const getLength = () => {
    //     get({
    //         messageApi,
    //         url: `/api/proj-owner/list/self`,
    //         onBefore() {

    //         },
    //         onSuccess(data: any) {
    //             // console.log('所属者表格', data.data);
    //             // setBelongPeopleArray(data.data)
    //             setBelongArray(data.data )
    //         },
    //         onFinally() {

    //         }
    //     })
    // }
    // // 获取更新的所属者数组并且做对比查看是否刷新网页
    // const getNewLength = () => {
    //     get({
    //         messageApi,
    //         url: `/api/proj-owner/list/self`,
    //         onBefore() {

    //         },
    //         onSuccess(data: any) {
    //             // console.log('所属者表格', data.data);
    //             // setBelongPeopleArray(data.data)
    //             console.log('查看结果',data.data != belongArray);

    //             // if (data.data == belongArray) {
    //             //     window.location.reload();
    //             // }
    //         },
    //         onFinally() {

    //         }
    //     })
    // }

    useEffect(() => {
        // getLength()
        reloadUser(messageApi, globalDispatchContext).then((data) => {
            if (!data.hasUserInfo) {
                setIsSelfModalOpen(true);
            }
        });
    }, [globalContext.user]);
    useEffect(() => {
        getUnRead()
    }, [])
    const items: MenuProps['items'] = [
        {
            key: 'userinfo',
            label: (
                <div className="dropdown-item">
                    <UserOutlined />
                    <span className="title">个人信息</span>
                </div>
            ),
            onClick: () => {
                setIsSelfModalOpen(true);
            }
        },
        {
            key: 'changePass',
            label: (
                <div className="dropdown-item">
                    <KeyOutlined />
                    <span className="title">修改密码</span>
                </div>
            ),
            onClick: () => {
                setIsPasswordModalOpen(true);
            }
        },
        {
            key: 'invoice',
            label: (
                <div className="dropdown-item">
                    <AccountBookOutlined />
                    <span className="title">发票管理</span>
                </div>
            ),
            onClick: () => {
                setIsInvoiceModalOpen(true);
            }
        },
        {
            key: 'myorder',
            label: (
                <div className="dropdown-item">
                    {/* <UsergroupAddOutlined /> */}
                    <ContainerOutlined />
                    <span className="title">我的订单</span>
                </div>
            ),
            onClick: () => {
                setMyorderModal(true)
            }
        },
        {
            key: 'belong',
            label: (
                <div className="dropdown-item">
                    <MenuFoldOutlined />
                    <span className="title">产权所属者</span>
                </div>
            ),
            onClick: () => {
                setBelongModal(true)
            }
        },
        {
            key: 'contact',
            label: (
                <div className="dropdown-item">
                    <UsergroupAddOutlined />
                    <span className="title">产权联系人</span>
                </div>
            ),
            onClick: () => {
                setContactModal(true)
            }
        },
        {
            key: 'coupon',
            label: (
                <div className="dropdown-item">
                    <GiftOutlined />
                    <span className="title">优惠券</span>
                </div>
            ),
            onClick: () => {
                // setCouponModal(true)
                dispath({
                    type: 'changeCouponModal',
                    val: true
                })
            }
        },

        {
            key: 'logout',
            label: (
                <div className="dropdown-item">
                    <LogoutOutlined />
                    <span className="title">退出系统</span>
                </div>
            ),
            onClick: () => {
                reMenuActive()

                window.location.href = '/copyright/logout'
            }
        },


    ]

    return (
        <>
            <div className="head">
                <div className="center">
                    <div className="left">
                        {/* <span className="sys-title">AI引擎软著</span>
                        <Divider type="vertical"/>
                        <span className="sys-title-sub">软件著作权一站式服务平台</span> */}
                        <img src={logoImg} alt="" />
                    </div>
                    {/* <div className="right" style={{backgroundImage: `url(${headRightBg})`}}> */}

                    <div className="right">

                        {/* <div className='head-nav' onClick={() => {
                            window.open('https://www.aimzhu.com/operator/route/agreementportal/view?agreementId=c0c5683a-bef3-40c3-8395-900a362ea234&title=系统操作流程')
                        }}>
                            <QuestionCircleOutlined />
                        </div> */}
                        {/* <div className='headLine'></div> */}
                        <BalanceHead />
                        {/* <div className='headLine'></div> */}
                        <RechargeHead />
                        <div className='headLine'></div>
                        <div className='invitationButton' onClick={() => {
                            setinvitationModal(true)
                            getIc()
                        }}>
                            邀请码
                        </div>
                        <div className='headLine'></div>
                        <div className='head-nav' title='系统操作流程' onClick={() => {

                            // window.open('https://www.aimzhu.com/operator/route/agreementportal/view?agreementId=c0c5683a-bef3-40c3-8395-900a362ea234&title=系统操作流程')
                            getUseUrl()

                        }}>
                            <QuestionCircleOutlined />
                        </div>
                        <div className='headLine'></div>
                        <div className='head-notice' onClick={() => {
                            setNoticeModal(true)
                        }}>
                            <BellOutlined />
                            <div className='noticeNum' style={{ display: unRead == 0 ? 'none' : 'block' }}>{unRead}</div>
                        </div>
                        <div className='headLine'></div>

                        {/*<MessageHead/>*/}
                        <div style={{ display: 'flex', alignContent: 'center', padding: '0', cursor: 'pointer' }}>
                            <div style={{ width: '50px', height: '50px', borderRadius: '25px', marginLeft: '', marginRight: '10px' }} >
                                <img src={userImg} alt="" width={50} height={50} />
                            </div>
                            <Dropdown menu={{
                                items: items
                            }}>
                                <Space>
                                    {/* 您好：{globalContext.user.nickname} */}
                                    个人中心
                                    <DownOutlined />
                                </Space>
                            </Dropdown>
                        </div>
                    </div>
                </div>
            </div>
            <Modal open={isSelfModalOpen}
                destroyOnClose={true}
                title="个人信息"
                footer={false}
                onCancel={() => {
                    if (!globalContext.user.hasUserInfo) {
                        messageApi.info('请完善个人信息');
                        return;
                    }
                    setIsSelfModalOpen(false)
                    // console.log('用户信息',globalContext.user.hasUserInfo);

                }}>
                <UserEdit handleConfirm={(data) => {
                    modal.confirm({
                        title: '提示',
                        content: '确定保存吗？',
                        okText: '确认',
                        cancelText: '取消',
                        okButtonProps: {
                            style: {
                                backgroundColor: 'var(--color-primary)'
                            }
                        },
                        onOk: () => {
                            setIsSelfModalOpen(false);
                            put({
                                messageApi,
                                url: '/api/user-info/update-self',
                                body: data,
                                onBefore() {
                                    setLoading(true);
                                },
                                onSuccess() {
                                    messageApi.success('修改成功');
                                },
                                onFinally() {
                                    setLoading(false);
                                }
                            })
                        }
                    });
                }} />
            </Modal>
            <Modal open={isPasswordModalOpen}
                title="修改密码"
                footer={false}
                onCancel={() => {
                    setIsPasswordModalOpen(false)
                }}>
                <PasswordChange handleConfirm={(data) => {
                    modal.confirm({
                        title: '提示',
                        content: '确定修改吗？',
                        okText: '确认',
                        cancelText: '取消',
                        okButtonProps: {
                            style: {
                                backgroundColor: 'var(--color-primary)'
                            }
                        },
                        onOk: () => {
                            put({
                                messageApi,
                                url: '/api/user/update-password',
                                body: data,
                                onBefore() {
                                    setLoading(true);
                                },
                                onSuccess() {
                                    setIsPasswordModalOpen(false);
                                    messageApi.success('修改成功，重新登录生效');
                                },
                                onFinally() {
                                    setLoading(false);
                                }
                            })
                        }
                    });
                }} />
            </Modal>
            <Modal open={isInvoiceModalOpen}
                title="发票管理"
                width={1100}
                footer={false}
                onCancel={() => setIsInvoiceModalOpen(false)}
            >
                <InvoiceList />
            </Modal>
            <Modal title="知识产权所属者"
                destroyOnClose

                open={belongModal}
                width={1200}

                footer={null}
                onCancel={() => {
                    upBelongArray()
                    // getNewLength()
                    setBelongModal(false)

                }}>

                <BelongPeople closeModal={() => { setBelongModal(false) }} setBelongPeopleInfo={setBelongPeopleInfo} belongPeopleInfo={belongPeopleInfo} setValue={setValue} isShow={false} ></BelongPeople>
            </Modal>
            <Modal title="知识产权联系人"
                destroyOnClose

                open={contactModal}
                width={1200}

                footer={null}
                onCancel={() => {
                    setContactModal(false)

                }}>

                <ContactPeople isShow={false} closeModal={() => { setContactModal(false) }} setConcatPeopleInfo={setConcatPeopleInfo} concatPeopleInfo={concatPeopleInfo} setConcatValue={setConcatValue}></ContactPeople>
            </Modal>
            <Modal title="邀请码"
                destroyOnClose

                open={invitationModal}
                width={578}

                footer={null}
                onCancel={() => {
                    // getNewLength()
                    setinvitationModal(false)
                    setInvNum('')
                    setInInvNum('')
                }}>
                <Spin tip="加载中..." spinning={isLoading}>
                    <div className='invitation-box'>
                        <div className='invBox-top'>
                            <div className='invBox-title'>
                                我的邀请码
                            </div>
                            <div className='invBox-line'></div>
                            <div className='invBox-btn' onClick={() => {
                                getInvNum()
                            }} style={{ display: invNum || icStatus ? 'none' : 'block' }}>
                                点击申请
                            </div>
                            <div className='invBox-btnTwo' style={{ display: icStatus == 'PENDING' ? 'block' : 'none' }}>
                                正在申请中
                            </div>
                            <div className='invBox-btnthree' style={{ display: icStatus == 'REJECTED' ? 'block' : 'none' }}>
                                <div className='errorBox'>
                                    <div className='errorBox-title'> 申请失败!</div>
                                    <div className='errorBox-btn' onClick={() => {
                                        getInvNum()
                                    }}>重新申请</div>
                                </div>

                            </div>
                            <div className='invBox-Num' style={{ display: invNum ? 'block' : 'none' }}>
                                <div className='invNum-box'>
                                    <div className='invNum'>
                                        {invNum}
                                    </div>
                                    <div className='copyBtn' onClick={() => {
                                        copyInvNum()
                                    }}>
                                        复制
                                    </div>
                                </div>
                            </div>
                        </div>
                        {/* <div style={{ display: icRebateRatio ? 'block' : 'none' }}> */}
                        <div className='invBox-bot'>
                            <div className='invBox-tips' >
                                {/* {icRebateRatio ? `邀请码分享给他人，即可获得${icRebateRatio}%佣金` : '邀请码分享给他人，即可获得佣金'} */}
                                {icRebateRatio ?
                                    (<div>
                                        <div>  邀请码分享给他人，即可获得{icRebateRatio}%佣金</div>
                                        <div style={{ paddingBottom: 20 }}>全托管佣金:{icPriceAll}元，写材料佣金:{icPriceMaterial}元</div>
                                    </div>

                                    )
                                    : (<>邀请码分享给他人，即可获得佣金</>)}
                                {/*  */}

                            </div>
                            {/* <div className='invBox-tips'>
                            失败的原因可能是XXXXXX导致,如有疑问请您咨询客服人员
                        </div> */}
                        </div>
                        {/* </div> */}
                    </div>
                    <div className='invitation-box'>
                        <div className='invBox-top'>
                            <div className='invBox-title' style={{ fontSize: '24px' }}>
                                他人邀请码
                            </div>
                            <div className='invBox-line'></div>
                            <div className='invBox-input' style={{ display: bindingInvNum ? 'none' : 'block' }}>
                                <div className='invInput'>
                                    <Input value={inInvNum} style={{ width: 261, height: 60, borderRadius: 25, fontSize: 24, textAlign: 'center' }} onChange={(e) => {
                                        setInInvNum(e.target.value)
                                    }} />
                                    <div className='invImg' onClick={() => {
                                        postInvNum()
                                    }}>
                                        <img src={inv} alt="" style={{ width: 31, height: 30 }} />
                                    </div>
                                </div>
                            </div>
                            <div className='invBox-input' style={{ display: bindingInvNum ? 'block' : 'none' }}>
                                <div className='invInput'>
                                    <div className='invNum-box'>
                                        <div className='invNum' >
                                            {bindingInvNum}
                                        </div>
                                        {/* <div className='relieveBtn' onClick={() => {
                                        setRelieveModal(true)
                                    }}>
                                        解绑
                                    </div> */}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className='invBox-bot'>
                            <div className='invBox-tips' >
                                {bindingInvNum ? '已绑定邀请码' : '输入他人的邀请码，即可获得相应优惠'}
                            </div>


                        </div>
                    </div>
                </Spin>
            </Modal>
            {/* <Modal title="提示"
                okText="确认"
                cancelText="取消"
                destroyOnClose
                open={relieveModal}
                onOk={() => {
                    setBindingInvNum('')
                    setInInvNum('')
                    setRelieveModal(false)
                }}
                onCancel={() => {
                    setRelieveModal(false)

                }}>
                <div>
                    确定解绑当前邀请码吗?
                </div>
            </Modal> */}
            <Modal title="我的订单"
                footer={null}
                // okText="确认"
                // cancelText="取消"
                destroyOnClose
                open={myorderModal}
                // onOk={() => {
                //     setBindingInvNum('')
                //     setInInvNum('')
                //     setRelieveModal(false)
                // }}
                width={1500}
                onCancel={() => {
                    setMyorderModal(false)

                }}>
                <MyOrder></MyOrder>
            </Modal>
            <Modal title="消息通知"
                footer={null}

                destroyOnClose
                open={noticeModal}

                width={1200}
                onCancel={() => {
                    setNoticeModal(false)
                    getUnRead()
                    // setUnRead(0)
                }}>
                <NoticeModal></NoticeModal>
            </Modal>
            {/* <Modal title="优惠券"
                footer={null}

                destroyOnClose
                open={couponModal}

                width={809}
                onCancel={() => {
                    // setCouponModal(false)
                    // setUnRead(0)
                }}>
                <HeadCouponModal closeModal={() => {
                    // setCouponModal(false)
                }}></HeadCouponModal>
            </Modal> */}

            <Spin tip="正在提交..." spinning={loading} fullscreen />
            {contextHolder}
            {modalHolder}
        </>
    )
}
