// 埋点配置 行为埋点配置
import React, { useRef, useState, Suspense } from 'react';
import moment from 'moment'; // 时间相关引用，没有使用可以删除
import numeral from "numeral"; // 数字相关引用，没有使用可以删除
import { connect } from 'umi';

import useRequest from '@ahooksjs/use-request'; // 请求数据的引用
import Draggable from 'react-draggable';
import SubMenu from "antd/lib/menu/SubMenu";
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import ProForm, { ProFormDatePicker, ProFormDateTimePicker, ProFormMoney, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from '@ant-design/pro-form';
import { MenuFoldOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Col, Drawer, message, Row, Popconfirm, Space, Image, Modal, Form, Switch, Upload, Tooltip, Descriptions, TreeSelect } from 'antd';

import type { CurrentUser } from "umi";
import type { ConnectState } from '@/models/connect';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { FormInstance } from 'antd';

import { getFieldEnumTree, getFieldEnumName } from "@/services/options"; // 枚举的引用，没有使用可以删除
import PageTitleBox from "@/components/PageTitleBox";
import { handeDeleteWECHATAPPBURYPOINT, handeGetWECHATAPPBURYPOINTList, handeGetWECHATAPPSIGNList, handeSynchroWECHATAPPBURYPOINT } from '../service';
import ModalFooter from '../scenicSpotConfig/component/modalFooter';
import { highlightText } from '@/utils/highlightText';


const BuriedPointConfig: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [currentRow, setCurrentRow] = useState<any>();
    const [showDetail, setShowDetail] = useState<boolean>();
    const [modalVisible, handleModalVisible] = useState<boolean>();
    const [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
    const [searchParams, setSearchParams] = useState<any>();

    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<any>()
    // 获取小程序的列表
    const [WECHATAPP_APPID, setWECHATAPP_APPID] = useState<any>()

    const onDraggaleStart = (event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };

    // 当前查询的文字
    const [currentSearchText, setCurrentSearchText] = useState<string>('')


    // 定义列表字段内容
    const columns: any = [
        {
            dataIndex: 'searchText',
            title: '查询内容',
            hideInTable: true,
            fieldprop: {
                placeholder: "请输入页面路径/模块名称"
            }
        },
        {
            dataIndex: 'WECHATAPP_APPID',
            title: '小程序类别',
            hideInTable: true,
            valueType: 'select',
            request: async () => {
                const req: any = {
                    SearchParameter: {
                        OWNERUNIT_ID: currentUser?.OwnerUnitId,
                        // PROVINCE_CODE: currentUser?.ProvinceCode
                    },
                    PageIndex: 1,
                    PageSize: 99,
                }
                const data = await handeGetWECHATAPPSIGNList(req)
                console.log('datadsda', data);
                let list: any = []
                if (data && data.length > 0) {
                    data.forEach((item: any) => {
                        list.push({ label: item.WECHATAPPSIGN_NAME, value: item.WECHATAPP_APPID })
                    })
                }
                setWECHATAPP_APPID(list)
                return list
            },
            initialValue: "wxee018fb96955552a"
        },
        {
            dataIndex: 'WECHATAPP_ROUTE',
            width: 300,
            title: <div style={{ textAlign: 'center' }}>小程序页面路径</div>,
            align: 'left',
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.WECHATAPP_ROUTE ? <a onClick={() => {
                    setCurrentRow({ ...record });
                    handleModalVisible(true);
                }}>
                    {/* {record?.WECHATAPP_ROUTE} */}
                    {highlightText(record?.WECHATAPP_ROUTE, currentSearchText)}
                </a> : "-"
            }
        },
        {
            dataIndex: 'WECHATAPP_MOULD',
            title: '小程序模板',
            width: 150,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return highlightText(record?.WECHATAPP_MOULD, currentSearchText)
            }
        },
        // {
        //     dataIndex: 'WECHATAPP_APPID',
        //     title: '小程序APPID',
        //     align: 'center',
        //     width: 150,
        //     ellipsis: true,
        //     hideInSearch: true,
        // },
        {
            dataIndex: 'WECHATAPPSIGN_NAME',
            title: '小程序名称',
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
        },
        // {
        //     dataIndex: 'ISSHOW',
        //     // title: '小程序埋点是显示',
        //     title: '有效状态',
        //     align: 'center',
        //     width: 150,
        //     ellipsis: true,
        //     hideInSearch: true,
        //     valueType: "select",
        //     valueEnum: {
        //         "1": "有效",
        //         "0": "无效"
        //     }
        // },
        {
            dataIndex: 'UPDATE_STAFF_NAME',
            title: '修改人员名称',
            width: 150,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'UPDATE_DATE',
            title: '修改时间',
            valueType: 'date',
            width: 150,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return record?.UPDATE_DATE ? moment(record?.UPDATE_DATE).format('YYYY-MM-DD HH:mm:ss') : "-"
            }
        },
        // {
        //     dataIndex: 'option',
        //     title: '操作',
        //     valueType: 'option',
        //     hideInSearch: true,
        //     render: (_, record) => {
        //         return (
        //             <Space>
        //                 <a
        //                     onClick={() => {
        //                         setCurrentRow(record);
        //                         setShowDetail(true);
        //                     }}
        //                 >
        //                     查看
        //                 </a>
        //                 <a
        //                     onClick={() => {
        //                         setCurrentRow({ ...record });
        //                         handleModalVisible(true);
        //                     }}
        //                 >
        //                     编辑
        //                 </a>
        //                 <Popconfirm
        //                     title="确认删除该小程序埋点配置列表信息吗?"
        //                     onConfirm={async () => {
        //                         await handelDelete(record.WECHATAPPBURYPOINT_ID);
        //                     }}
        //                 >

        //                     <a>删除</a>
        //                 </Popconfirm>
        //             </Space >
        //         );
        //     },
        // },
    ];

    const handelDelete = async (id: number) => {
        const result = await handeDeleteWECHATAPPBURYPOINT({ WECHATAPPBURYPOINTId: id });

        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:删除失败`);
        } else {
            message.success('删除成功！');
            actionRef.current?.reload()
            formRef.current?.resetFields();
            setCurrentRow(undefined);
            handleConfirmLoading(false)
            handleModalVisible(false)
        }
    };

    const handleAddUpdate = async (res: any) => {

        let req: any = {}
        if (currentRow?.WECHATAPPBURYPOINT_ID) {
            req = {
                ...currentRow,
                ...res,
                UPDATE_STAFF_ID: currentUser?.ID,
                UPDATE_STAFF_NAME: currentUser?.Name,
                UPDATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                ISSHOW: 1
            }
        } else {
            req = {
                ...res,
                CREATE_STAFF_ID: currentUser?.ID,
                CREATE_STAFF_NAME: currentUser?.Name,
                CREATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                UPDATE_STAFF_ID: currentUser?.ID,
                UPDATE_STAFF_NAME: currentUser?.Name,
                UPDATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                ISSHOW: 1
            }
        }
        console.log('reqreq', req);

        const data = await handeSynchroWECHATAPPBURYPOINT(req)
        handleConfirmLoading(false)
        if (data.Result_Code === 100) {
            message.success("新增成功！")
            setCurrentRow(undefined)
            formRef?.current?.resetFields()
            handleModalVisible(false)
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    };

    return (
        <div>
            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <ProTable
                    style={{ height: 'calc(100vh - 135px)', background: '#fff' }}
                    scroll={{ y: 'calc(100vh - 430px)' }}
                    rowKey={(record) => {
                        return `${record?.WECHATAPPBURYPOINT_ID}`
                    }}
                    formRef={formRef}
                    headerTitle={<PageTitleBox props={props} />} // 列表表头
                    actionRef={actionRef}
                    search={{ span: 6, labelWidth: 'auto' }}
                    bordered
                    // 请求数据
                    request={async (params, sorter) => {
                        const req = {
                            SearchParameter: {
                                // WECHATAPP_APPID: "wxee018fb96955552a"
                                WECHATAPP_APPID: params?.WECHATAPP_APPID || "",
                                ISSHOW: 1,
                                WECHATAPPBURYPOINT_STATE: 1
                            },
                            PageIndex: 1,
                            PageSize: 999,
                            keyWord: {
                                Key: "WECHATAPP_ROUTE,WECHATAPP_MOULD",
                                value: params?.searchText || ""
                            },
                            SortStr: "UPDATE_DATE desc",
                        }
                        console.log('reqreqreqreqreq', req);

                        const data = await handeGetWECHATAPPBURYPOINTList(req);
                        setCurrentSearchText(params?.searchText || "")
                        console.log('datadatadatadatadata', data);
                        if (data.List && data.List.length > 0) {
                            return { data: data.List, success: true, total: data.TotalCount }
                        }
                        return { data: [], success: true }
                    }}
                    columns={columns}
                    toolbar={{
                        actions: [
                            // 新增按钮
                            <Button
                                key="new"
                                icon={<PlusOutlined />}
                                type="primary"
                                onClick={() => {
                                    handleModalVisible(true);
                                }}
                            >
                                小程序埋点配置
                            </Button>,
                        ],
                    }}
                    pagination={{ defaultPageSize: 20 }}
                />
                <Drawer
                    width={600}
                    visible={showDetail}
                    onClose={() => {
                        setCurrentRow(undefined);
                        setShowDetail(false);
                    }}
                    closable={false}
                >
                    {currentRow?.WECHATAPPBURYPOINT_ID && (
                        <ProDescriptions
                            column={2}
                            request={async () => ({
                                data: currentRow || {},
                            })}
                            params={{
                                id: currentRow?.WECHATAPPBURYPOINT_ID,
                            }}
                            columns={columns}
                        />
                    )}
                </Drawer>
                <Modal
                    title={
                        <div
                            className='buriedPointConfig'
                            style={{
                                width: '100%',
                                cursor: 'move',
                            }}
                            onMouseOver={() => {
                                if (disabled) {
                                    setDraggleDisabled(false)
                                }
                            }}
                            onMouseOut={() => {
                                setDraggleDisabled(true)
                            }}

                            onFocus={() => { }}
                            onBlur={() => { }}
                        >
                            {currentRow ? '更新小程序埋点配置' : '新建小程序埋点配置'}
                        </div>
                    }
                    destroyOnClose={true}
                    width={900}
                    bodyStyle={{
                        height: '700px', // 你可以根据需要调整高度
                        overflowY: 'auto',
                    }}
                    visible={modalVisible}
                    confirmLoading={confirmLoading}
                    afterClose={() => {
                        formRef.current?.resetFields();
                        setCurrentRow(undefined);
                    }}
                    onCancel={() => {
                        handleConfirmLoading(false)
                        handleModalVisible(false)
                    }}
                    footer={<ModalFooter
                        hideDelete={!currentRow?.WECHATAPPBURYPOINT_ID}
                        handleDelete={async () => {
                            await handelDelete(currentRow?.WECHATAPPBURYPOINT_ID)
                        }}
                        handleCancel={() => {
                            handleConfirmLoading(false)
                            handleModalVisible(false)
                            formRef.current?.resetFields();
                            setCurrentRow(undefined);
                        }}
                        handleOK={() => {
                            formRef?.current?.validateFields().then(() => {
                                handleConfirmLoading(true)
                                formRef?.current?.submit()
                            })
                        }}

                    />}

                    onOk={async () => { // 提交框内的数据
                        formRef?.current?.validateFields().then(() => {
                            handleConfirmLoading(true)
                            formRef?.current?.submit()
                        })
                    }}
                    modalRender={(modal) => {
                        return <Draggable
                            disabled={disabled}
                            bounds={bounds}
                            onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                            handle='.buriedPointConfig'
                        >
                            <div ref={draggleRef}>{modal}</div>
                        </Draggable>
                    }}
                >
                    <ProForm
                        layout={'horizontal'}
                        labelCol={{ style: { width: 80 } }}
                        formRef={formRef}
                        autoFocusFirstInput
                        submitter={false}
                        preserve={false}
                        initialValues={currentRow}
                        onFinish={async (values) => {
                            let newValue: any = { ...values };
                            if (currentRow) {
                                // 编辑数据
                                newValue = { ...values, WECHATAPPBURYPOINT_ID: currentRow.WECHATAPPBURYPOINT_ID };
                            }
                            // 如果有开关，要把开关的代码写进去
                            const success = await handleAddUpdate(newValue);

                            handleConfirmLoading(false)
                            if (success) {
                                if (actionRef.current) {
                                    actionRef.current.reload();
                                }
                                handleModalVisible(false);
                            }
                        }}
                    >
                        <Row>
                            <Col span={12}>
                                <ProFormText
                                    name="WECHATAPP_ROUTE"
                                    label="页面路径"
                                />
                            </Col>
                            <Col span={12}>
                                <ProFormText
                                    name="WECHATAPP_MOULD"
                                    label="模块名称"
                                />
                            </Col>
                            <Col span={12}>
                                <ProFormSelect
                                    name="WECHATAPP_APPID"
                                    label="小程序名称"
                                    options={WECHATAPP_APPID}
                                    fieldProps={{
                                        onChange: (e, option) => {
                                            formRef.current?.setFieldsValue({ WECHATAPPSIGN_NAME: option?.label || "" })
                                        }
                                    }}
                                />
                            </Col>
                            <Col span={12} style={{ display: 'none' }}>
                                <ProFormText
                                    name="WECHATAPPSIGN_NAME"
                                    label="小程序名称"
                                />
                            </Col>
                            {/* <Col span={12}>
                                <ProFormSelect
                                    name="ISSHOW"
                                    label="有效状态"
                                    options={[{ label: "有效", value: 1 }, { label: "无效", value: 0 }]}
                                />
                            </Col> */}
                        </Row>
                    </ProForm>
                </Modal>
            </div>
        </div>
    );
};
export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(BuriedPointConfig);
