// 失物招领审核
import PageTitleBox from "@/components/PageTitleBox";
import { ConnectState } from "@/models/connect";
import ProTable, { ActionType } from "@ant-design/pro-table";
import { Button, Col, FormInstance, Image, message, Modal, Popconfirm, Row } from "antd";
import { useRef, useState } from "react";
import { connect, CurrentUser } from "umi";
import { handeGetSUGGESTIONList, handeSynchroSUGGESTION } from "../service";
import moment from 'moment'
import ProForm, { ProFormDatePicker, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from "@ant-design/pro-form";
import session from "@/utils/session";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { deletePicture } from "@/services/picture";

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 LostandFoundReview: React.FC<{ currentUser: CurrentUser | undefined }> = (props) => {
    const { currentUser } = props
    const { confirm } = Modal;
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modalRef = useRef<FormInstance>();
    // 当前选中行数据
    const [currentRow, setCurrentRow] = useState<any>()
    // 显示新增窗口
    const [showAddModal, setShowAddModal] = useState<boolean>(false)
    // 图片列表
    const [fileList, setFileList] = useState<any>()
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片
    // 弹出框的确认效果
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false)


    const columns: any = [
        {
            title: '统计时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            hideInDescriptions: true,
            initialValue: [moment().subtract(1, 'month'), moment()],
            search: {
                transform: (value: any) => {
                    return {
                        StartDate: value[0],
                        EndDate: value[1],
                    };
                },
            },
        },
        {
            title: '服务区名称',
            width: 150,
            dataIndex: 'SERVERPART_NAME',
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '物品名称',
            width: 150,
            dataIndex: 'SUGGESTION_TITLE',
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.SUGGESTION_TITLE ? <a onClick={() => {
                    setCurrentRow(record)
                    setShowAddModal(true)
                }}>{record?.SUGGESTION_TITLE || "-"}</a> : "-"
            }
        },
        {
            title: '发现时间',
            width: 150,
            dataIndex: 'SUGGESTION_CREATEDATE',
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.SUGGESTION_CREATEDATE ? moment(record?.SUGGESTION_CREATEDATE).format('YYYY-MM-DD HH:mm') : ''
            }
        },
        {
            title: '联系电话',
            width: 150,
            dataIndex: 'PHONE_NUMBER',
            align: 'center',
            ellipsis: true,
            hideInSearch: true,
        },
    ]

    const handleChangePreview = (val: any) => {
        setImagePreviewVisible(val)
    }

    // 悬浮框的关闭事件
    const handleModalClose = () => {
        setConfirmLoading(false)
        setCurrentRow(undefined)
        setFileList([])
        setShowAddModal(false)
    }


    // 新增
    const handleAddLostThing = async (type: number) => {
        // type 1  审核通过   2 驳回
        let req: any = {}
        req = {
            ...currentRow,
            SUGGESTION_STATE: type === 1 ? 1 : 9,
        }

        console.log('req', req);
        const data = await handeSynchroSUGGESTION(req)
        if (data.Result_Code === 100) {
            message.success('审核通过！')
            handleModalClose()
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
            setConfirmLoading(false)
        }

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


    return (
        <div>
            <ProTable
                actionRef={actionRef}
                formRef={formRef}
                columns={columns}
                bordered
                expandable={{
                    expandRowByClick: true
                }}
                scroll={{ x: "100%", y: "calc(100vh - 430px)" }}
                headerTitle={<PageTitleBox props={props} />} // 列表表头
                search={{ span: 6 }}
                request={async (params) => {
                    const req: any = {
                        SearchParameter: {
                            SUGGESTION_TYPES: 4000,
                            SUGGESTION_STATES: 2,
                            ENUM_LABEL: params?.ENUM_LABEL || ''
                        },
                        PageIndex: 1,
                        PageSize: 999999,
                    }

                    const data = await handeGetSUGGESTIONList(req)
                    console.log('1111', data);
                    if (data && data.length > 0) {
                        return { data, success: true }
                    }
                    return { data: [], success: true }
                }}
            />


            {/* 图片预览组件 */}
            {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={"审核失物"}
                destroyOnClose={true}
                width={900}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                visible={showAddModal}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    handleModalClose()
                }}
                footer={
                    <div style={{ width: '100%', boxSizing: 'border-box', padding: '0 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                        <div></div>
                        <div>
                            <Popconfirm
                                title={'确认驳回？'}
                                onConfirm={() => {
                                    handleAddLostThing(2)
                                }}
                            >
                                <Button danger>驳回</Button>
                            </Popconfirm>

                            <Popconfirm
                                title={'确认审核通过？'}
                                onConfirm={() => {
                                    handleAddLostThing(1)
                                }}
                            >
                                <Button style={{ marginLeft: '8px' }} type={"primary"}>审核通过</Button>
                            </Popconfirm>
                        </div>
                    </div>
                }
                okText={"审核通过"}
                onOk={async () => { // 提交框内的数据
                    modalRef.current?.validateFields().then(async (res: any) => {
                        setConfirmLoading(true)
                        await handleAddLostThing(res)
                        setConfirmLoading(false)
                    })
                }}
            >
                <ProForm
                    formRef={modalRef}
                    layout={'horizontal'}
                    submitter={false}
                    request={async () => {
                        if (currentRow?.SUGGESTION_ID) {
                            let imgList: any = []
                            if (currentRow?.ImageList && currentRow?.ImageList.length > 0) {
                                currentRow?.ImageList.forEach((item: any) => {
                                    imgList.push({
                                        label: item.ImageName,
                                        url: item.ImageUrl
                                    })
                                })
                            }
                            setFileList(imgList)
                            return { ...currentRow, SCENICAREA_Image: imgList }
                        }
                        return {}
                    }}
                    labelCol={{ style: { width: 80 } }}
                >
                    <Row gutter={16}>
                        <Col span={12}>
                            <ProFormSelect
                                label={'服务区'}
                                name={'SERVERPART_ID'}
                                rules={[{
                                    required: true,
                                    message: '请选择服务区'
                                }]}
                                request={async () => {
                                    let serverpartList = session.get('serverpartList')
                                    let list: any = []
                                    if (serverpartList && serverpartList.length > 0) {
                                        serverpartList.forEach((item: any) => {
                                            if (item.value !== 586 && item.value !== 650 && item.value !== 680 && item.value !== 897 && item.value !== 841) {
                                                list.push(item)
                                            }
                                        })
                                    }
                                    return list
                                }}
                                fieldProps={{
                                    showSearch: true,  // 启用搜索框
                                    filterOption: (inputValue: any, option: any) => {
                                        // 通过 label 搜索
                                        return option.label.toLowerCase().includes(inputValue.toLowerCase());
                                    }
                                }}
                                readonly
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                label={'物品名称'}
                                name={'SUGGESTION_TITLE'}
                                rules={[{
                                    required: true,
                                    message: '请输入物品名称'
                                }]}
                                readonly
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDatePicker
                                label={'发现时间'}
                                name={'SUGGESTION_CREATEDATE'}
                                width="lg"
                                fieldProps={{
                                    showTime: {
                                        format: 'HH:mm',  // 只显示时和分
                                        minuteStep: 1,    // 分钟步长，可以设置为 5、10 等
                                        hourStep: 1,      // 小时步长
                                    },
                                    format: 'YYYY-MM-DD HH:mm',  // 格式化为日期和时间（只显示时分）
                                }}
                                readonly
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name={"PHONE_NUMBER"}
                                label={"联系电话"}
                                placeholder="请输入手机号"
                                readonly
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                name={"SUGGESTION_REASON"}
                                label={"描述信息"}
                                readonly
                            />
                        </Col>

                        <Col span={24}>
                            <ProFormUploadButton
                                name="SCENICAREA_Image"
                                label={'附件图片'}
                                listType="picture-card"
                                accept="image/*"
                                readonly
                                disabled
                                fieldProps={{
                                    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, '')
                                                        deleteLoading()

                                                        if (success) {
                                                            const files = [...fileList]
                                                            files.splice(index, 1)
                                                            setFileList(files)
                                                            message.success("删除成功")
                                                        }
                                                        else {
                                                            message.error("删除失败")
                                                        }
                                                    } else {
                                                        const files = [...fileList];
                                                        files.splice(index, 1);
                                                        setFileList(files);
                                                    }
                                                },
                                                onCancel() {
                                                },
                                            });
                                        } else {
                                            setFileList(info.fileList)
                                        }
                                        // else {
                                        //     setFileList(info.fileList)
                                        // }
                                    }
                                }}
                            />

                        </Col>
                    </Row>
                </ProForm>

            </Modal >

        </div >
    )
}

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