// 同步检查项目的悬浮框 
import { uploadAHYDPicture } from "@/pages/serverpartAssets/service";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { ProForm, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea, ProFormTimePicker, ProFormUploadButton, ProFormUploadDragger } from "@ant-design/pro-components";
import { Col, FormInstance, message, Modal, Row } from "antd";
import { useRef, useState } from "react";
import { connect } from "umi";


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;
}

type DetailProps = {
    onRef: any,
    onShow: boolean,
    setOnShow: (value: boolean) => void
    handleAddInspectionContentData: (formRef: any) => void
}

const AddInspectionContent = ({ onRef, onShow, setOnShow, handleAddInspectionContentData }: DetailProps) => {
    const { confirm } = Modal;
    const AddInspectionContentFormRef = useRef<FormInstance>();

    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    // 预览图片
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false)

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

    return (
        <div>
            <Modal
                title={'同步检查内容'}
                destroyOnClose
                width={1200}
                open={onShow}
                onCancel={() => {
                    setOnShow(false)
                    setFileList([])
                }}
                onOk={async () => { // 提交框内的数据
                    AddInspectionContentFormRef.current?.validateFields().then((res: any) => {
                        if (handleAddInspectionContentData) {
                            let str: string = ''
                            if (fileList && fileList.length > 0) {
                                fileList.forEach((item: any) => {
                                    if (str) {
                                        str += `,${item.url}`
                                    } else {
                                        str = `${item.url}`
                                    }
                                })
                            }
                            let obj: any = {
                                ...res,
                                EXCEPTIONPHOTO_URL: str
                            }
                            handleAddInspectionContentData(obj)
                        }
                    })
                    setOnShow(false)
                    setFileList([])
                }}
            >
                <ProForm
                    formRef={AddInspectionContentFormRef}
                    submitter={false}
                    layout={'horizontal'}
                    labelCol={{ style: { width: 120 } }}
                >
                    <Row gutter={8}>
                        <Col span={24}>
                            <ProFormSelect
                                label={'内容类型'}
                                name={'PATROLCONTENT_TYPE'}
                                rules={[{ required: true, message: '请选择内容类型!' }]}
                                options={[
                                    { label: '服务质量监督', value: 1000 },
                                    { label: '运营维护', value: 2000 },
                                    { label: '安全管理', value: 3000 },
                                    { label: '通用', value: 4000 },
                                ]}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                label={'巡检内容'}
                                name={'PATROLDETAIL_CONTENT'}
                                rules={[{ required: true, message: '请输入巡检内容!' }]}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                label={'巡检结果'}
                                name={'PATROLDETAIL_RESULT'}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormTextArea
                                label={'异常描述'}
                                name={'EXCEPTION_CONTENT'}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormUploadButton
                                label={"异常图片"}
                                name={"EXCEPTIONPHOTO_URL"}
                                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)
                                            console.log('successsuccesssuccess', success);

                                            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 是展示在页面上的绝对链接
                                                })
                                                setFileList(list)
                                            }
                                        } else {
                                            message.error("您上传的图片不存在.")
                                        }
                                    },
                                    onChange: async (info: any) => {
                                        console.log('infoinfoinfo', info);

                                        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)
                                                }
                                            });
                                        }
                                    }
                                }}
                            />
                        </Col>

                    </Row>
                </ProForm>

            </Modal>
        </div>
    )
}



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