import './proj-new.css';
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { Button, Flex, Form, Input, message, Modal, Spin, Checkbox } from "antd";
import { useContext, useEffect, useState } from "react";
import { get, post } from "../../util/AjaxUtils.ts";
import { IProjCharge, ProjAdditionalType, ProjChargeType } from "../../interfaces/proj/IProj.ts";
import { GlobalDispatchContext, reloadUser } from "../../context/GlobalContext.ts";
// const { TextArea } = Input;
type ProjInfo = {
    projName: string;
    projIntroduction: string;
};

export default function ProjNew() {
    const globalDispatchContext = useContext(GlobalDispatchContext);
    const nav = useNavigate();
    const pathParams = useParams();
    const [queryParams] = useSearchParams();

    const [messageApi, contextHolder] = message.useMessage();
    const [loading, setLoading] = useState<boolean>(false);
    const height = window.innerHeight - 180;
    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [chargePrice, setChargePrice] = useState(0);
    const [projInfo, setProjInfo] = useState<ProjInfo>({
        projName: '',
        projIntroduction: '',
    });
    const [createProjId, setCreateProjId] = useState('');
    const oldlistProjChargeAdditional: string[] = [];
    const [listProjChargeAdditional, setlistProjChargeAdditional] = useState<string[]>([])

    useEffect(() => {
        get({
            messageApi: messageApi,
            url: '/api/proj/charge/get',
            onSuccess({ data }) {

                const charge = data as IProjCharge;
                // console.log('创建页price',charge.proj.materialAgent);

                let price = 0;
                switch (pathParams.projChargeType) {
                    case ProjChargeType.ALL:
                        price = charge.proj.all;
                        break;
                    case ProjChargeType.MATERIAL_AGENT:
                        price = charge.proj.materialAgent;
                        break;
                    case ProjChargeType.MATERIAL_AGENT_URGENT:
                        price = charge.proj.materialAgentUrgent;
                        break;
                    case ProjChargeType.MATERIAL:
                        price = charge.proj.material;
                        break;
                    case ProjChargeType.FREE:
                        price = charge.proj.free;
                        break;
                    default:
                        messageApi.error({
                            type: 'error',
                            content: '价格类型错误',
                        })
                }
                const pkg = queryParams.get('pkg') == 'true' ? true : false
                const videoDemo = queryParams.get('videoDemo') == 'true' ? true : false
                if (pkg) {
                    price += charge.additional.pkg;
                    oldlistProjChargeAdditional.push(ProjAdditionalType.PKG);
                    console.log(listProjChargeAdditional);

                }
                if (videoDemo) {
                    price += charge.additional.videoDemo;
                    oldlistProjChargeAdditional.push(ProjAdditionalType.VIDEO_DEMO);
                    console.log(listProjChargeAdditional);

                }
                setChargePrice(price);
                setlistProjChargeAdditional(oldlistProjChargeAdditional)
                // console.log('传递信息pkg:',pkg,'videoDemo:',videoDemo);

                // console.log('显示价格',price);

            }
        })
    }, []);

    return (
        <>
            {contextHolder}
            {/* <Breadcrumb
                items={[
                    {title: <Link to={'/'}>首页</Link>},
                    {title: <Link to={'/proj-create'}>创建项目</Link>},
                    {title: '新建项目'},
                ]}
            /> */}
            <div className='projNew' style={{ height: `${height}px`, overflow: 'auto' }}>
                <div className="proj-new">
                    {/* <div className="proj-title">请完善项目的基本信息</div> */}
                    <div className="proj-form">
                        <Form
                            name="basic"
                            layout={'vertical'}
                            labelCol={{ span: 24 }}
                            wrapperCol={{ span: 24 }}
                            style={{ width: '100%' }}
                            onFinish={(formData) => {
                                setIsCreateModalOpen(true);
                                setProjInfo({
                                    projName: formData.projName,
                                    projIntroduction: formData.projIntroduction
                                })
                            }}
                            autoComplete="off"
                        >
                            <div className='formItemOne'>
                                <div className='formItem-title oneTitle'>系统全称*</div>
                                <Form.Item<ProjInfo>
                                    name="projName"
                                    rules={[{ required: true, message: '请输入系统全称' }]}
                                >
                                    <Input style={{ background: '#eeeeee', width: '1000px', height: '50px', fontSize: '16px' }} placeholder="请输入系统全称" />
                                </Form.Item>
                            </div>
                            <div className='software-protocol'>
                                <Form.Item
                                    name="agreement"
                                    valuePropName="checked"
                                    rules={[
                                        {
                                            validator: (_, value) =>
                                                value ? Promise.resolve() : Promise.reject(new Error('请阅读并勾选《软件委托开发协议》')),
                                        },
                                    ]}
                                >
                                    <Checkbox>
                                        我同意平台 <a onClick={()=>{
                                            window.open('https://www.aimzhu.com/Seda.html')
                                        }}>《软件委托开发协议》</a>
                                    </Checkbox>
                                </Form.Item>
                            </div>
                            {/* <div className='formItemTwo'>
                                <div className='formItem-title '>简单描述</div>
                                <Form.Item<ProjInfo>
                                    name="projIntroduction"
                                >
                                        <TextArea rows={10} style={{ background: '#eeeeee', resize: 'none',width:"328px",height:'220px',fontSize:'16px' }} placeholder="请对系统作出简单的描述，以使可准确生成资料..." />
                                </Form.Item>
                            </div> */}
                            <div style={{ marginTop: '' }}>
                                <Form.Item>
                                    <Flex align="center" justify="center" gap="large">
                                        <Button
                                            // style={{
                                            //     backgroundColor: '#F5F5F5', width: '216px',
                                            //     height: '50px', color: '#AFAFAF', fontSize: '16px'
                                            // }} 
                                            size='large'
                                            type="default" htmlType="button" onClick={() => {
                                                nav(-1);
                                            }}
                                        >
                                            返回
                                        </Button>
                                        <Button type="primary" htmlType="submit"
                                            size='large'
                                        // style={{
                                        //     backgroundColor: 'var(--color-primary)', width: '216px',
                                        //     height: '50px', fontSize: '16px', marginLeft: '53px'
                                        // }}
                                        >
                                            保存并付款
                                        </Button>

                                    </Flex>
                                </Form.Item>
                            </div>
                        </Form>
                    </div>
                </div>
            </div>
            <Modal title="提示"
                okText="确定"
                cancelText="取消"
                open={isCreateModalOpen}
                onOk={() => {
                    // console.log('最终',listProjChargeAdditional);

                    setIsCreateModalOpen(false);
                    post<any>({
                        messageApi,
                        url: '/api/proj/create',
                        body: {
                            projName: projInfo.projName,
                            projChargeType: pathParams.projChargeType,
                            listProjChargeAdditional: listProjChargeAdditional
                        },
                        onBefore() {
                            setLoading(true);
                        },
                        onSuccess({ data }) {
                            setIsEditModalOpen(true);
                            setCreateProjId(data.data);
                            reloadUser(messageApi, globalDispatchContext).then(() => {
                                messageApi.success('扣款成功');
                            });
                        },
                        onFinally() {
                            setLoading(false);
                        }
                    })
                }}
                onCancel={() => {
                    setIsCreateModalOpen(false);
                }}>
                <div>该操作会扣除 {chargePrice / 100} 元，确定操作码？</div>
            </Modal>
            <Modal title="提示"
                okText="确定"
                cancelText="取消"
                open={isEditModalOpen}
                onOk={() => {
                    if (pathParams.projChargeType == ProjChargeType.ALL) {
                        nav(`/proj-eall/${createProjId}`);
                    } else if (pathParams.projChargeType == ProjChargeType.FREE) {
                        nav(`/proj-efree/${createProjId}`);
                    } else {
                        nav(`/proj-edit/${createProjId}`);
                    }
                }}
                onCancel={() => {
                    setIsEditModalOpen(false);
                }}>
                <div>项目创建成功，开始编辑项目？</div>
            </Modal>
            <Spin tip="正在提交..." spinning={loading} fullscreen />
        </>
    )
}