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

type DetailProps = {
    onRef: any,
    currentRowInfo: any,// 当前整改行数据
    onShow: boolean,
    setOnShow: (value: boolean) => void
    handleGetRectificationStatusData: any
    parentRow: 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 RectificationStatusInfoModal = ({ onRef, currentRowInfo, onShow, setOnShow, handleGetRectificationStatusData, parentRow }: DetailProps) => {
    const { confirm } = Modal;
    const RectificationStatusInfoFormRef = useRef<FormInstance>();
    // 文件列表
    const [fileList, setFileList] = useState<any>([])
    // 预览图片
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false)
    // 当前片区下的服务区列表
    const [serverPartList, setServerPartList] = useState<any>()

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

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

    return (
        <div>
            <Modal
                title={'整改情况'}
                destroyOnClose
                width={900}
                open={onShow}
                onCancel={() => {
                    setOnShow(false)
                }}
                onOk={async () => { // 提交框内的数据
                    RectificationStatusInfoFormRef.current?.validateFields().then((res: any) => {
                        if (handleGetRectificationStatusData) {
                            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,
                                LOCALEPHOTO: str
                            }
                            handleGetRectificationStatusData(obj)
                        }
                    })
                    setOnShow(false)
                }}
            >
                <ProForm
                    formRef={RectificationStatusInfoFormRef}
                    submitter={false}
                    layout={'horizontal'}
                    labelCol={{ style: { width: 80 } }}
                    request={async () => {
                        if (currentRowInfo) {
                            console.log('currentRowInfocurrentRowInfocurrentRowInfo', currentRowInfo);

                        } else if (parentRow) {
                            console.log('parentRowparentRowparentRow', parentRow);
                            handleGetServerPartList(parentRow?.belongAreaCode)
                            return {
                                SACode: parentRow?.SACode,
                                SAName: parentRow?.SAName,
                                belongAreaCode: parentRow?.belongAreaCode,
                                belongArea: parentRow?.belongArea,
                            }
                        } else {
                            return {

                            }
                        }
                    }}
                >
                    <Row gutter={8}>
                        <Col span={12}>
                            <ProFormSelect
                                label={'片区'}
                                name={'belongAreaCode'}
                                rules={[{ required: true, message: '请选择片区!' }]}
                                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)
                                    console.log('datadatadatadata', data);
                                    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) => {
                                        console.log('valuevalue', value);
                                        handleGetServerPartList(value)
                                        if (value) {
                                            RectificationStatusInfoFormRef.current?.setFieldsValue({ belongArea: option.label })
                                        } else {
                                            RectificationStatusInfoFormRef.current?.setFieldsValue({ belongArea: "" })
                                        }
                                    }
                                }}
                                disabled={parentRow}
                            />
                        </Col>
                        <Col span={12} style={{ display: 'none' }}>
                            <ProFormText
                                label={'片区名称'}
                                name={'belongArea'}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormSelect
                                label={'服务区'}
                                name={'SACode'}
                                options={serverPartList}
                                fieldProps={{
                                    onChange: (e: any, option: any) => {
                                        console.log('e', e);
                                        if (e) {
                                            RectificationStatusInfoFormRef.current?.setFieldsValue({ SAName: option.label })
                                        } else {
                                            RectificationStatusInfoFormRef.current?.setFieldsValue({ SAName: "" })
                                        }
                                    }
                                }}
                                rules={[{ required: true, message: '请选择服务区!' }]}
                                disabled={parentRow}
                            />
                        </Col>
                        <Col span={12} style={{ display: 'none' }}>
                            <ProFormText
                                label={'服务区名称'}
                                name={'SAName'}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                label={'责任单位'}
                                name={'DUTYUNIT'}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                label={'责任人'}
                                name={'DUTYPSNNAME'}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                label={'联系电话'}
                                name={'PHONE'}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormText
                                label={'巡检人'}
                                name={'INSPECTIONPSN'}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormDatePicker
                                label={'巡检日期'}
                                name={'INSPECTIONDATE'}
                                width={'100%'}
                            />
                        </Col>
                        <Col span={12}></Col>
                        <Col span={12}>
                            <ProFormTextArea
                                label={'巡检问题'}
                                name={'INSPECTIONQUESTION'}
                            />
                        </Col>
                        <Col span={12}>
                            <ProFormTextArea
                                label={'整改要求'}
                                name={'RECTIFICATIONREQUEST'}
                            />
                        </Col>
                        <Col span={24}>
                            <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)
                                            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>

                        <Col span={24}>
                            <ProFormTextArea
                                label={'整改结果'}
                                name={'RECTIFICATION_RESULT'}
                            />
                        </Col>
                    </Row>
                </ProForm>

            </Modal>
        </div>
    )
}



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