import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { Button, Col, FormInstance, message, Modal, Row } from "antd";
import ProTable, { ActionType } from "@ant-design/pro-table";
import { useRef, useState } from "react";
import { handleDeletePUSHMODULE, handleGetPUSHMODULEList, handleSynchroPUSHMODULE } from "../service";
import moment from 'moment'
import ProForm, { ProFormSelect, ProFormText, ProFormTextArea } from "@ant-design/pro-form";
import ModalFooter from "../../scenicSpotConfig/component/modalFooter";

type DetailProps = {
    onShow: boolean  // 显示的判断
    setOnShow: any   // 控制是否显示
    parentRow: any   // 父级传入的行数据
    currentUser: any // 公参信息
    handleUpdateLeftData?: any // 更新一下外部的左侧树的数据
}
const PushTemplateModal = ({ onShow, setOnShow, parentRow, currentUser, handleUpdateLeftData }: DetailProps) => {
    const actionRef = useRef<ActionType>();
    const ModalFormRef = useRef<FormInstance>();
    const formRef = useRef<FormInstance>();
    // 显示同步抽屉
    const [updateModal, setUpdateModal] = useState<boolean>(false)
    // 当前行数据
    const [currentRow, setCurrentRow] = useState<any>()
    // 悬浮框的loading效果
    const [modalLoading, setModalLoading] = useState<boolean>(false)

    const columns: any = [
        {
            dataIndex: 'PUSHMODULE_NUM',
            title: '模板序号',
            width: 150,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'PUSHMODULE_NAME',
            title: '模板名称',
            width: 150,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.PUSHMODULE_NAME ? <a onClick={() => {
                    setCurrentRow(record)
                    setUpdateModal(true)
                }}>{record?.PUSHMODULE_NAME}</a> : ""
            }
        },
        {
            dataIndex: 'PUSHMODULE_CODE',
            title: '模板编码',
            width: 250,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'PUSHMODULE_INDEX',
            title: '模板索引',
            width: 100,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        // {
        //     dataIndex: 'PUSHMODULE_STATE',
        //     title: '模板状态',
        //     width: 100,
        //     align: 'center',
        //     ellipsis: true,
        //     hideInSearch: true,
        //     valueType: 'select',
        //     fieldProps: {
        //         options: [{ label: "有效", value: 1 }, { label: "无效", value: 0 }]
        //     }
        // },
        {
            dataIndex: 'STAFF_NAME',
            title: '操作员名称',
            width: 120,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'OPERATE_DATE',
            title: '操作时间',
            width: 180,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.OPERATE_DATE ? moment(record?.OPERATE_DATE).format('YYYY-MM-DD HH:mm:ss') : ""
            }
        },
        {
            dataIndex: 'PUSHMODULE_DESC',
            title: '备注',
            width: 250,
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
    ]

    // 同步推送模板信息
    const handleUpdatePushModal = async (res: any) => {
        let req: any = {}
        setModalLoading(true)
        if (currentRow?.PUSHMODULE_ID) {
            req = {
                WECHATPUBLICSIGN_ID: parentRow?.WECHATPUBLICSIGN_ID,
                ...currentRow,
                ...res,
                PUSHMODULE_STATE: 1,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
            }
        } else {
            req = {
                ...res,
                PUSHMODULE_STATE: 1,
                WECHATPUBLICSIGN_ID: parentRow?.WECHATPUBLICSIGN_ID,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                ADDTIME: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        }
        const data = await handleSynchroPUSHMODULE(req)
        setModalLoading(false)

        console.log('datadatadatadata', data);
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            setCurrentRow(null)
            setUpdateModal(false)
            actionRef.current?.reload()
            if (handleUpdateLeftData) {
                handleUpdateLeftData()
            }
        } else {
            message.error(data.Result_Desc)
        }
    }

    // 删除推送模板
    const handleDeletePushModal = async (id: any) => {
        const req: any = {
            PUSHMODULEId: id
        }
        const data = await handleDeletePUSHMODULE(req)
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            setCurrentRow(null)
            setUpdateModal(false)
            actionRef.current?.reload()
            if (handleUpdateLeftData) {
                handleUpdateLeftData()
            }
        } else {
            message.error(data.Result_Desc)
        }
    }

    return (
        <div>
            <Modal
                open={onShow}
                onCancel={() => {
                    setOnShow(false)
                }}
                width={1400}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                destroyOnClose
                title={"推送模板"}
                footer={false}
            >
                <ProTable
                    actionRef={actionRef}
                    formRef={formRef}
                    columns={columns}
                    bordered
                    expandable={{
                        expandRowByClick: true
                    }}
                    scroll={{ x: "100%", y: "500px" }}
                    search={false}
                    pagination={false}
                    options={false}
                    request={async () => {
                        const req: any = {
                            SearchParameter: {
                                WECHATPUBLICSIGN_ID: parentRow?.WECHATPUBLICSIGN_ID,
                                PUSHMODULE_STATE: 1
                            },
                            PageIndex: 1,
                            PageSize: 999999,
                            SortStr: "PUSHMODULE_INDEX,ADDTIME desc",
                            requestEncryption: true
                        }
                        const data = await handleGetPUSHMODULEList(req)
                        console.log('datadatadatadatadatadata222', data);
                        if (data && data.length > 0) {
                            return { data, success: true }
                        }
                        return { data: [], success: true }
                    }}
                    toolbar={{
                        actions: [
                            <Button type={'primary'} onClick={() => {
                                setUpdateModal(true)
                            }}>添加模板</Button>
                        ]
                    }}
                />
            </Modal>


            <Modal
                open={updateModal}
                onCancel={() => {
                    setCurrentRow(null)
                    setUpdateModal(false)
                }}
                width={1400}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                destroyOnClose
                title={currentRow?.PUSHMODULE_NAME || "新增模板"}
                onOk={() => {
                    ModalFormRef?.current?.validateFields().then(async (res) => {
                        handleUpdatePushModal(res)
                    })
                }}
                footer={<ModalFooter
                    confirmLoading={modalLoading}
                    hideDelete={!currentRow?.PUSHMODULE_ID}
                    handleDelete={async () => {
                        await handleDeletePushModal(currentRow?.PUSHMODULE_ID)
                    }}
                    handleCancel={() => {
                        setCurrentRow(null)
                        setUpdateModal(false)
                    }}
                    handleOK={() => {
                        ModalFormRef?.current?.validateFields().then(async (res) => {
                            handleUpdatePushModal(res)
                        })
                    }}

                />}
            >
                <ProForm
                    formRef={ModalFormRef}
                    layout={'horizontal'}
                    submitter={false}
                    labelCol={{ style: { width: 80 } }}
                    initialValues={{
                        ...currentRow
                    }}
                >
                    <Row gutter={8}>
                        <Col span={8}>
                            <ProFormText
                                label={"模板名称"}
                                name={"PUSHMODULE_NAME"}
                            />
                        </Col>
                        <Col span={16}>
                            <ProFormText
                                label={"模板编码"}
                                name={"PUSHMODULE_CODE"}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                label={"模板编号"}
                                name={"PUSHMODULE_NUM"}
                            />
                        </Col>
                        <Col span={8}>
                            <ProFormText
                                label={"模板索引"}
                                name={"PUSHMODULE_INDEX"}
                            />
                        </Col>
                        {/* <Col span={8}>
                            <ProFormSelect
                                label={"模板状态"}
                                name={"PUSHMODULE_STATE"}
                                options={[{ label: "有效", value: 1 }, { label: "无效", value: 0 }]}
                                initialValue={1}
                            />
                        </Col> */}
                        <Col span={24}>
                            <ProFormTextArea
                                label={"备注"}
                                name={"PUSHMODULE_DESC"}
                                fieldProps={{
                                    rows: 8,
                                }}
                            />
                        </Col>
                    </Row>
                </ProForm>

            </Modal>
        </div>
    )
}

export default connect(({ user, }: ConnectState) => ({
    currentUser: user.currentUser,
}))(PushTemplateModal);
