import './agent-agreement.css'
import {Link, useParams} from "react-router-dom";
import {
    Breadcrumb,
    Button,
    GetProp,
    message,
    Spin,
    Table,
    TableProps,
    Tag,
    Upload,
    UploadProps
} from "antd";
import {useEffect, useState} from "react";
import {DevUserId, get, put, uploadFileUrl} from "../../util/AjaxUtils.ts";
import {IListPage} from "../../interfaces/listpage/IListPage.ts";
import useMessage from "antd/es/message/useMessage";
import useModal from "antd/es/modal/useModal";
import {DownloadOutlined, UploadOutlined} from "@ant-design/icons";

type TableDataType = {
    orderId: string;
    signDate: string;
    signFileId: string;
    creator: string;
    gmtCreate: string;
    orderAgreementFile: string;
    orderAgreementId: string;
    orderAgreementName: string;
    orderAgreementNote: string;
    orderAgreementStatus: string;
    orderAgreementStatusText: string;
}

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

export default function AgentAgreement() {
    const pathParams = useParams();
    const [messageApi, contextHolder] = useMessage();
    const [modal, modalHolder] = useModal();
    const [isLoading, setIsLoading] = useState(false);
    const [isConfirmLoading, setIsConfirmLoading] = useState(false);
    const [page, setPage] = useState(1);
    const [total, setTotal] = useState(0);
    const [dataArray, setDataArray] = useState<TableDataType[]>([]);
    const [uploadSignFileId, setUploadSignFileId] = useState('');

    const domHeight = window.innerHeight - 180;

    const beforeUpload = (file: FileType) => {
        const isJpgOrPng = file.type === 'application/pdf';
        if (!isJpgOrPng) {
            message.error('只能上传 PDF 格式文件!');
            return;
        }
        return isJpgOrPng;
    };

    const columns: TableProps<TableDataType>['columns'] = [
        {
            title: '协议名称',
            dataIndex: 'orderAgreementName',
            key: 'orderAgreementName',
            align: 'center',
            width: 200
        },
        {
            title: '协议备注',
            dataIndex: 'orderAgreementNote',
            key: 'orderAgreementNote',
            align: 'center',

        },
        {
            title: '协议状态',
            dataIndex: 'orderAgreementStatusText',
            key: 'orderAgreementStatusText',
            align: 'center',
            width: 150,
            render: value => {
                return <Tag color="geekblue">{value}</Tag>
            }
        },
        {
            title: '创建时间',
            dataIndex: 'gmtCreate',
            key: 'gmtCreate',
            align: 'center',
            width: 180
        },
        {
            title: '协议签订时间',
            dataIndex: 'signDate',
            key: 'signDate',
            align: 'center',
            width: 180,
            render: (value) => {
                if(value) {
                    return value;
                }
                return '-'
            }
        },
        {
            title: '甲方协议',
            dataIndex: 'orderAgreementId',
            key: 'orderAgreementId',
            align: 'center',
            width: 100,
            render: (value) => {
                return <a href={value} download><DownloadOutlined /> 下载</a>
            }
        },
        {
            title: '乙方协议',
            dataIndex: 'signFileId',
            key: 'signFileId',
            align: 'center',
            width: 150,
            render: (value) => {
                if(value) {
                    return <a href={value} download><DownloadOutlined /> 下载</a>
                }
                return (
                    <Upload name="file"
                            action={uploadFileUrl()}
                            headers={{'X-USER-ID': DevUserId}}
                            beforeUpload={beforeUpload}
                            maxCount={1}
                            onChange={
                                (info) => {
                                    if (info.file.status !== 'uploading') {
                                        console.log(info.file, info.fileList);
                                    }
                                    if (info.file.status === 'done') {
                                        message.success('上传成功');
                                        info.file.name = '协议文件';
                                        setUploadSignFileId(info.file.response.data.fileId);
                                    } else if (info.file.status === 'error') {
                                        message.error('上传失败');
                                    }
                                }
                            }
                            onRemove={() => {
                                setUploadSignFileId('');
                            }}
                    >
                        <a href="/#" onClick={(e)=>{
                            e.preventDefault();
                        }}><UploadOutlined /> {uploadSignFileId ? '重新上传' : '上传'}</a>
                    </Upload>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'option',
            key: 'option',
            align: 'center',
            width: 120,
            render: (_value, record) => {
                if(!uploadSignFileId) {
                    return <>-</>
                }
                return (
                    <Button size="small" type="primary" style={{backgroundColor: 'var(--color-primary)'}} onClick={() => {
                        modal.confirm({
                            title: '提示',
                            content: '确定提交吗？',
                            okText: '确定',
                            cancelText: '取消',
                            okButtonProps: {
                                style: {
                                    backgroundColor: 'var(--color-primary)'
                                }
                            },
                            onOk: () => {
                                put<any>({
                                    messageApi,
                                    url: `/api/agent/order/agreement/update`,
                                    body: {
                                        orderAgreementId: record.orderAgreementId,
                                        fileId: uploadSignFileId
                                    },
                                    onBefore() {
                                        setIsConfirmLoading(true);
                                    },
                                    onSuccess() {
                                        messageApi.success('提交成功，等待审核');
                                        getData();
                                    },
                                    onFinally() {
                                        setIsConfirmLoading(false);
                                    }
                                })
                            }
                        })
                    }}>提交协议</Button>
                )
            }
        },
    ];

    const getData = () => {
        get<IListPage<TableDataType>>({
            messageApi,
            url: `/api/agent/order/agreement/listpage/order-id/${pathParams.orderId}`,
            onBefore() {
                setIsLoading(true)
            },
            onSuccess({data}) {
                setDataArray([
                    ...data.rows
                ])
                setPage(data.page);
                setTotal(data.total);
            },
            onFinally() {
                setIsLoading(false)
            }
        })
    }

    useEffect(() => {
        getData();
    }, [page])

    return (
        <>
            <Breadcrumb
                items={[
                    {title: <Link to="/?type=agent">首页</Link>},
                    {title: '协议清单'},
                ]}
            />
            <div className="agreement-container" style={{height: `${domHeight}px`}}>
                <Spin tip="加载中..." spinning={isLoading}>
                    <Table columns={columns} dataSource={dataArray} rowKey="orderId" scroll={{y: domHeight - 105}} bordered pagination={{
                        current: page,
                        pageSize: 20,
                        total: total,
                        onChange: (page) => {
                            setPage(page);
                        }
                    }}/>
                </Spin>
            </div>
            <Spin tip="正在提交..." spinning={isConfirmLoading} fullscreen/>
            {contextHolder}
            {modalHolder}
        </>
    )
}