import './agent-select.css';
import {Link, useNavigate, useParams} from "react-router-dom";
import {Breadcrumb, Button, Divider, Image, message, Modal, Radio, RadioChangeEvent, Spin} from "antd";
import CardAgent from "../../components/card/CardAgent.tsx";
import {errorImage} from "../../util/CommonUtil.ts";
import {useEffect, useState} from "react";
import {AgentMedalEnum} from "../../interfaces/card/ICardProj.ts";
import NoData from '../../assets/no-data.png';
import {get, downloadUrl, post} from "../../util/AjaxUtils.ts";
import {IListPage} from "../../interfaces/listpage/IListPage.ts";

enum AgentPriceType {
    NORMAL = 'NORMAL',
    URGENT = 'URGENT'
}

type AgentPrice = {
    priceType: AgentPriceType;
    priceTypeText: string;
    typePrice: number;
}

type AgentDTO = {
    basicsAddresss: string;
    basicsCertification: string;
    basicsContactNumber: string;
    basicsContactPerson: string;
    basicsId: string;
    basicsIntro: string;
    basicsLogo: string;
    basicsName: string;
    priceDTOS: AgentPrice[];
}

type Agent = {
    id: string,
    logo: string,
    name: string,
    desc: string,
    medal: AgentMedalEnum,
    certificateImg: string,
    selected: false
}


