// 预览附件的页面
import { connect } from "umi";
import { ConnectState } from "@/models/global";
import './style.less'
import { ActionType, FormInstance, ProForm, ProFormDatePicker, ProFormSelect, ProFormText, ProFormTimePicker, ProFormUploadButton, ProTable } from "@ant-design/pro-components";
import { useEffect, useRef, useState } from "react";
import { Button, Col, Divider, message, Row, Image, Modal } from "antd";
import { handleGetPATROLList, handleGetSERVERPARTDetail, handleGetServerpartTree, handleGetSERVERPARTTYPEList, handleSynchroPATROL, handleSynchroRECTIFICATION } from "./service";
import { handleGetPassportInfoById } from "../DigitalElectronics/service";
import moment from "moment";
import { encryptAES } from "@/utils/handleAes";
import AddInspectionItems from "./components/AddInspectionItems";
import AddInspectionContent from "./components/AddInspectionContent";
import normalIcon from '../../assets/normalIcon.png'
import errorIcon from '../../assets/errorIcon.png'
import RectificationStatusInfoModal from "./components/RectificationStatusInfoModal";
import { handleGetServerpartInfo, uploadAHYDPicture } from "../serverpartAssets/service";
import { ExclamationCircleOutlined } from "@ant-design/icons";


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

