import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { Button, Col, FormInstance, message, Modal, Row } from "antd";
import { useRef, useState } from "react";
import React from "react";
import Draggable from "react-draggable";
import ProForm, { ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from "@ant-design/pro-form";
import session from "@/utils/session";
import { handleGetServerpartInfo } from "@/pages/newDataAnalysis/service";
import { compressImage } from "@/utils/imageCompress";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { deleteAHYDPicture, uploadAHYDPicture } from "@/services/picture";
import { handleGetRESTSTATIONBILLList, handleGetSynchroRESTSTATION } from "../service";
import moment from 'moment'
import ProTable, { ActionType } from "@ant-design/pro-table";
import SharedRestStationOrderDetail from "./SharedRestStationOrderDetail";

type DetailProps = {
    parentRow: any; // 当前行数据
    setParentRow: any; // 改变当前行数据的方法
    onShow: any;// 显示悬浮框
    setOnShow: any;// 改变显示悬浮框的方法
    readonly?: any;// 判断是不是只读
    fileList: any;// 图片附件
    setFileList: any;// 改变图片附件的方法
    currentUser: any;// 页面公参
    actionRef: any;// 父级表格实例
}

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

const SharedRestStationDetail = ({ parentRow, setParentRow, onShow, setOnShow, readonly, fileList, setFileList, currentUser, actionRef }: DetailProps) => {
    const draggleRef = React.createRef<any>()
    const tableRef = useRef<ActionType>();

    const { confirm } = Modal;
    const modalFromRef = useRef<FormInstance>();
    const serverpartList = session.get('serverpartList')
    const serverpartObj = session.get('serverpartObj')

    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    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 [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
    const [selectName, setSelectName] = useState<string[]>(); // 选择的服务区名称
    // 当前选择的服务区方位
    const [REGIONList, setREGIONList] = useState<any>([])
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    // 显示订单详情的悬浮框
    const [orderModalVisible, handleOrderModalVisible] = useState<boolean>(false);
    // 订单的当前行数据
    const [currentRow, setCurrentRow] = useState<any>();

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

    const columns: any = [
        {
            title: <div style={{ textAlign: 'center' }}>订单编码</div>,
            width: 150,
            align: 'center',
            dataIndex: "RESTSTATIONBILL_CODE",
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return <a onClick={() => {
                    setCurrentRow(record)
                    handleOrderModalVisible(true)
                }}>
                    {record.RESTSTATIONBILL_CODE}
                </a>
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>会员名称</div>,
            width: 150,
            align: 'center',
            dataIndex: "MEMBERSHIP_NAME",
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>手机号码</div>,
            width: 150,
            align: 'center',
            dataIndex: "MEMBERSHIP_MOBILEPHONE",
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>下单时间</div>,
            width: 150,
            align: 'center',
            dataIndex: "ORDER_STARTDATE",
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.ORDER_STARTDATE ? moment(record?.ORDER_STARTDATE).format('YYYY/MM/DD HH:mm:ss') : ''
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>结束时间</div>,
            width: 150,
            align: 'center',
            dataIndex: "ORDER_ENDDATE",
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.ORDER_ENDDATE ? moment(record?.ORDER_ENDDATE).format('YYYY/MM/DD HH:mm:ss') : ''
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>剩余时间</div>,
            width: 150,
            align: 'center',
            dataIndex: "REMAIN_SECONDS",
            ellipsis: true,
            hideInSearch: true
        },
        {
            title: <div style={{ textAlign: 'center' }}>续费状态</div>,
            width: 150,
            align: 'center',
            dataIndex: "RENEWAL_STATUS",
            ellipsis: true,
            hideInSearch: true,
            valueType: "select",
            valueEnum: {
                1: { text: '未续费', status: 'error' },
                2: { text: '已续费', status: 'Success' },
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>保洁状态</div>,
            width: 150,
            align: 'center',
            dataIndex: "CLEANING_STATUS",
            ellipsis: true,
            hideInSearch: true,
            valueType: "select",
            valueEnum: {
                0: { text: '待清洁', status: 'error' },
                1: { text: '已清洁', status: 'Success' },
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>订单状态</div>,
            width: 150,
            align: 'center',
            dataIndex: "RESTSTATIONBILL_STATE",
            ellipsis: true,
            hideInSearch: true,
            valueType: "select",
            fieldProps: {
                options: [{ label: '待付款', value: 1 }, { label: '使用中', value: 2 }, { label: '已完成', value: 3 }]
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>联系电话</div>,
            width: 150,
            align: 'center',
            dataIndex: "EMERGENCY_PHONENUMBER",
            ellipsis: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>评价打分</div>,
            width: 150,
            align: 'center',
            dataIndex: "RESTSTATIONBILL_SCORE",
            ellipsis: true,
            hideInSearch: true
        },
    ]

    // 新增同步休息站
    const handleAddUpdateStation = async (obj: any) => {
        let req: any = {}

        if (parentRow.RESTSTATION_ID) {
            req = {
                ...parentRow,
                ...obj,
                STAFF_ID: currentUser.ID,
                STAFF_NAME: currentUser.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        } else {
            req = {
                ...obj,
                PROVINCE_CODE: "530000",
                SERVERPART_NAME: serverpartObj[obj.SERVERPART_ID],
                STAFF_ID: currentUser.ID,
                STAFF_NAME: currentUser.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            }
        }
        console.log('reqreqreqreq', req);
        handleConfirmLoading(true)
        const data = await handleGetSynchroRESTSTATION(req)
        if (data.Result_Code === 100) {

            if (obj.RESTSTATION_IMG && obj.RESTSTATION_IMG.length > 0) {
                const formData = new FormData();
                obj.RESTSTATION_IMG.forEach((file: any) => {
                    if (!file.ImageUrl) {
                        // 使用压缩后的文件，如果没有则使用原文件
                        const fileToUpload = file.originFileObj?.compressedFile || file.originFileObj;
                        formData.append('files[]', fileToUpload);
                        formData.append('ImageName', typeof file !== 'string' ? file?.name : '');
                    }
                });
                formData.append('TableId', data.Result_Data.RESTSTATION_ID);
                formData.append('TableType', '1309');

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

            handleConfirmLoading(false)
            message.success(data.Result_Desc)
            setOnShow(false)
            setParentRow(undefined);
            setFileList([])
            if (actionRef) {
                actionRef.current?.reload()
            }
        } else {
            handleConfirmLoading(false)
            message.error(data.Result_Desc)
        }
    }

    return (
        <div>
            <Modal
                className="SharedRestStationManagement"
                title={
                    <div
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}

                        onFocus={() => { }}
                        onBlur={() => { }}
                    >
                        {parentRow ? '编辑共享休息站' : '新增共享休息站'}
                    </div>
                }
                destroyOnClose={true}
                width={900}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                open={onShow}
                confirmLoading={confirmLoading}
                afterClose={() => {
                    modalFromRef.current?.resetFields();
                    setParentRow(undefined);
                }}
                onCancel={() => {
                    handleConfirmLoading(false)
                    setOnShow(false)
                    setParentRow(undefined);
                    setREGIONList([])
                    setFileList([])
                }}
                footer={readonly ? '' :
                    <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
                        <Button onClick={() => {
                            handleConfirmLoading(false)
                            setOnShow(false)
                            setParentRow(undefined);
                            setREGIONList([])
                            setFileList([])
                        }}>取消</Button>
                        <Button type="primary" loading={confirmLoading} style={{ marginLeft: '16px' }} onClick={async () => {
                            modalFromRef.current?.validateFields().then(async (values) => {
                                await handleAddUpdateStation(values)
                            })
                        }}>
                            确认
                        </Button>
                    </div>
                }
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                        handle=".SharedRestStationManagement"
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <ProForm
                    layout={'horizontal'}
                    formRef={modalFromRef}
                    submitter={false}
                    labelCol={{ style: { width: 100 } }}
                    request={async () => {
                        if (parentRow) {
                            if (parentRow?.SERVERPART_ID) {
                                const regReq: any = {
                                    ServerpartId: parentRow?.SERVERPART_ID
                                }
                                const regData = await handleGetServerpartInfo(regReq)
                                console.log('regDataregDataregData', regData);

                                let list: any = regData.RegionInfo
                                let res: any = []
                                if (list && list.length > 0) {
                                    list.forEach((item: any) => {
                                        res.push({ label: item.SERVERPART_REGIONNAME, value: item.SERVERPART_REGION })
                                    })
                                }
                                setREGIONList(res)
                            }
                            return { ...parentRow, SERVERPART_REGION: Number(parentRow.SERVERPART_REGION) };
                        } else {
                            return {}
                        }

                    }}
                >
                    <Row gutter={8}>
                        <Col span={12}>
                            <ProFormText
                                label={"休息站名称"}
                                name={"RESTSTATION_NAME"}
                                rules={[{ required: true, message: '请输入共享休息站名称' }]}
                                readonly={readonly}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                label={"所属服务区"}
                                name={"SERVERPART_ID"}
                                fieldProps={{
                                    options: serverpartList,
                                    showSearch: true,
                                    onChange: async (e, option) => {
                                        modalFromRef.current?.setFieldsValue({ SERVERPART_REGION: '' })
                                        if (e) {
                                            const regReq: any = {
                                                ServerpartId: e
                                            }
                                            const regData = await handleGetServerpartInfo(regReq)
                                            console.log('regDataregDataregData', regData);

                                            let list: any = regData.RegionInfo
                                            let res: any = []
                                            if (list && list.length > 0) {
                                                list.forEach((item: any) => {
                                                    res.push({ label: item.SERVERPART_REGIONNAME, value: item.SERVERPART_REGION })
                                                })
                                            }
                                            setREGIONList(res)
                                        } else {
                                            setREGIONList([])
                                        }
                                    }
                                }}
                                readonly={readonly}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                label={"服务区方位"}
                                name={"SERVERPART_REGION"}
                                fieldProps={{
                                    options: REGIONList,
                                }}

                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                label={"所在位置"}
                                name={"RESTSTATION_LOCATION"}
                            />
                        </Col>

                        <Col span={12}>
                            <ProFormSelect
                                label={"门锁状态"}
                                name={"LOCK_STATUS"}
                                fieldProps={{
                                    options: [{ label: "空闲中", value: 1 }, { label: "使用中", value: 2 }],
                                }}

                            />
                        </Col>

                        <Col span={12}>
                            <ProFormSelect
                                label={"保洁状态"}
                                name={"CLEANING_STATUS"}
                                fieldProps={{
                                    options: [{ label: "待清洁", value: 1 }, { label: "清洁中", value: 2 }, { label: "已清洁", value: 3 }],
                                }}

                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                label={"紧急联系电话"}
                                name={"EMERGENCY_CONTACT"}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDigit
                                label={"评价打分"}
                                name={"RESTSTATIONBILL_SCORE"}
                                fieldProps={{
                                    max: 5
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                label={"有效状态"}
                                name={"RESTSTATION_STATE"}
                                fieldProps={{
                                    options: [{ label: "有效", value: 1 }, { label: "无效", value: 0 }],
                                }}
                                initialValue={1}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                label={"备注说明"}
                                name={"RESTSTATION_DESC"}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormUploadButton
                                name="RESTSTATION_IMG"
                                label="休息室图片"
                                listType="picture-card"
                                accept="image/*"
                                readonly={readonly}
                                fieldProps={{
                                    beforeUpload: beforeUpload,
                                    onPreview: handlePreview,
                                    fileList: fileList, // 绑定 fileList
                                    customRequest: ({ file, onSuccess, onError, onProgress }) => {
                                        // 开始处理
                                        onProgress?.({ percent: 10 });
                                        compressImage(file as File, {
                                            width: 300,
                                            height: 300,
                                            maxSize: 200 // KB
                                        })
                                            .then(compressedFile => {
                                                console.log(`压缩成功: ${file.name} 从 ${(file.size / 1024).toFixed(1)}KB 压缩到 ${(compressedFile.size / 1024).toFixed(1)}KB`);

                                                // 保存压缩后的文件到原文件对象上
                                                (file as any).compressedFile = compressedFile;

                                                onProgress?.({ percent: 100 });
                                                onSuccess?.(compressedFile);
                                            })
                                            .catch(err => {
                                                console.error('图片压缩失败:', err);
                                                message.error('图片处理失败，请重试');
                                                onError?.(err);
                                            });
                                    },
                                    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("删除成功")
                                                            if (actionRef) {
                                                                actionRef.current?.reload()
                                                            }
                                                        }
                                                        else {
                                                            message.error("删除失败")
                                                        }
                                                    } else {
                                                        const files = [...fileList];
                                                        files.splice(index, 1);
                                                        setFileList(files);
                                                    }
                                                },
                                                onCancel() {
                                                },
                                            });
                                        } else {
                                            setFileList(info.fileList)
                                        }
                                    }
                                }}
                            />
                        </Col>
                    </Row>



                    {/* 休息站订单信息 */}
                    {
                        parentRow && parentRow.RESTSTATION_ID ?
                            <div>
                                <ProTable
                                    actionRef={tableRef}
                                    bordered
                                    columns={columns}
                                    search={{ span: 12 }}
                                    scroll={{ x: "100%", y: 400 }}
                                    request={async (params: any) => {
                                        const req: any = {
                                            SearchParameter: {
                                                RESTSTATION_IDS: parentRow?.RESTSTATION_ID,
                                                RESTSTATIONBILL_STATES: "1,2,3"
                                            },
                                            KeyWord: {
                                                Key: 'EMERGENCY_PHONENUMBER',
                                                Value: params?.EMERGENCY_PHONENUMBER || ''
                                            },
                                            PageIndex: 1,
                                            PageSize: 999999,
                                        }
                                        const data = await handleGetRESTSTATIONBILLList(req)
                                        console.log('datadatadata', data);
                                        if (data && data.length > 0) {
                                            return { data, success: true }
                                        }
                                        return { data: [], success: true }
                                    }}
                                    options={false}
                                    toolbar={{
                                        actions: [
                                            <Button
                                                key="new"
                                                type="primary"
                                                onClick={() => {
                                                    handleOrderModalVisible(true)
                                                }}
                                            >
                                                同步订单
                                            </Button>
                                        ]
                                    }}
                                />
                            </div> : ""
                    }
                </ProForm>
            </Modal>

            <SharedRestStationOrderDetail bigParams={parentRow} onShow={orderModalVisible} setOnShow={handleOrderModalVisible} parentRow={currentRow} setParentRow={setCurrentRow} actionRef={tableRef} currentUser={currentUser} readonly={currentRow?.RESTSTATIONBILL_ID} />
        </div>
    )
}

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