// 景区信息配置
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, ProFormDigit, 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 { handeDeleteSCENICAREA, handeGetSCENICAREAList, handeSynchroSCENICAREA } from '../service';
import session from '@/utils/session';
import { deleteAHYDPicture, deletePicture, uploadAHYDPicture, uploadPicture } from '@/services/picture';
import ModalFooter from './component/modalFooter';
import { handleSetlogSave } from '@/utils/format';
import { highlightText } from '@/utils/highlightText';


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 < 5;
    if (!isLt2M) {
        message.error('图片大小不超过 5MB!');
    }
    return isJpgOrPng && isLt2M;
}

const scenicSpotConfig: 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 [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const draggleRef = React.createRef<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),
        });
    };

    // 景区类型的枚举
    let SCENICAREATYPEObj = session.get('SCENICAREATYPEObj')
    let SCENICAREATYPEList = session.get('SCENICAREATYPEList')
    // 景区状态的枚举
    let BUSINESSSTATEObj = session.get('BUSINESSSTATEObj')
    let BUSINESSSTATEList = session.get('BUSINESSSTATEList')


    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    // 当前查询的文字
    const [currentSearchText, setCurrentSearchText] = useState<string>('')

    // 定义列表字段内容
    const columns: any = [
        {
            dataIndex: 'searchText',
            title: '查询内容',
            hideInTable: true,
            fieldProps: {
                placeholder: "输入景区名称/景区位置"
            }
        },
        {
            dataIndex: 'SCENICAREA_NAME',
            title: '景区名称',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            hideInDescriptions: true,
            fixed: "left",
            render: (_, record) => {
                return <a onClick={() => {
                    console.log('recordrecord', record);

                    let imgList: any = []
                    if (record?.ImageList && record?.ImageList.length > 0) {
                        record?.ImageList.forEach((item: any) => {
                            let obj = JSON.parse(JSON.stringify(item))
                            obj.url = obj.ImageUrl
                            obj.name = obj.ImageName
                            obj.uid = item.ImageId
                            obj.status = 'done'
                            imgList.push(obj)
                        })
                    }
                    setCurrentRow({
                        ...record,
                        SCENICAREA_Image: imgList
                    });
                    setFileList(imgList);
                    handleModalVisible(true);
                }}>
                    {highlightText(record?.SCENICAREA_NAME, currentSearchText)}
                    {/* {record?.SCENICAREA_NAME || ""} */}
                </a>
            }
        },
        {
            dataIndex: 'SCENICAREA_TYPE',
            title: '景区类型',
            width: 120,
            ellipsis: true,
            align: 'center',
            valueType: "select",
            valueEnum: SCENICAREATYPEObj
        },
        {
            dataIndex: 'SCENICAREA_LOCATION',
            title: '景区位置',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return highlightText(record?.SCENICAREA_LOCATION, currentSearchText)
            }
        },
        {
            dataIndex: 'SCENICAREA_FACILITY',
            title: '景区设施',
            width: 150,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'SCENICAREA_INFO',
            title: '景区简介',
            width: 300,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'SCENICAREA_OPENHOURS',
            title: '开放时间',
            width: 180,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'TICKET_PRICE',
            title: '门票价格',
            width: 120,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            sorter: (a, b) => a.TICKET_PRICE - b.TICKET_PRICE,
            defaultSortOrder: 'descend'
        },
        {
            dataIndex: 'SCENICAREA_LEVEL',
            title: '景区等级',
            width: 120,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'SCENICAREA_SCORE',
            title: '景区评分',
            width: 120,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            sorter: (a, b) => a.SCENICAREA_SCORE - b.SCENICAREA_SCORE
        },
        {
            dataIndex: 'SCENICAREA_EVALUATENUM',
            title: '评价条数',
            width: 120,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            sorter: (a, b) => a.SCENICAREA_EVALUATENUM - b.SCENICAREA_EVALUATENUM
        },
        {
            dataIndex: 'SCENICAREA_PHONE',
            title: '联系电话',
            width: 150,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'SCENICAREA_STATE',
            title: '景区状态',
            width: 120,
            ellipsis: true,
            valueType: 'select',
            align: 'center',
            valueEnum: BUSINESSSTATEObj,
            initialValue: "1000"
        },
        {
            dataIndex: 'OPERATE_DATE',
            title: '修改时间',
            width: 180,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
            render: (_, record) => {
                return record?.OPERATE_DATE ? moment(record?.OPERATE_DATE).format('YYYY-MM-DD HH:mm:ss') : "-"
            }
        },
        // {
        //     dataIndex: 'option',
        //     title: '操作',
        //     width: 120,
        //     ellipsis: true,
        //     valueType: 'option',
        //     hideInSearch: true,
        //     align: 'center',
        //     fixed: "right",
        //     render: (_, record) => {
        //         return (
        //             <Space>
        //                 <a
        //                     onClick={() => {
        //                         let imgList: any = []
        //                         if (record?.ImageList && record?.ImageList.length > 0) {
        //                             record?.ImageList.forEach((item: any) => {
        //                                 let obj = JSON.parse(JSON.stringify(item))
        //                                 obj.url = obj.ImageUrl
        //                                 obj.name = obj.ImageName
        //                                 obj.uid = item.ImageId
        //                                 obj.status = 'done'
        //                                 imgList.push(obj)
        //                             })
        //                         }
        //                         setCurrentRow({
        //                             ...record,
        //                             SCENICAREA_Image: imgList
        //                         });
        //                         setFileList(imgList);
        //                         handleModalVisible(true);
        //                     }}
        //                 >
        //                     编辑
        //                 </a>
        //                 <Popconfirm
        //                     title="确认删除该景区信息列表信息吗?"
        //                     onConfirm={async () => {
        //                         await handelDelete(record.SCENICAREA_ID);
        //                     }}
        //                 >
        //                     <a>删除</a>
        //                 </Popconfirm>
        //             </Space >
        //         );
        //     },
        // },
    ];

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

    const handelDelete = async (scenicareaid: number) => {
        const result = await handeDeleteSCENICAREA({ SCENICAREAId: scenicareaid });

        if (result.Result_Code !== 100) {
            message.error(`${result.Result_Desc}` || `${result.Result_Code}:删除失败`);
        } else {
            message.success('删除成功！');
            handleSetlogSave(`删除【${currentRow?.SCENICAREA_NAME}】`)
            handleConfirmLoading(false)
            handleModalVisible(false)
            setFileList([])
            actionRef.current?.reload()
        }
    };

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

        let req: any = {}
        let imgList: any = []
        if (fileList && fileList.length > 0) {
            fileList.forEach((item: any) => {
                imgList.push({
                    ImageName: item.name,
                    ImageUrl: item.url
                })
            })
        }

        if (currentRow?.SCENICAREA_ID) {
            req = {
                ...currentRow,
                ...res,
                // ImageList: imgList,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        } else {
            req = {
                ...res,
                // ImageList: imgList,
                PROVINCE_CODE: currentUser?.ProvinceCode,
                STAFF_ID: currentUser?.ID,
                STAFF_NAME: currentUser?.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        }
        handleConfirmLoading(true)

        const data = await handeSynchroSCENICAREA(req)
        console.log('datadatadatadata', data);

        if (data.Result_Code === 100) {
            console.log('res.SCENICAREA_Imageres.SCENICAREA_Imageres.SCENICAREA_Image', res.SCENICAREA_Image);
            if (res.SCENICAREA_Image && res.SCENICAREA_Image.length > 0) {
                const formData = new FormData();
                res.SCENICAREA_Image.forEach((file: any) => {
                    if (!file.ImageUrl) {
                        formData.append('files[]', file.originFileObj);
                        formData.append('ImageName', typeof file !== 'string' ? file?.name : '');
                    }
                });
                formData.append('TableId', data.Result_Data.SCENICAREA_ID);
                formData.append('TableType', '1305');

                console.log('formData', formData);
                await uploadAHYDPicture(formData)
            }

            handleSetlogSave(`${currentRow?.SCENICAREA_ID ? `更新${currentRow?.SCENICAREA_NAME}景区` : `新增${data.Result_Data.SCENICAREA_NAME}`}信息`)


            handleConfirmLoading(false)
            message.success("更新成功！")
            setCurrentRow(undefined)
            formRef?.current?.resetFields()
            handleModalVisible(false)
            actionRef.current?.reload()
            setFileList([])
        } else {
            handleConfirmLoading(false)
            message.error(data.Result_Desc)
        }
    };

    return (
        <div style={{
            width: "100%",
            paddingTop: 0,
            paddingBottom: 0,
            paddingRight: 0,
            background: "#fff"
        }}>
            <ProTable
                scroll={{ x: "100%", y: 'calc(100vh - 430px)' }}
                rowKey={(record) => {
                    return `${record?.SCENICAREA_ID}`
                }}
                formRef={formRef}
                headerTitle={<PageTitleBox props={props} />} // 列表表头
                actionRef={actionRef}
                search={{ span: 6, labelWidth: 'auto' }}
                bordered
                // 请求数据
                request={async (params, sorter) => {
                    const req = {
                        searchParameter: {
                            PROVINCE_CODES: currentUser?.ProvinceCode,
                            SCENICAREA_TYPES: params?.SCENICAREA_TYPE,
                            SCENICAREA_STATES: params?.SCENICAREA_STATE,
                        },
                        keyWord: {
                            Key: "SCENICAREA_NAME,SCENICAREA_LOCATION",
                            Value: params?.searchText || ""
                        },
                        PageIndex: 1,
                        PageSize: 999999,
                    }
                    const data = await handeGetSCENICAREAList(req);
                    console.log('datadatadatadatadata', data);
                    setCurrentSearchText(params?.searchText || "")

                    handleSetlogSave(`查看了景区信息配置列表`)

                    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>,
                    ],
                }}
            />


            {/* 图片预览组件 */}
            {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='scenicSpotConfig'
                        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)
                    setFileList([])
                }}
                footer={<ModalFooter hideDelete={!currentRow?.SCENICAREA_ID} handleDelete={async () => {
                    await handelDelete(currentRow?.SCENICAREA_ID);

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

                        handleConfirmLoading(false)
                        handleModalVisible(false);
                    }}
                >
                    <Row gutter={8}>
                        <Col span={12}>
                            <ProFormSelect
                                name="SCENICAREA_TYPE"
                                label="景区类型"
                                options={SCENICAREATYPEList}
                                rules={[
                                    {
                                        required: true,
                                        message: "请选择景区类型！"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="SCENICAREA_NAME"
                                label="景区名称"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入景区名称！"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormText
                                name="SCENICAREA_LOCATION"
                                label="景区地址"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDigit
                                name="SCENICAREA_X"
                                label="景区经度"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入景区经度！"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDigit
                                name="SCENICAREA_Y"
                                label="景区纬度"
                                rules={[
                                    {
                                        required: true,
                                        message: "请输入景区纬度！"
                                    }
                                ]}
                            />
                        </Col>


                        <Col span={12}>
                            <ProFormText
                                name="SCENICAREA_OPENHOURS"
                                label="开放时间"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDigit
                                name="TICKET_PRICE"
                                label="门票价格"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="SCENICAREA_LEVEL"
                                label="景区等级"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDigit
                                name="SCENICAREA_SCORE"
                                label="景区评分"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDigit
                                name="SCENICAREA_EVALUATENUM"
                                label="评价条数"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="SCENICAREA_PHONE"
                                label="联系电话"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="SCENICAREA_EMAIL"
                                label="联系邮箱"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name="SCENICAREA_WEBSITE"
                                label="官方网站"
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                name="SCENICAREA_STATE"
                                label="景区状态"
                                options={BUSINESSSTATEList}
                                rules={[
                                    {
                                        required: true,
                                        message: "请选择景区状态！"
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                name="SCENICAREA_FACILITY"
                                label="景区设施"
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormUploadButton
                                name="SCENICAREA_Image"
                                label="景区图片"
                                listType="picture-card"
                                accept="image/*"
                                fieldProps={{
                                    beforeUpload: beforeUpload,
                                    onPreview: handlePreview,
                                    fileList: fileList, // 绑定 fileList
                                    customRequest: ({ file, onSuccess }) => {
                                        // 自定义上传，不实际发送请求
                                        setTimeout(() => {
                                            if (onSuccess) {
                                                onSuccess({});
                                            }
                                        }, 0);
                                    },
                                    onChange: async (info: any) => {
                                        console.log('info', info);
                                        console.log('fileList', fileList);
                                        if (info.file.status === 'removed') {
                                            const index = fileList.findIndex(n => n.uid === info.file.uid);
                                            confirm({
                                                title: '确认删除该文件吗？',
                                                icon: <ExclamationCircleOutlined />,
                                                async onOk() {
                                                    if (info.file.ImageId) {
                                                        const deleteLoading = message.loading('正在删除...')
                                                        // const success = await deletePicture(info.file?.ImagePath, info.file?.uid, '', '5000')
                                                        const success = await deleteAHYDPicture(info.file?.ImagePath, info.file?.uid, '', '5000')
                                                        deleteLoading()

                                                        if (success) {
                                                            const files = [...fileList]
                                                            files.splice(index, 1)
                                                            setFileList(files)
                                                            message.success("删除成功")
                                                            actionRef.current?.reload()
                                                        }
                                                        else {
                                                            message.error("删除失败")
                                                        }
                                                    } else {
                                                        const files = [...fileList];
                                                        files.splice(index, 1);
                                                        setFileList(files);
                                                    }
                                                },
                                                onCancel() {
                                                },
                                            });
                                        } else {
                                            setFileList(info.fileList)
                                        }
                                    }
                                }}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                name="SCENICAREA_INFO"
                                label="景区简介"
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                name="SCENICAREA_DESC"
                                label="备注说明"
                            />
                        </Col>
                    </Row>
                </ProForm>
            </Modal >
        </div >
    );
};
export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser
}))(scenicSpotConfig);