const OperationReport = ({ PATROLID }: DetailProps) => {
    const { confirm } = Modal;
    const actionRef = useRef<ActionType>();
    const AddInspectionItemsRef = useRef<any>();
    const AddInspectionContentRef = useRef<any>();
    const formRef = useRef<FormInstance>();
    // 选中的行
    const [selectedRowKey, setSelectedRowKey] = useState<any>();
    // 保存数据
    const [saveLoading, setSaveLoading] = useState<boolean>(false)
    // 当前的用户信息
    const [userInfoDetail, setUserInfoDetail] = useState<any>()
    // 当前片区下的服务区列表
    const [serverPartList, setServerPartList] = useState<any>()
    // 当前服务区下的方位
    const [SERVERPARTREGION, setSERVERPARTREGION] = useState<any>()
    // 显示同步巡检项目的悬浮框
    const [showInspectionItemsModal, setShowInspectionItemsModal] = useState<boolean>(false)
    // 巡检项目 表格数据
    const [inspectionItemsTableData, setInspectionItemsTableData] = useState<any>()
    // 添加巡检内容的悬浮框
    const [addContentModal, setAddContentModal] = useState<boolean>(false)
    // 根据当前的巡检项目的id  里面包含的巡检内容
    const [inspectionItemObj, setInspectionItemObj] = useState<any>()
    // 根据当前的巡检项目的id  里面包含的现场照片
    const [inspectionItemPhoto, setInspectionItemPhoto] = useState<any>()
    // 巡检内容 显示的列表
    const [inspectionContentList, setInspectionContentList] = useState<any>()
    // 页面的数据类型  区分日常巡检 和 现场巡检
    const [pageDataType, setPageDataType] = useState<number>(1000)
    // 整改情况modal
    const [rectificationStatusModal, setRectificationStatusModal] = useState<boolean>(false)
    // 当前的巡检记录
    const [currentRecord, setCurrentRecord] = useState<any>()
    // 整改情况的行数据
    const [currentRectification, setCurrentRectification] = useState<any>()
    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    // 预览图片
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false)

    // 预览上传后的图片
    const handlePreview = async () => {
        setFileList(fileList)
        setImagePreviewVisible(true)
    };
    // 表格字段
    const columns: any = [
        {
            title: "序号",
            dataIndex: 'index',
            valueType: 'index',
            hideInSearch: true,
            align: 'center',
            width: 80,
            ellipsis: true
        },
        {
            title: "状态",
            dataIndex: 'PATROLDETAIL_STATE',
            valueType: 'select',
            hideInSearch: true,
            align: 'center',
            width: 120,
            ellipsis: true,
            fieldProps: {
                options: [
                    { label: "编辑中", value: 1 },
                    { label: "巡查中", value: 2 },
                    { label: "待跟进", value: 3 },
                    { label: "整改中", value: 4 },
                    { label: "已完成", value: 5 },
                ]
            }
        },
        {
            title: pageDataType === 3000 ? "检查项目" : "巡检项目",
            dataIndex: 'PATROL_POSITION',
            hideInSearch: true,
            align: 'center',
            width: 180,
            ellipsis: true
        },
        {
            title: "合作单位",
            dataIndex: 'DUTYUNIT_NAME',
            hideInSearch: true,
            align: 'center',
            width: 150,
            ellipsis: true
        },
        {
            title: "检查人",
            dataIndex: 'INSPECTION_PERSON',
            hideInSearch: true,
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInTable: pageDataType === 3000 ? false : true
        },
        {
            title: "检查开始时间",
            dataIndex: 'INSPECTION_STARTTIME',
            hideInSearch: true,
            align: 'center',
            width: 180,
            ellipsis: true,
            hideInTable: pageDataType === 3000 ? false : true
        },
        {
            title: "检查完成时间",
            dataIndex: 'INSPECTION_ENDTIME',
            hideInSearch: true,
            align: 'center',
            width: 180,
            ellipsis: true,
            hideInTable: pageDataType === 3000 ? false : true
        },
    ]

    // 数据录入的方法
    const handleAddUpdate = async (obj: any) => {
        // 用参数去判断 两个嵌套的子集 是否已经有数据了 没有的话 就提示
        let list: any = []
        if (inspectionItemsTableData && inspectionItemsTableData.length > 0) {
            list = JSON.parse(JSON.stringify(inspectionItemsTableData))
            list.forEach((item: any) => {
                if (inspectionItemObj && inspectionItemObj[`${item?.PATROL_ID}-${item?.rowIndex || item?.PATROLDETAIL_ID}`] && inspectionItemObj[`${item?.PATROL_ID}-${item?.rowIndex || item?.PATROLDETAIL_ID}`].length > 0) {
                    item.PATROLCONTENTList = inspectionItemObj[`${item?.PATROL_ID}-${item?.rowIndex || item?.PATROLDETAIL_ID}`]
                }

                if (inspectionItemPhoto && inspectionItemPhoto[`${item?.PATROL_ID}-${item?.rowIndex || item?.PATROLDETAIL_ID}`] && inspectionItemPhoto[`${item?.PATROL_ID}-${item?.rowIndex || item?.PATROLDETAIL_ID}`].length > 0) {
                    // item.PATROLCONTENTList = inspectionItemPhoto[`${item?.PATROL_ID}-${item?.rowIndex || item?.PATROLDETAIL_ID}`]
                    // 保存现场照片的路径

                    let url: string = ""
                    let list: any = inspectionItemPhoto[`${item?.PATROL_ID}-${item?.rowIndex || item?.PATROLDETAIL_ID}`]
                    if (list && list.length > 0) {
                        list.forEach((item: any) => {
                            if (url) {
                                url += `,${item.url}`
                            } else {
                                url = item.url
                            }
                        })
                    }
                    item.ONSITEPHOTO_URL = url
                }
            })
        }



        const req: any = {
            ...obj,
            INSPECTION_ENDTIME: moment(obj.INSPECTION_ENDTIME).format('YYYY-MM-DD'),
            INSPECTION_STARTTIME: moment(obj.INSPECTION_STARTTIME).format('YYYY-MM-DD'),
            PATROL_DATE: moment(obj.PATROL_DATE).format('YYYY-MM-DD'),
            PATROL_STARTTIME: `${moment(obj.PATROL_DATE).format('YYYY-MM-DD')} ${moment(obj.PATROL_STARTTIME).format('HH:mm:ss')}`,
            PATROL_ENDTIME: `${moment(obj.PATROL_DATE).format('YYYY-MM-DD')} ${moment(obj.PATROL_ENDTIME).format('HH:mm:ss')}`,
            STAFF_ID: userInfoDetail.ID,
            STAFF_NAME: userInfoDetail.Name,
            OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            PATROL_TYPE: pageDataType || 1000,
            PATROL_STATE: 1000,
            PATROLDETAILList: list
        }
        console.log('reqreq', req);

        if (req.PATROLDETAILList && req.PATROLDETAILList.length > 0) {
            // 只要有一个子集就是 true
            let isOk: boolean = false
            req.PATROLDETAILList.forEach((item: any) => {
                if (item.PATROLCONTENTList && item.PATROLCONTENTList.length > 0) {
                    isOk = true
                }
            })
            if (!isOk) {
                message.error('巡检内容数据未录入!')
                setSaveLoading(false)
                return
            }
        } else {
            message.error('巡检项目数据未录入!')
            setSaveLoading(false)
            return
        }

        let newReq: any = {
            name: "",
            value: encryptAES(JSON.stringify(req))
        }
        const data = await handleSynchroPATROL(newReq)
        setSaveLoading(false)
        if (data.Result_Code === 100) {
            message.success('同步成功!')

        } else {
            message.error(data.Result_Desc)
        }
        setSaveLoading(false)
    }

    // 根据区域获取到服务区列表
    const handleGetServerPartList = async (id: string) => {
        const req: any = {
            ProvinceCode: "530000",
            SPRegionType_ID: id
        }
        const data = await handleGetServerpartTree(req)
        if (data && data.length > 0) {
            let list = data[0].children
            setServerPartList(list)
        } else {
            setServerPartList([])
        }
    }

    // 拿到新增的巡检项目的内容 假保存的 
    const handleGetNewProjectData = async (formData: any) => {
        if (inspectionItemsTableData && inspectionItemsTableData.length > 0) {
            let list: any = JSON.parse(JSON.stringify(inspectionItemsTableData))
            list.push({
                ...formData,
                rowIndex: inspectionItemsTableData.length + 1,
                STAFF_ID: userInfoDetail.ID,
                STAFF_NAME: userInfoDetail.Name,
                OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
            })
            setInspectionItemsTableData(list)
        } else {
            let list: any = [{ ...formData, rowIndex: 1 }]
            setSelectedRowKey(`${formData?.PATROL_ID}-1`);
            setInspectionItemsTableData(list)
        }

        setShowInspectionItemsModal(false)
    }

    // 拿到添加巡检内容 悬浮框里面的内容
    const handleAddInspectionContentData = async (formData: any) => {
        let obj: any = {}
        if (inspectionItemObj) {
            obj = JSON.parse(JSON.stringify(inspectionItemObj))
        }
        let list: any = []
        if (inspectionItemObj && inspectionItemObj[selectedRowKey] && inspectionItemObj[selectedRowKey].length > 0) {
            list = JSON.parse(JSON.stringify(inspectionItemObj[selectedRowKey]))
        }

        if (list && list.length > 0) {
            list.push({ ...formData, rowId: selectedRowKey })
        } else {
            list = [{ ...formData, rowId: selectedRowKey }]
        }
        obj[selectedRowKey] = list

        setInspectionItemObj(obj)
        setInspectionContentList(list)
    }

    // 根据传入的行号 切换显示的巡检内容
    const handleChangeContentList = async (id: string) => {
        let list: any = []
        if (inspectionItemObj && inspectionItemObj[id] && inspectionItemObj[id].length > 0) {
            list = inspectionItemObj[id]
        }
        setInspectionContentList(list)

        // 现场照片内容
        let photoList: any = []
        if (inspectionItemPhoto && inspectionItemPhoto[id] && inspectionItemPhoto[id].length > 0) {
            photoList = inspectionItemPhoto[id]
        }
        setFileList(photoList)
    }

    // 拿到整改情况的录入数据
    const handleGetRectificationStatusData = async (formData: any) => {
        const req: any = {
            ...formData,
            PATROL_ID: PATROLID,
            STAFF_ID: userInfoDetail.ID,
            STAFF_NAME: userInfoDetail.Name,
            OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss'),
        }
        let newReq: any = {
            name: "",
            value: encryptAES(JSON.stringify(req))
        }

        const data = await handleSynchroRECTIFICATION(newReq)
        if (data.Result_Code === 100) {
            message.success('同步成功!')

        } else {
            message.error(data.Result_Desc)
        }
        setRectificationStatusModal(false)
    }

    // 获取到服务区方位的方法
    const handleGetSERVERPARTREGION = async (id: string) => {
        setSERVERPARTREGION([])
        const req: any = {
            SERVERPARTId: id
        }
        const data = await handleGetServerpartInfo(req)
        let list: any = []
        if (data.RegionInfo && data.RegionInfo.length > 0) {
            data.RegionInfo.forEach((item: any) => {
                list.push({ label: item.SERVERPART_REGIONNAME, value: item.SERVERPART_REGION })
            })
        }

        setSERVERPARTREGION(list)
    }


    return (
        <div className="operationReportMain">
            <div className="pageTitle">
                <div className="pageTitleLeft"></div>
                <div className="pageTitleCenter">{`${pageDataType === 3000 ? '现场巡检' : '日常巡检'}${PATROLID ? '详情' : '录入'}`}</div>
                <div className="pageTitleRight">
                    {
                        PATROLID ? '' :
                            <Button type={'primary'} loading={saveLoading} onClick={() => {
                                formRef.current?.validateFields().then((res: any) => {
                                    if (saveLoading) {
                                        return
                                    }

                                    setSaveLoading(true)
                                    handleAddUpdate(res)
                                })
                            }}>保存</Button>
                    }

                </div>
            </div>
            <ProForm
                formRef={formRef}
                submitter={false}
                layout={'horizontal'}
                labelCol={{ style: { width: 120 } }}
                request={async () => {
                    // 地址栏传参    UserIdEncrypted 为当前登录用户的加密id
                    const search = window.location.search;
                    const addressParams = Object.fromEntries(new URLSearchParams(search).entries());
                    const req: any = {
                        UserIdEncrypted: addressParams.UserIdEncrypted
                    }
                    const userInfo = await handleGetPassportInfoById(req)
                    setUserInfoDetail(userInfo)

                    if (addressParams.dataType) {
                        setPageDataType(Number(addressParams.dataType))
                    }

                    if (PATROLID) {
                        const req: any = {
                            SearchParameter: {
                                PATROL_IDS: PATROLID
                            },
                            PageIndex: 1,
                            PageSize: 100,
                        }
                        let newReq: any = {
                            name: "",
                            value: encryptAES(JSON.stringify(req))
                        }
                        const data = await handleGetPATROLList(newReq)

                        if (data && data.length > 0) {
                            let detail: any = data[0]

                            setCurrentRecord(detail)
                            if (detail.PATROLDETAILList && detail.PATROLDETAILList.length > 0) {
                                let list: any = detail.PATROLDETAILList
                                setInspectionItemsTableData(list)

                                console.log('listlistlist', list);

                                let obj: any = {}
                                let photoObj: any = {}
                                list.forEach((item: any, index: number) => {
                                    obj[`${item?.PATROL_ID}-${item?.rowIndex || item?.PATROLDETAIL_ID}`] = item.PATROLCONTENTList
                                    let photoList: any = item.ONSITEPHOTO_URL ? item.ONSITEPHOTO_URL.split(',') : []
                                    let list: any = []
                                    if (photoList && photoList.length > 0) {
                                        photoList.forEach((item: any, index: number) => {
                                            list.push({
                                                url: item,
                                                uid: index
                                            })
                                        })
                                    }
                                    photoObj[`${item?.PATROL_ID}-${item?.rowIndex || item?.PATROLDETAIL_ID}`] = list
                                })


                                setInspectionItemPhoto(photoObj)
                                setInspectionItemObj(obj)
                                setInspectionContentList(obj[`${list[0].PATROL_ID}-${list[0].rowIndex || list[0].PATROLDETAIL_ID}`])
                                setSelectedRowKey(`${list[0].PATROL_ID}-${list[0].rowIndex || list[0].PATROLDETAIL_ID}`);
                                setFileList(photoObj[`${list[0].PATROL_ID}-${list[0].rowIndex || list[0].PATROLDETAIL_ID}`])
                            }

                            handleGetServerPartList(detail.SPREGIONTYPE_ID)

                            handleGetSERVERPARTREGION(detail.SERVERPART_ID)
                            return {
                                ...detail,
                                SERVERPART_REGION: Number(detail.SERVERPART_REGION)
                            }
                        }



                    } else {
                        return {
                            STAFF_NAME: userInfo.Name,
                            OPERATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
                        }
                    }
                }}
            >
                <Row gutter={8}>
                    <Col span={24}>
                        <ProFormText
                            label={'任务标题'}
                            name={'PATROL_TITLE'}
                            rules={[{
                                required: true,
                                message: '请输入任务标题!'
                            }]}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>

                    <Col span={8}>
                        <ProFormSelect
                            label={'所属片区'}
                            name={'SPREGIONTYPE_ID'}
                            request={async () => {
                                const req: any = {
                                    SearchParameter: {
                                        SERVERPARTSTATICTYPE_ID: 1000,
                                        TYPE_STATE: 1,
                                        PROVINCE_CODE: 530000
                                    },
                                    PageIndex: 1,
                                    PageSize: 100,
                                    SortStr: "TYPE_INDEX,SERVERPARTTYPE_ID"
                                }
                                const data = await handleGetSERVERPARTTYPEList(req)
                                let list: any = []
                                if (data && data.length > 0) {
                                    data.forEach((item: any) => {
                                        list.push({ label: item.TYPE_NAME, value: item.SERVERPARTTYPE_ID })
                                    })
                                }
                                return list
                            }}
                            fieldProps={{
                                showSearch: true,
                                filterOption: (input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
                                optionFilterProp: 'label',
                                onChange: (value: any, option: any) => {
                                    handleGetServerPartList(value)
                                    if (value) {
                                        formRef.current?.setFieldsValue({ SPREGIONTYPE_NAME: option.label })
                                    } else {
                                        formRef.current?.setFieldsValue({ SPREGIONTYPE_NAME: "" })
                                    }
                                }
                            }}
                            rules={[{
                                required: true,
                                message: '请选择所属片区!'
                            }]}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>
                    <Col span={8} style={{ display: 'none' }}>
                        <ProFormText
                            label={'片区名称'}
                            name={'SPREGIONTYPE_NAME'}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>
                    <Col span={8}>
                        <ProFormSelect
                            label={'服务区'}
                            name={'SERVERPART_ID'}
                            rules={[{
                                required: true,
                                message: '请选择服务区!'
                            }]}
                            options={serverPartList}
                            fieldProps={{
                                onChange: (e: any, option: any) => {
                                    handleGetSERVERPARTREGION(e)
                                    if (e) {
                                        formRef.current?.setFieldsValue({ SERVERPART_NAME: option.label })
                                    } else {
                                        formRef.current?.setFieldsValue({ SERVERPART_NAME: "" })
                                    }
                                }
                            }}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>
                    <Col span={8} style={{ display: 'none' }}>
                        <ProFormText
                            label={'服务区名称'}
                            name={'SERVERPART_NAME'}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>
                    <Col span={8}>
                        <ProFormSelect
                            label={'服务区方位'}
                            name={'SERVERPART_REGION'}
                            rules={[{
                                required: true,
                                message: '请选择服务区方位!'
                            }]}
                            options={SERVERPARTREGION}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>

                    <Col span={8}>
                        <ProFormDatePicker
                            label={'巡检日期'}
                            name={'PATROL_DATE'}
                            width={'100%'}
                            rules={[{
                                required: true,
                                message: '请选择巡检日期!'
                            }]}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>

                    <Col span={8}>
                        <ProFormTimePicker
                            label={'开始时间'}
                            name={'PATROL_STARTTIME'}
                            width={'100%'}
                            rules={[{
                                required: true,
                                message: '请选择开始时间!'
                            }]}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>
                    <Col span={8}>
                        <ProFormTimePicker
                            label={'结束时间'}
                            name={'PATROL_ENDTIME'}
                            width={'100%'}
                            rules={[{
                                required: true,
                                message: '请选择结束时间!'
                            }]}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>
                    <Col span={8}>
                        <ProFormDatePicker
                            label={'发布时间'}
                            name={'发布时间'}
                            width={'100%'}
                            rules={[{
                                required: true,
                                message: '请选择发布时间!'
                            }]}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>

                    <Col span={8}>
                        <ProFormText
                            label={'创建人'}
                            name={'STAFF_NAME'}
                            disabled
                            readonly={PATROLID ? true : false}
                        />
                    </Col>
                    <Col span={8}>
                        <ProFormText
                            label={'创建时间'}
                            name={'OPERATE_DATE'}
                            disabled
                            readonly={PATROLID ? true : false}
                        />
                    </Col>
                    <Col span={8}>
                        <ProFormSelect
                            label={'状态'}
                            name={'COMPLETE_STATE'}
                            options={[
                                { label: "编辑中", value: 1 },
                                { label: "巡查中", value: 2 },
                                { label: "待跟进", value: 3 },
                                { label: "整改中", value: 4 },
                                { label: "已完成", value: 5 },
                            ]}
                            initialValue={1}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>


                    <Col span={8}>
                        <ProFormText
                            label={'检查人'}
                            name={'PATROL_PERSON'}
                            readonly={PATROLID ? true : false}
                        />
                    </Col>

                    {
                        pageDataType === 3000 ?
                            <Col span={8}>
                                <ProFormDatePicker
                                    label={'要求整改时间'}
                                    name={'TILLTIME'}
                                    width={'100%'}
                                />
                            </Col> :
                            <>
                                <Col span={8}>
                                    <ProFormTimePicker
                                        label={'巡检开始时间'}
                                        name={'INSPECTION_STARTTIME'}
                                        width={'100%'}
                                        readonly={PATROLID ? true : false}
                                    />
                                </Col>
                                <Col span={8}>
                                    <ProFormTimePicker
                                        label={'巡检结束时间'}
                                        name={'INSPECTION_ENDTIME'}
                                        width={'100%'}
                                        readonly={PATROLID ? true : false}
                                    />
                                </Col>
                            </>
                    }
                </Row>
            </ProForm>

            {fileList && fileList.length > 0 && <div style={{ display: 'none' }}>
                <Image.PreviewGroup
                    preview={{
                        visible: imagePreviewVisible,
                        onVisibleChange: vis => {
                            setImagePreviewVisible(vis)
                        }

                    }}>
                    {
                        fileList.map((n) =>
                            <Image src={n.url} key={n.url} />
                        )
                    }

                </Image.PreviewGroup>
            </div>}

            {/* 非表单内容 */}
            <Row gutter={8}>
                <Col span={12}>
                    <Divider className="inspectionItemsTitle" orientation="left">巡检项目</Divider>
                    <div className="leftItem">
                        <ProTable
                            actionRef={actionRef}
                            rowKey={(record: any) => {
                                return `${record?.PATROL_ID}-${record?.rowIndex || record?.PATROLDETAIL_ID}`
                            }}
                            search={PATROLID ? false : {}}
                            options={false}
                            columns={columns}
                            bordered
                            scroll={{ x: "100%", y: 230 }}
                            dataSource={inspectionItemsTableData}
                            onRow={(record) => ({
                                onClick: () => {
                                    setSelectedRowKey(`${record?.PATROL_ID}-${record?.rowIndex || record?.PATROLDETAIL_ID}`);
                                    handleChangeContentList(`${record?.PATROL_ID}-${record?.rowIndex || record?.PATROLDETAIL_ID}`)
                                },
                            })}
                            className="leftItemProTable"
                            rowClassName={(record) => (`${record?.PATROL_ID}-${record?.rowIndex || record?.PATROLDETAIL_ID}` === selectedRowKey ? 'ant-table-row-selected' : '')}
                            toolbar={{
                                actions: PATROLID ? [] : [
                                    <Button
                                        key="new"
                                        type="primary"
                                        onClick={(e) => {
                                            setShowInspectionItemsModal(true)
                                        }}
                                    >
                                        添加巡检项目
                                    </Button>
                                ]
                            }}
                        />
                    </div>
                </Col>
                <Col span={12}>
                    <Divider className="inspectionItemsTitle" orientation="left">巡检内容</Divider>

                    <div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
                        {
                            selectedRowKey ?
                                PATROLID ? '' :
                                    <Button type={'primary'} onClick={() => {
                                        setAddContentModal(true)
                                    }}>添加巡检内容</Button> : ""
                        }
                    </div>

                    <div className="inspectionContentListBox">
                        {
                            inspectionContentList && inspectionContentList.length > 0 ?
                                inspectionContentList.map((item: any) => {
                                    return <div className="inspectionContentItem">
                                        <div className="inspectionContentItemLeft">
                                            <img className="inspectionContentItemIcon" src={item.EXCEPTION_CONTENT ? errorIcon : normalIcon} />
                                        </div>
                                        <div className="inspectionContentItemCenter">
                                            <div className="inspectionContentText">{item?.PATROLDETAIL_CONTENT || ""}</div>
                                            {
                                                item.EXCEPTION_CONTENT ?
                                                    <div className="errorContentTextBox">
                                                        <div className="errorContentTitle">异常描述:</div>
                                                        <div className="errorContentText">{item?.EXCEPTION_CONTENT || ""}</div>
                                                        <div className="errorContentImgList">
                                                            <Image.PreviewGroup>
                                                                {item.EXCEPTIONPHOTO_URL &&
                                                                    item.EXCEPTIONPHOTO_URL.split(',').map((url: string, index: number) => (
                                                                        <Image
                                                                            key={index}
                                                                            src={url}
                                                                            className="errorContentImg"
                                                                            width={80}         // 你自己的缩略图尺寸
                                                                            height={80}
                                                                            style={{ objectFit: 'cover', borderRadius: 6, marginRight: '10px' }}
                                                                            preview={{ mask: '预览' }}  // 鼠标移入显示遮罩 + "预览" 文案
                                                                        />
                                                                    ))}
                                                            </Image.PreviewGroup>
                                                        </div>
                                                    </div> : ""
                                            }
                                        </div>

                                        <div className="inspectionContentItemRight">
                                            {
                                                item.EXCEPTION_CONTENT ?
                                                    <div className="btnText" onClick={() => {
                                                        setCurrentRectification(item)
                                                        setRectificationStatusModal(true)
                                                    }}>整改情况</div> : ""
                                            }
                                        </div>
                                    </div>
                                }) : ""
                        }
                        {
                            selectedRowKey ?
                                <div className="inspectionContentItem" style={{ borderBottom: '0px dashed #dadada' }}>
                                    <div className="inspectionContentItemCenter">
                                        <ProFormUploadButton
                                            label={"现场照片"}
                                            name={"LOCALEPHOTO"}
                                            fileList={fileList}
                                            listType="picture-card"
                                            accept="image/*"
                                            fieldProps={{
                                                beforeUpload,
                                                maxCount: 9,
                                                onPreview: handlePreview,
                                                customRequest: async (info) => {
                                                    const formData = new FormData();
                                                    formData.append('files', info.file);
                                                    formData.append('TableType', '1208');
                                                    formData.append('ImageName', typeof info.file !== 'string' ? info.file?.name : '');
                                                    if (info.filename) {
                                                        const success = await uploadAHYDPicture(formData)

                                                        if (success) {
                                                            let list: any = []
                                                            if (fileList && fileList.length > 0) {
                                                                list = JSON.parse(JSON.stringify(fileList))
                                                            }
                                                            list.push({
                                                                name: success.Result_Data.ImageName,
                                                                url: success.Result_Data.ImageUrl, // url 是展示在页面上的绝对链接
                                                            })
                                                            if (selectedRowKey) {
                                                                let obj: any = inspectionItemPhoto ? JSON.parse(JSON.stringify(inspectionItemPhoto)) : {}

                                                                let newList: any = list

                                                                obj[selectedRowKey] = newList
                                                                setInspectionItemPhoto(obj)
                                                            }
                                                            setFileList(list)
                                                        }
                                                    } else {
                                                        message.error("您上传的图片不存在.")
                                                    }
                                                },
                                                onChange: async (info: any) => {
                                                    if (info.file.status === 'removed') {
                                                        confirm({
                                                            title: '确认删除该图片吗？',
                                                            icon: <ExclamationCircleOutlined rev={undefined} />,
                                                            async onOk() {
                                                                let list: any = JSON.parse(JSON.stringify(fileList))
                                                                let res: any = []
                                                                if (list && list.length > 0) {
                                                                    list.forEach((item: any) => {
                                                                        if (item.url === info.file.url) {

                                                                        } else {
                                                                            res.push(item)
                                                                        }
                                                                    })
                                                                }
                                                                setFileList(res)

                                                                if (selectedRowKey) {
                                                                    let obj: any = inspectionItemPhoto ? JSON.parse(JSON.stringify(inspectionItemPhoto)) : {}
                                                                    obj[selectedRowKey] = res
                                                                    setInspectionItemPhoto(obj)
                                                                }
                                                            }
                                                        });
                                                    }
                                                }
                                            }}
                                            disabled={PATROLID ? true : false}
                                        />
                                    </div>
                                </div>
                                : ""
                        }
                    </div>
                </Col>
            </Row>



            {/* 添加巡检项目 */}
            <AddInspectionItems onRef={AddInspectionItemsRef} onShow={showInspectionItemsModal} setOnShow={setShowInspectionItemsModal} handleGetNewProjectData={handleGetNewProjectData} pageDataType={pageDataType} />

            {/* 添加巡检内容的悬浮框 */}
            <AddInspectionContent onRef={AddInspectionContentRef} onShow={addContentModal} setOnShow={setAddContentModal} handleAddInspectionContentData={handleAddInspectionContentData} />

            {/* 整改情况 的录入悬浮框 */}
            <RectificationStatusInfoModal currentRowInfo={currentRectification} parentRow={currentRecord} onShow={rectificationStatusModal} setOnShow={setRectificationStatusModal} handleGetRectificationStatusData={handleGetRectificationStatusData} />
        </div>

    )
}


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