// 成长值枚举规则配置页面
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, ProFormDateTimeRangePicker, ProFormDigit, ProFormMoney, ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect, 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 { uploadPicture } from '@/services/picture';
import defaultIcon from '../../../assets/brand/defaultIcon.png'
import classNames from 'classnames';
import session from '@/utils/session';
import ModalFooter from '../../scenicSpotConfig/component/modalFooter';
import { handeDeleteFIELDENUM, handeGetFIELDEXPLAINList, handeGetNestingFIELDENUMList, handeSynchroFIELDENUM } from '../../service';


const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('请上传JPEG、jpg、png格式的图片文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('图片大小不超过 2MB!');
    }
    return isJpgOrPng && isLt2M;
}


const GrowthConfig: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const { confirm } = Modal;
    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 [typeTreeData, setTypeTreeData] = useState<any>()
    // 表单里面的是否预售
    const [formPRESALE_TYPE, setFormPRESALE_TYPE] = useState<boolean>(false)

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

    let AFTERSALETYPEObj = session.get('AFTERSALETYPEObj')
    const { data: FIELDEXPLAIN_ID } = useRequest(async () => {
        const req: any = {
            SearchParameter: {
                FIELDEXPLAIN_FIELD: "GROWTH_TYPE"
            }
        }
        const data = await handeGetFIELDEXPLAINList(req)
        if (data && data.length > 0) {
            let obj: any = data[0]
            return obj.FIELDEXPLAIN_ID
        }

    })
    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片

    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 columns: any = [
        {
            dataIndex: 'FIELDENUM_NAME',
            title: '类别名称',
            align: 'center',
            width: 300,
            ellipsis: true,
            hideInSearch: true,
            hideInDescriptions: true,
            render: (_, record) => {
                return <a
                    onClick={() => {
                        setCurrentRow({ ...record });
                        handleModalVisible(true);
                    }}
                >{record?.FIELDENUM_NAME || ""}</a>
            }
        },
        {
            dataIndex: 'FIELDENUM_VALUE',
            title: '售后枚举',
            align: 'center',
            width: 120,
            ellipsis: true,
            // valueType: 'treeSelect',
            // valueEnum: typeTreeData,
            hideInSearch: true,
        },
        {
            dataIndex: 'FIELDENUM_INDEX',
            title: '类别索引',
            align: 'center',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'FIELDENUM_STATUS',
            title: '有效状态',
            align: 'center',
            width: 120,
            ellipsis: true,
            valueType: "select",
            valueEnum: {
                "1": "有效",
                "0": "无效"
            },
            initialValue: "1"
        },
        {
            dataIndex: 'FIELDENUM_DESC',
            title: '备注说明',
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        // {
        //     dataIndex: 'option',
        //     title: '操作',
        //     width: 100,
        //     ellipsis: true,
        //     valueType: 'option',
        //     align: 'center',
        //     hideInSearch: true,
        //     render: (_, record) => {
        //         return (
        //             <Space>
        //                 <a
        //                     onClick={() => {
        //                         setCurrentRow({ ...record });
        //                         handleModalVisible(true);
        //                     }}
        //                 >
        //                     编辑
        //                 </a>
        //                 <Popconfirm
        //                     title="确认删除该点餐自定义类别列表信息吗?"
        //                     onConfirm={async () => {
        //                         handelDelete(record.FIELDENUM_ID);
        //                     }}
        //                 >
        //                     <a>删除</a>
        //                 </Popconfirm>
        //             </Space>
        //         );
        //     },
        // },
    ];

    // 预览上传后的图片
    const handlePreview = async () => {
        setFileList(fileList)
        setImagePreviewVisible(true)
    };
    const handleChangePreview = (val: any) => {
        setImagePreviewVisible(val)
    }

    // 删除点餐类别
    const handelDelete = async (id: any) => {
        const req: any = {
            FIELDENUMId: id
        }
        const result = await handeDeleteFIELDENUM(req)
        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:删除失败`);
        } else {
            message.success('删除成功！');
            actionRef.current?.reload()
            handleConfirmLoading(false)
            handleModalVisible(false)
            setFormPRESALE_TYPE(false)
            setFileList([])
        }
    }

    // 同步点餐列表
    const handleAddUpdate = async (res: any) => {
        let req: any = {}
        if (currentRow?.FIELDENUM_ID) {
            req = {
                ...currentRow,
                ...res,
            }
        } else {
            req = {
                ...res,
                FIELDEXPLAIN_ID: FIELDEXPLAIN_ID,
                FIELDENUM_PID: -1,
            }
        }
        const data = await handeSynchroFIELDENUM(req)
        handleConfirmLoading(false)
        if (data.Result_Code === 100) {
            message.success("新增成功！")
            setCurrentRow(undefined)
            formRef?.current?.resetFields()
            handleModalVisible(false)
            setFormPRESALE_TYPE(false)
            setFileList([])
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    }

    return (
        <PageContainer header={{
            title: '',
            breadcrumb: {}
        }}>
            <ProTable
                style={{ height: 'calc(100vh - 135px)', background: '#fff' }}
                scroll={{ y: 'calc(100vh - 410px)' }}
                rowKey={(record) => {
                    return `${record?.FIELDENUM_PID}-${record?.FIELDENUM_ID}`
                }}
                formRef={formRef}
                headerTitle={<PageTitleBox props={props} />} // 列表表头
                actionRef={actionRef}
                search={{ span: 6, labelWidth: 'auto' }}
                bordered
                // 请求数据
                request={async (params, sorter) => {
                    const req = {
                        FIELDEXPLAIN_FIELD: 'GROWTH_TYPE',
                        FIELDEXPLAIN_ID: "",
                        FIELDENUM_PID: "",
                        FIELDENUM_STATUS: params?.FIELDENUM_STATUS,
                        SearchKey: ""
                    }
                    const data = await handeGetNestingFIELDENUMList(req);
                    if (data && data.length > 0) {
                        setTypeTreeData(data)
                        return { data: data, success: true, total: data.length }
                    }
                    return { data: [], success: true }
                }}
                columns={columns}
                toolbar={{
                    actions: [
                        // 新增按钮
                        <Button
                            key="new"
                            icon={<PlusOutlined />}
                            type="primary"
                            onClick={() => {
                                handleModalVisible(true);
                            }}
                        >
                            售后服务类别
                        </Button>,
                    ],
                }}
            />

            {/* 图片预览组件 */}
            {fileList && fileList.length > 0 && <div style={{ display: 'none' }}>
                <Image.PreviewGroup
                    preview={{
                        visible: imagePreviewVisible,
                        onVisibleChange: vis => {
                            handleChangePreview(vis)
                        }
                    }}>
                    {
                        fileList.map((n) => <Image src={n.url} key={n.url} />)
                    }
                </Image.PreviewGroup>
            </div>}


            <Modal
                title={
                    <div
                        className='orderCategoryModal'
                        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);
                }}
                footer={<ModalFooter
                    hideDelete={!currentRow?.FIELDENUM_ID}
                    handleDelete={async () => {
                        await handelDelete(currentRow?.FIELDENUM_ID)
                    }}
                    handleCancel={() => {
                        handleConfirmLoading(false)
                        handleModalVisible(false)
                        setFormPRESALE_TYPE(false)
                        setFileList([])
                    }}
                    handleOK={() => {
                        formRef?.current?.validateFields().then(() => {
                            handleConfirmLoading(true)
                            formRef?.current?.submit()
                        })
                    }}

                />}
                onCancel={() => {
                    handleConfirmLoading(false)
                    handleModalVisible(false)
                    setFormPRESALE_TYPE(false)
                    setFileList([])
                }}

                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='.orderCategoryModal'
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <ProForm
                    layout={'horizontal'}
                    formRef={formRef}
                    autoFocusFirstInput
                    labelCol={{ style: { width: 80 } }}
                    submitter={false}
                    preserve={false}
                    initialValues={currentRow ? {
                        ...currentRow,
                    } : {
                        FIELDENUM_STATUS: 1,
                    }}
                    onFinish={async (values) => {
                        let newValue = { ...values };
                        if (currentRow) {
                            // 编辑数据
                            newValue = { ...values, FIELDENUM_ID: currentRow.FIELDENUM_ID };
                        }
                        // 如果有开关，要把开关的代码写进去
                        await handleAddUpdate(newValue);

                        handleConfirmLoading(false)
                        setFormPRESALE_TYPE(false)
                    }}
                >
                    <Row gutter={8}>
                        {/* <Col span={12}>
                            <ProFormTreeSelect
                                name="FIELDENUM_PID"
                                label="上级类别"
                                request={async () => {
                                    if (typeTreeData && typeTreeData.length > 0) {
                                        let list: any = [{ FIELDENUM_NAME: "默认类别", FIELDENUM_ID: -1 }, ...typeTreeData]
                                        return list
                                    } else {
                                        const req = {
                                            FIELDEXPLAIN_FIELD: 'GROWTH_TYPE',
                                            FIELDEXPLAIN_ID: "",
                                            FIELDENUM_PID: "",
                                            FIELDENUM_STATUS: 1,
                                            SearchKey: ""
                                        }
                                        const data = await handeGetNestingFIELDENUMList(req);
                                        if (data && data.length > 0) {
                                            data.unshirft({ FIELDENUM_NAME: "默认类别", FIELDENUM_ID: -1 })
                                            setTypeTreeData(data)
                                            return data
                                        } else {
                                            return [{ FIELDENUM_NAME: "默认类别", FIELDENUM_ID: -1 }]
                                        }
                                    }
                                }}
                                fieldProps={{
                                    fieldNames: {
                                        label: 'FIELDENUM_NAME',
                                        value: 'FIELDENUM_ID',
                                        children: 'children'
                                    },
                                    showSearch: true,
                                    filterTreeNode: (input, node) =>
                                        (node.FIELDENUM_NAME || '').toLowerCase().includes(input.toLowerCase())
                                }}
                                rules={[
                                    {
                                        required: true,
                                        message: "请选择上级类别"
                                    }
                                ]}
                            />
                        </Col> */}
                        <Col span={12}>
                            <ProFormText
                                name="FIELDENUM_NAME"
                                label="类别名称"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入类别名称"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDigit
                                name="FIELDENUM_INDEX"
                                label="类别索引"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入类别索引"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDigit
                                name="FIELDENUM_VALUE"
                                label="售后枚举"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入售后枚举"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                name="FIELDENUM_STATUS"
                                label="有效状态"
                                options={[{ label: "有效", value: 1 }, { label: "无效", value: 0 }]}
                                rules={[
                                    {
                                        required: true,
                                        message: "请选择有效状态"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                name="FIELDENUM_DESC"
                                label="备注"
                            />
                        </Col>

                    </Row>
                </ProForm>
            </Modal>
        </PageContainer >
    );
};
export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(GrowthConfig);