export default function AgentSelect() {

    const [messageApi, contextHolder] = message.useMessage();
    const nav = useNavigate();
    const pathParams = useParams();
    const height = window.innerHeight - 150;

    const [modal, modalHolder] = Modal.useModal();
    const [page, setPage] = useState(1);
    const [agentList, setAgentList] = useState<Agent[]>([]);
    const [selectedAgentId, setSelectedAgentId] = useState('0');
    const [showAgentMoreBtn, setShowAgentMoreBtn] = useState(true);
    const [isAgentListLoading, setIsAgentListLoading] = useState(false);
    const [selectedAgent, setSelectedAgent] = useState<AgentDTO>();
    const [isAgentLoading, setIsAgentLoading] = useState(false);
    const [selectedPriceValue, setSelectedPriceValue] = useState('');
    const [isConfirmLoading, setIsConfirmLoading] = useState(false);


    const getSelectedAgentData = (basicsId: string) => {
        get<AgentDTO>({
            messageApi,
            url: `/api/agent/get/${basicsId}`,
            onBefore() {
                setIsAgentLoading(true);
            },
            onSuccess({data}) {
                setSelectedAgent({
                    ...data
                });
                setSelectedPriceValue(`${data.priceDTOS[0].priceType}:${data.priceDTOS[0].typePrice}`)
            },
            onFinally() {
                setIsAgentLoading(false);
            }
        })
    }

    useEffect(() => {
        get<IListPage<AgentDTO>>({
            messageApi,
            url: `/api/agent/listpage`,
            config: {
                params: {
                    page: page,
                    rows: 10
                }
            },
            onBefore() {
                setIsAgentListLoading(true);
            },
            onSuccess({data}) {
                if (data.rows.length == 0) {
                    setShowAgentMoreBtn(false);
                    return;
                }
                data.rows.forEach((item) => {
                    agentList.push({
                        id: item.basicsId,
                        logo: item.basicsLogo,
                        name: item.basicsName,
                        desc: item.basicsIntro,
                        medal: AgentMedalEnum.NORMAL,
                        certificateImg: item.basicsCertification,
                        selected: false
                    })
                })
                setAgentList([
                    ...agentList
                ])
            },
            onFinally() {
                setIsAgentListLoading(false);
            }
        })
    }, [page])

    const renderAgent = () => {
        return agentList.map((item, index) => {
            return (
                <CardAgent key={`agent${index}`} logo={item.logo}
                           name={item.name}
                           desc={item.desc}
                           medal={item.medal}
                           certificateImg={item.certificateImg}
                           selected={selectedAgentId == item.id}
                           handleSelect={() => {
                               setSelectedAgentId(item.id);
                               getSelectedAgentData(item.id);
                           }}
                />
            )
        })
    }

    /**
     * 证书
     * @param certification
     */
    const renderCertifications = (certification: string) => {
        if (certification) {
            return <></>
        }
        return certification.split(',').map(id => (
            <Image width={270}
                   height={170}
                   src={downloadUrl(id, false)}
                   preview={false}
                   fallback={errorImage}
            />
        ))
    }

    const renderPrice = (prices: AgentPrice[]) => {
        if (!prices) {
            return <></>
        }
        return prices.map((price, index) => <Radio value={`${price.priceType}:${price.typePrice}`}
                                                   key={`p${index}`}>{price.priceTypeText}￥：{(price.typePrice / 100)}</Radio>)
    }

    const renderSelectedAgent = () => {
        if (!selectedAgent) {
            return (
                <div className="no-data">
                    <Image src={NoData} preview={false}/>
                    <span>请选择左侧机构</span>
                </div>
            )
        }
        return (
            <>
                <div className="agent-info">
                    <div className="agent-title">机构信息</div>
                    <div className="agent-body">
                        <div className="agent-name">{selectedAgent.basicsName}</div>
                        <div className="agent-desc" dangerouslySetInnerHTML={{__html: selectedAgent.basicsIntro}}></div>
                        <Divider dashed style={{
                            marginTop: '10px',
                            marginBottom: '10px'
                        }}/>
                        <div className="agent-img-title">机构证书</div>
                        <div className="agent-img-list">{renderCertifications(selectedAgent.basicsId)}</div>
                        <Divider dashed style={{
                            marginTop: '10px',
                            marginBottom: '10px'
                        }}/>
                        <div className="agent-contact">
                            <div className="line">
                                <span>联系人：{selectedAgent.basicsContactPerson}</span>
                                <span>联系电话：{selectedAgent.basicsContactNumber}</span>
                            </div>
                            <div className="line">
                                <span>联系地址：{selectedAgent.basicsAddresss}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div className="agent-price">
                    <span className="label">价格种类：</span>
                    <Radio.Group onChange={(e: RadioChangeEvent) => {
                        setSelectedPriceValue(e.target.value);
                    }} defaultValue={selectedPriceValue}>{renderPrice(selectedAgent.priceDTOS)}</Radio.Group>
                </div>
                <div style={{marginTop: '15px', textAlign: 'center'}}>
                    <Button type="primary" style={{backgroundColor: 'var(--color-primary)'}} onClick={() => {
                        if (!selectedPriceValue) {
                            messageApi.error('请选择价格种类');
                            return;
                        }
                        modal.confirm({
                            title: '提示',
                            content: '确定选择此代理商吗？确认后，会扣除相应金额。',
                            okText: '确认',
                            cancelText: '取消',
                            okButtonProps: {
                                style: {
                                    backgroundColor: 'var(--color-primary)'
                                }
                            },
                            onOk: () => {
                                const priceArray = selectedPriceValue.split(':');
                                post({
                                    messageApi,
                                    url: `api/proj/save-agent-order/proj-id/${pathParams.projId}`,
                                    body: {
                                        basicsId: selectedAgent.basicsId,
                                        basicsName: selectedAgent.basicsName,
                                        priceType: priceArray[0],
                                        price: priceArray[1]
                                    },
                                    onBefore() {
                                        setIsConfirmLoading(true);
                                    },
                                    onSuccess() {
                                        messageApi.success('提交成功', 1, () => {
                                            nav(-1);
                                        });
                                    },
                                    onFinally() {
                                        setIsConfirmLoading(false);
                                    }
                                })
                            }
                        });
                    }}>选择</Button>
                </div>
            </>
        )
    }

    return (
        <>
            <Breadcrumb
                items={[
                    {title: <Link to="/">首页</Link>},
                    {title: <Link to="/proj-create">创建项目</Link>},
                    {title: <a onClick={() => {nav(-1)}}>编辑项目</a>},
                    {title: '找代理'},
                ]}
            />
            <div className="agent-select" style={{height: `${height}px`}}>
                <div className="agent-select-left">
                    <div className="list">
                        <Spin tip="正在加载" spinning={isAgentListLoading}>
                            <div className="list-item">
                                {renderAgent()}
                            </div>
                            {
                                showAgentMoreBtn ? (
                                    <div className="load">
                                        <Button type="text" onClick={() => {
                                            setPage(page + 1);
                                        }}>加载更多...</Button>
                                    </div>
                                ) : <></>
                            }
                        </Spin>
                    </div>
                </div>
                <Spin tip="正在加载" spinning={isAgentLoading}>
                    <div className="agent-select-right" style={{height: `${height - 30}px`}}>
                        {renderSelectedAgent()}
                    </div>
                </Spin>
            </div>
            <Spin tip="正在提交" spinning={isConfirmLoading}/>
            {contextHolder}
            {modalHolder}
        </>
    )
}