// 失物招领申请
import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import ProCard from "@ant-design/pro-card";
import { ExclamationCircleOutlined, MenuFoldOutlined } from "@ant-design/icons";
import { Col, FormInstance, Modal, Popconfirm, Row } from "antd";
import { Button, message, Space, Spin, Tree, Image } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getFieldEnumTree, getServerpartTree } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import LeftSelectTree from "@/pages/reports/settlementAccount/component/leftSelectTree";
import PageTitleBox from "@/components/PageTitleBox";
import moment from 'moment'
import ProForm, { ProFormDatePicker, ProFormDateRangePicker, ProFormSelect, ProFormText, ProFormTextArea, ProFormTreeSelect, ProFormUploadButton } from "@ant-design/pro-form";
import { handleGetPictureList } from "@/pages/reports/settlementAccount/service";
import session from "@/utils/session";
import { handeDeleteSUGGESTION, handeGetPictureList, handeGetSUGGESTIONList, handeSynchroSUGGESTION } from "../service";
import { deletePicture, uploadPicture } 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 LostandFoundAPPliance: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { confirm } = Modal;
    const { currentUser } = props
    const downloadBtnRef = useRef<any>()
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const modalRef = useRef<FormInstance>();
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
    const [collapsible, setCollapsible] = useState<boolean>(false)
    const [treeView, setTreeView] = useState<any>()
    const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())
    const [lostTypeList, setLostTypeList] = useState<any>()
    const [lostTypeObj, setLostTypeObj] = useState<any>()
    // 显示新增窗口
    const [showAddModal, setShowAddModal] = useState<boolean>(false)

    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 导出的加载效果
    const [showLoading, setShowLoading] = useState<boolean>(false)
    // 是否显示打印的表格
    const [showExportTable, setShowExportTable] = useState<boolean>(false)
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()
    // 当前选中行数据
    const [currentRow, setCurrentRow] = useState<any>()
    // 弹出框的确认效果
    const [confirmLoading, setConfirmLoading] = useState<boolean>(false)
    // 图片列表
    const [fileList, setFileList] = useState<any>()

    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false) // 预览图片

    const { loading: serverpartloading, data: myServerpartList = [] } = useRequest(async () => {
        const list = await getFieldEnumTree({ FieldExplainField: 'business_target' })
        let lostList: any = []
        if (list && list.length > 0) {
            list.forEach((item: any) => {
                if (item.value === 6000) {
                    lostList = item.children
                }
            })
        }
        setLostTypeList(lostList)
        let obj: any = {}
        if (lostList && lostList.length > 0) {
            lostList.forEach((item: any) => {
                item.disabled = true
                if (item.children && item.children.length > 0) {
                    item.children.forEach((subItem: any) => {
                        obj[subItem.value] = subItem.label
                    })
                }
            })
        }
        setLostTypeObj(obj)
        return lostList
    })

    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: 'ENUM_LABEL',
        //     valueType: 'treeSelect',
        //     request: async () => {
        //         return myServerpartList
        //     },
        //     // valueEnum: lostTypeList,
        //     fieldProps: {
        //         showSearch: true,
        //         allowClear: true,
        //         treeDefaultExpandAll: true,
        //         filterTreeNode: (inputValue: any, treeNode: any) => {
        //             // 通过 label 搜索
        //             return treeNode.label.toLowerCase().includes(inputValue.toLowerCase());
        //         },
        //     },
        //     render: (_, record) => {
        //         return record?.ENUM_LABEL && lostTypeObj ? lostTypeObj[record?.ENUM_LABEL] : '-'
        //     }
        // },
        {
            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_STATE',
            align: 'center',
            valueType: 'select',
            valueEnum: {
                "1": "审核通过",
                "2": "审核中",
                "9": "已驳回"
            },
            ellipsis: true,
            hideInSearch: true,
        },
        {
            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,
        },
        // {
        //     title: '操作',
        //     dataIndex: "options",
        //     hideInSearch: true,
        //     width: 120,
        //     align: 'center',
        //     ellipsis: true,
        //     render: (_, record) => {
        //         return <div>
        //             <a onClick={() => {
        //                 setCurrentRow(record)
        //                 setShowAddModal(true)
        //             }}>
        //                 编辑
        //             </a>
        //             <Popconfirm
        //                 title={'确认删除？'}
        //                 onConfirm={() => {
        //                     handleDeleteThing(record?.SUGGESTION_ID)
        //                 }}
        //             >
        //                 <a style={{ marginLeft: '8px' }}>删除</a>
        //             </Popconfirm>

        //         </div>
        //     }
        // }
    ]

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

    // 新增
    const handleAddLostThing = async (obj: any) => {
        let serverpartObj: any = session.get('serverpartObj')
        let req: any = {}
        if (currentRow?.SUGGESTION_ID) {
            req = {
                ...currentRow,
                ...obj,
                SUGGESTION_ID: currentRow?.SUGGESTION_ID,
                SUGGESTION_STATE: 2,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                SUGGESTION_CREATEDATE: obj?.SUGGESTION_CREATEDATE ? moment(obj?.SUGGESTION_CREATEDATE).format('YYYY-MM-DD HH:mm:ss') : '',
                SERVERPART_NAME: obj.SERVERPART_ID ? serverpartObj[obj.SERVERPART_ID] : ''
            }
        } else {
            req = {
                ...obj,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
                PROVINCE_CODE: currentUser?.ProvinceCode,
                SUGGESTION_CREATEDATE: obj?.SUGGESTION_CREATEDATE ? moment(obj?.SUGGESTION_CREATEDATE).format('YYYY-MM-DD HH:mm:ss') : '',
                SUGGESTION_STATE: 2,
                SUGGESTION_TYPE: 4000,
                SERVERPART_NAME: obj.SERVERPART_ID ? serverpartObj[obj.SERVERPART_ID] : ''
            }
        }

        console.log('req', req);
        const data = await handeSynchroSUGGESTION(req)
        if (data.Result_Code === 100) {
            console.log('datadatadatadata', data);
            message.success(data.Result_Desc)
            if (obj.SCENICAREA_Image && obj.SCENICAREA_Image.length > 0) {
                handleSaveImg(obj.SCENICAREA_Image, data.Result_Data)
            }
            handleModalClose()
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
            setConfirmLoading(false)
        }
    }

    // 保存图片
    const handleSaveImg = async (imgList: any, objData: any) => {
        // objData 保存之后的数据
        const formData = new FormData();
        imgList.forEach((file: any) => {
            formData.append('files[]', file.originFileObj);
            formData.append('ImageName', typeof file !== 'string' ? file?.name : '');
        });
        formData.append('TableId', objData.SUGGESTION_ID);
        // formData.append('TableId', shopData.COMMODITY_ID);
        formData.append('TableType', "1306");

        console.log('formData', formData);
        let res = await uploadPicture(formData)
    }

    // 删除
    const handleDeleteThing = async (id: any) => {
        const data = await handeDeleteSUGGESTION({ SUGGESTIONId: id })
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            actionRef.current?.reload()
        } else {
            message.error(data.Result_Desc)
        }
    }

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


    return (
        <div ref={(el) => {
            // 打印报表
            if (!reqDetailList || reqDetailList.length === 0) return;
            setPrintOut(el);
        }} >

            <div className={`saleReportHideBox${printIndex}`} style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }}>
                {
                    showExportTable && reqDetailList && reqDetailList.length > 0 ?
                        <ProTable
                            columns={columns}
                            dataSource={reqDetailList}
                            pagination={false}
                            expandable={{
                                defaultExpandAllRows: true
                            }}
                        /> : ''
                }
            </div>
            <div id='hiddenBox' style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }} />

            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} />
                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        headerTitle={<PageTitleBox props={props} />}
                        search={{ span: 6 }}
                        request={async (params) => {
                            if (!selectedId) {
                                return
                            }
                            const req: any = {
                                SearchParameter: {
                                    SUGGESTION_TYPES: 4000,
                                    SERVERPART_IDS: selectedId,
                                    SUGGESTION_STATES: "1,2,9",
                                    ENUM_LABEL: params?.ENUM_LABEL || ''
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                            }
                            setSearchParams(params)

                            const data = await handeGetSUGGESTIONList(req)
                            if (data && data.length > 0) {
                                return { data, success: true }
                            }
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [
                                <Button type="primary" onClick={() => {
                                    setShowAddModal(true)
                                }}>新增失物招领</Button>
                            ]
                        }}
                    />
                </div>
            </div>

            {/* 图片预览组件 */}
            {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={currentRow ? "编辑失物信息" : "新增失物信息"}
                destroyOnClose={true}
                width={900}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                visible={showAddModal}
                confirmLoading={confirmLoading}
                onCancel={() => {
                    handleModalClose()
                }}
                footer={currentRow?.SUGGESTION_ID ? false :
                    <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', boxSizing: 'border-box', padding: '0 16px' }}>
                        <div></div>
                        <div>
                            <Button style={{ marginRight: '8px' }} onClick={() => {
                                handleModalClose()
                            }}>取消</Button>
                            <Button type={'primary'} loading={confirmLoading} onClick={() => {
                                modalRef.current?.validateFields().then(async (res: any) => {
                                    setConfirmLoading(true)
                                    await handleAddLostThing(res)
                                    setConfirmLoading(false)
                                })
                            }}>发起申请</Button>
                        </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());
                                    }
                                }}
                            />
                        </Col>
                        {/* <Col span={12}>
                            <ProFormTreeSelect
                                label={'失物类型'}
                                name={'ENUM_LABEL'}
                                rules={[{
                                    required: true,
                                    message: '请选择失物类型'
                                }]}
                                fieldProps={{
                                    showSearch: true, // 启用搜索框
                                    treeDefaultExpandAll: true, // 默认展开所有节点
                                    filterTreeNode: (inputValue: string, treeNode: any) => {
                                        // 通过label进行模糊匹配
                                        return treeNode.label.toLowerCase().includes(inputValue.toLowerCase());
                                    },
                                    options: lostTypeList // 传入树形节点数据
                                }}
                            />
                        </Col> */}
                        <Col span={12}>
                            <ProFormText
                                label={'物品名称'}
                                name={'SUGGESTION_TITLE'}
                                rules={[{
                                    required: true,
                                    message: '请输入物品名称'
                                }]}
                            />
                        </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',  // 格式化为日期和时间（只显示时分）
                                }}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                name={"PHONE_NUMBER"}
                                label={"联系电话"}
                                placeholder="请输入手机号"
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                name={"SUGGESTION_REASON"}
                                label={"描述信息"}
                            />
                        </Col>

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