import { BetaSchemaForm, PageContainer, ProFormInstance, useToken } from "@ant-design/pro-components"
import { useAjax } from "@/Hook/useAjax"
import { useModel } from "@umijs/max"
import React, { JSXElementConstructor, Key, ReactElement, ReactNode, ReactPortal, useEffect, useMemo, useRef, useState } from "react"
import { appVipRechargeTemplateInfo, appVipRechargeTemplateList, appVipRechargeTemplateRemove, appVipRechargeTemplateSave, appVipRechargeTemplateSwitch, appVipRechargeTemplateUpdate } from "@/services/miniApp/moduleConfig"
import { Button, Card, Col, Empty, message, Modal, Row, Space } from "antd"
import { DeleteOutlined, EditOutlined, ExclamationCircleFilled, PlusOutlined } from "@ant-design/icons"
import formConfig from "./formConfig"
import { Template } from "./template"
import { createStyles } from "antd-style";
const useStyles = createStyles(({ token }) => {
    return {
        active: {
            position: 'relative',
            "&::after": {
                content: '""', // 修正了这里的拼写错误
                display: "block",
                opacity: 1,
                border: '15px solid #1890ff',
                borderBlockEnd: '15px solid transparent',
                borderInlineStart: '15px solid transparent', // 修正了多余的分号
                borderStartEndRadius: '6px',
                position: 'absolute',
                top: 0,
                right: 0
            }
        }
    }
})
type DataItem = {
    name: string;
    state: string;
};
const VipPage: React.FC = () => {
    let { token } = useToken()
    let { initialState } = useModel("@@initialState")
    let [open, setOpen] = useState<any>(null)
    let [editValues, setEditValues] = useState<any>({})
    let [activeT, setActiveT] = useState<any>()
    let { styles } = useStyles()
    let getList = useAjax((params) => appVipRechargeTemplateList(params))//获取模板列表
    let add = useAjax((params) => appVipRechargeTemplateSave(params))//新增模板
    let switchT = useAjax((params) => appVipRechargeTemplateSwitch(params))//切换模板
    let editT = useAjax((params) => appVipRechargeTemplateUpdate(params))//编辑模板
    let delT = useAjax((params) => appVipRechargeTemplateRemove(params))//删除模板
    let infoT = useAjax((id) => appVipRechargeTemplateInfo(id))//模板详情
    const formRef = useRef<ProFormInstance>();
    let publicData = useMemo(() => {
        return {
            appId: initialState?.selectApp?.id || "",
            appType: initialState?.selectApp?.appType || ""
        }
    }, [initialState?.selectApp, initialState?.currentUser?.distributorId])
    // 获取表单数据
    useEffect(() => {
        getList.run(publicData).then(res => {
            if (res.data) {
                let activeObj = res?.data?.find((item: { activateTemplate: any }) => item.activateTemplate)
                activeObj && setActiveT(activeObj.id)
            }
        })
    }, [publicData])
    // 提交表单
    const submit = async (values: any) => {
        let api = editValues?.id ? editT : add
        if (!values.activateTemplate) {
            values.activateTemplate = false
        }
        if (editValues?.id) {
            values.id = editValues?.id
        }
        values.rechargeConfigs = []
        if (values.rechargeConfigList?.length > 0) {//首充
            values.rechargeConfigs.push({
                firstRecharge: true,//是否首充档位;true：首充 false：非首充
                rechargeConfigList: values.rechargeConfigList,
            })
        }
        if (values.rechargeConfigList1?.length > 0) {//非首充
            values.rechargeConfigs.push(
                {
                    firstRecharge: false,//是否首充档位;true：首充 false：非首充
                    rechargeConfigList: values.rechargeConfigList1,
                }
            )
        }
        delete values.rechargeConfigList
        delete values.rechargeConfigList1
        api.run({ ...values, ...publicData }).then(res => {
            if (res.code === 200) {
                getList.refresh()
                message.success(values.id ? "编辑模板成功" : "新建模板成功!")
                closeForm(false)
            }
        })
    }
    // 关闭表单弹窗和重置表单内容
    const closeForm = (b: boolean, values?: any) => {
        if (!b) {
            setEditValues({})
            formRef?.current?.resetFields?.()
            setOpen(b)
        } else {
            setOpen(b)
            if (values) {
                infoT.run(values.id).then(res => {
                    if (res.code === 200) {
                        let data = res.data
                        for (let item of data.rechargeConfigs) {
                            if (item.firstRecharge) {
                                data.rechargeConfigList = item.rechargeConfigList
                            } else {
                                data.rechargeConfigList1 = item.rechargeConfigList
                            }
                        }
                        setEditValues(data)
                        formRef?.current?.setFieldsValue(data)
                    }
                })
            }
        }
    }
    // 模板切换
    const switchTemplate = (id: any) => {
        let params = { ...publicData, id }
        Modal.confirm({
            title: '切换充值模板',
            content: '是否要切换为当前充值模板？',
            icon: <ExclamationCircleFilled />,
            okText: "切换",
            onOk: () => {
                switchT.run(params).then(res => {
                    if (res.code === 200) {
                        setActiveT(id)
                        getList.refresh()
                        message.success("切换成功")
                    }
                })
            }
        });
    }
    // 模板删除
    const delTemplate = (id: any) => {
        Modal.confirm({
            title: '删除充值模板',
            content: '是否要删除当前充值模板？',
            icon: <ExclamationCircleFilled />,
            okType: 'danger',
            okText: "删除",
            onOk: () => {
                delT.run(id).then(res => {
                    if (res.code === 200) {
                        getList.refresh()
                        message.success("删除成功")
                    }
                })
            }
        });
    }
    return <PageContainer
        title={false}
        extra={getList?.data?.data?.length > 0 && <Button type="primary" onClick={() => { closeForm(true) }}><PlusOutlined />新增模板</Button>}
    >
        {/* 模板列表 */}
        <Row gutter={[20, 20]}>
            {
                getList?.data?.data?.map((item: { id: Key | null | undefined; templateName: string | number | boolean | ReactElement<any, string | JSXElementConstructor<any>> | Iterable<ReactNode> | ReactPortal | null | undefined; rechargeConfigs: any[]; templateType: number; templateDescription: string | number | boolean | ReactElement<any, string | JSXElementConstructor<any>> | Iterable<ReactNode> | ReactPortal | null | undefined }) => {
                    return <Col key={item.id} style={{ cursor: 'pointer' }} onClick={() => { switchTemplate(item.id) }} xs={{span:24}} sm={{span:8}}>
                        <Card className={activeT === item.id ? styles.active : ""} style={{ background: activeT === item.id ? token.colorPrimaryBgHover : token.colorFillAlter }} hoverable>
                            <h3 style={{ fontSize: 16, fontWeight: 500, color: token.colorText, fontFamily: 'PingFang SC' }}>{item.templateName}</h3>
                            {
                                item.rechargeConfigs?.map((config, index) => {
                                    return <React.Fragment key={index}>
                                        <Template data={config} />
                                    </React.Fragment>
                                })
                            }
                            <p style={{ marginTop: 20, color: token.colorTextSecondary, fontSize: 12 }}>{item.templateDescription}</p>
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'end' }}>
                                <Space>
                                    <Button size='small' type='primary' onClick={(e) => { e.stopPropagation(); closeForm(true, item) }}><EditOutlined /></Button>
                                    <Button size='small' type="primary" danger onClick={(e) => { e.stopPropagation(); delTemplate(item.id) }}><DeleteOutlined /></Button>
                                </Space>
                            </div>
                        </Card>
                    </Col>
                })
            }
            {
                getList?.data?.data?.length === 0 && <div style={{ width: "100%", height: "100%", marginTop: "10%" }}><Empty description={<Space direction='vertical'><div>暂无模板数据</div><Button type="primary" onClick={() => { closeForm(true) }}><PlusOutlined />新增模板</Button></Space>} /></div>
            }
        </Row>
        {/* 模板弹窗 */}
        <BetaSchemaForm<DataItem>
            title={editValues?.id ? "编辑模板" : '新建模板'}
            formRef={formRef}
            open={open}
            onOpenChange={(b) => { !b && closeForm(b) }}
            layoutType={"ModalForm"}
            rowProps={{
                gutter: [16, 16],
            }}
            colProps={{
                span: 12,
            }}
            width={1000}
            grid={true}
            onFinish={submit}
            columns={formConfig()}
            loading={add?.loading}
        />
    </PageContainer>

}
export default VipPage