import { Button, Col, Form, InputNumber, Modal, Radio, Row } from "antd";
import React, { useEffect, useState } from "react";
import Cropper from "react-cropper";
import "cropperjs/dist/cropper.css";
import { RcFile } from "antd/lib/upload";
import { dataURLtoFile } from "@/utils/compress";

interface Props {
    file?: RcFile,
    visible?: boolean,
    onChange?: (fileList: any[], file: any) => void,
    onClose?: () => void
}
/**
 * 新投放素材剪切
 * @param props 
 */
const CropperImg: React.FC<Props> = (props) => {

    /**====================== */
    const { file, visible, onChange, onClose } = props
    const [image, setImage] = useState(''); //初始图片
    const [cropper, setCropper] = useState<any>();//实例
    const [type, setType] = useState<number>(6)
    const [dragMode] = useState<'none' | 'crop' | 'move'>('none')
    const [imgSize, setImageSize] = useState<{ width: number, height: number }>({ width: 0, height: 0 })
    const [detail, setDetail] = useState<{ width: number, height: number, rotate: number }>({ width: 0, height: 0, rotate: 0 }); //设置数据
    /**====================== */

    /** 获取宽高 image */
    useEffect(() => {
        if (file) {
            let img: any = new Image();
            let _URL = window.URL || window.webkitURL;
            img.onload = function (e: any) {
                const reader = new FileReader();
                setDetail({ ...detail, width: this.width, height: this.height })
                setImageSize({ width: this.width, height: this.height })
                reader.onload = async () => {
                    setImage(reader.result as any);
                }
                reader.readAsDataURL(file);
            }
            img.src = _URL.createObjectURL(file);
        }
    }, [])

    /**数值变化重置实例 */
    useEffect(() => {
        if (typeof cropper !== "undefined") {
            setTimeout(() => {
                cropper.setData(detail);
            }, 300)
        }
    }, [cropper, detail]);

    /** 初始化 */
    useEffect(() => {
        if (visible && cropper) {
            setTimeout(() => {
                cropper.reset()
            }, 200)
        }
    }, [visible, cropper])

    /** 处理宽高 */
    useEffect(() => {
        switch (type) {
            case 1:
                setDetail({ ...detail, width: 800, height: 800 })
                break
            case 2:
                setDetail({ ...detail, width: 800, height: 640 })
                break
            case 3:
                setDetail({ ...detail, width: 800, height: 450 })
                break
            case 4:
                setDetail({ ...detail, width: 750, height: 800 })
                break
            case 5:
                setDetail({ ...detail, width: 640, height: 800 })
                break
            case 6:

                break
        }
    }, [type])

    /**关闭 */
    const cancel = () => {
        onClose && onClose()
        setCropper(undefined)
        setImage('')
    }

    const getCropData = async () => {
        if (typeof cropper !== "undefined") {
            let newFile = await dataURLtoFile(cropper.getCroppedCanvas().toDataURL('image/jpeg'), file?.name)
            onChange?.([{
                lastModified: newFile.lastModified,
                // lastModifiedDate: newFile.lastModifiedDate,
                name: newFile.name,
                percent: 0,
                size: newFile.size,
                thumbUrl: cropper.getCroppedCanvas().toDataURL('image/jpeg'),
                type: newFile.type,
                // uid: newFile.uid,
                originFileObj: newFile
            }], newFile)
            // setCropper(undefined)
            // setImage('')
        }
    }

    return <Modal
        open={visible}
        onCancel={cancel}
        width={1000}
        footer={<div style={{ display: 'flex', justifyContent: 'center' }}>
            <Button onClick={cancel}>取消</Button>
            <Button type='primary' onClick={getCropData}>确定</Button>
        </div>}
    >
        <div>
            <div style={{ width: "100%" }}>
                <Row>
                    <Col span={16}>
                        <Cropper
                            style={{ height: 450, width: 600, backgroundImage: `url(${require('../../../../../public/init.png')})`, border: '1px solid #efefef' }}
                            zoomTo={0.6}
                            initialAspectRatio={1}
                            preview=".img-preview"
                            src={image}
                            viewMode={1}
                            dragMode={dragMode} // 'crop' 重新设置裁剪框大小 'move' 移动画布
                            guides={true}
                            rotatable={true}
                            minCropBoxHeight={10}
                            minCropBoxWidth={10}
                            background={false}
                            responsive={true}
                            autoCropArea={1}
                            cropBoxResizable={false}
                            zoomable={false} // 图片缩放
                            movable={false} // 图片移动控制
                            onInitialized={(instance: any) => {
                                console.log('instance--->', instance)
                                setCropper(instance);
                            }}
                            crop={() => { }}
                        />
                    </Col>
                    <Col span={8}>
                        <Row gutter={[10, 10]}>
                            <Col span={24} style={{ height: 275 }}>
                                <div className="box" style={{ width: "100%", float: "right", overflow: 'hidden' }}>
                                    <h1>Preview</h1>
                                    <div
                                        className="img-preview"
                                        style={{ width: "100%", float: "left", height: "200px", overflow: 'hidden' }}
                                    />
                                </div>
                            </Col>
                            <Col>
                                <Radio.Group onChange={(e) => { setType(e.target.value) }} value={type} style={{ marginBottom: 20, }}>
                                    <Radio value={1} disabled={800 > imgSize.width || 800 > imgSize.height}>800*800</Radio>
                                    <Radio value={2} disabled={800 > imgSize.width || 640 > imgSize.height}>800*640</Radio>
                                    <Radio value={3} disabled={800 > imgSize.width || 450 > imgSize.height}>800*450</Radio>
                                    <Radio value={4} disabled={750 > imgSize.width}>{"750*<1536"}</Radio>
                                    <Radio value={5} disabled={640 > imgSize.width || 800 > imgSize.height}>640*800</Radio>
                                    <Radio value={6}>自定义</Radio>
                                </Radio.Group>
                                <Form>
                                    {type === 6 && <Form.Item label="裁剪框宽" style={{ marginBottom: 10 }}>
                                        <InputNumber
                                            style={{ width: 200 }}
                                            value={detail.width}
                                            min={1}
                                            onChange={(e) => { setDetail({ ...detail, width: e || 0 }) }}
                                        />
                                    </Form.Item>}

                                    {(type === 6 || type === 4) && <Form.Item label="裁剪框高" style={{ marginBottom: 0 }}>
                                        <InputNumber
                                            style={{ width: 200 }}
                                            value={detail.height}
                                            min={1}
                                            max={imgSize.height}
                                            onChange={(e) => { setDetail({ ...detail, height: e || 0 }) }}
                                        />
                                    </Form.Item>}

                                </Form>

                            </Col>
                        </Row>
                    </Col>
                </Row>
            </div>
        </div>
    </Modal>
}

export default React.memo(CropperImg)