/** @format */

import * as React from 'react'
import {UploadChangeParam, RcFile} from 'antd/es/upload'
import {Form, Input, Spin, Button, Modal, Upload, Icon} from "antd"
import {FormComponentProps} from "antd/es/form"
import Axios from "../../../../utils/xhr"
import {SEARCH_GET_DATA} from "../../../../const/path"

import {message} from "antd"

const formItemLayout = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 12
    }
}

interface SearchTypeFormProps {
    onGetSearchData: any,
    searchInfoType: any
}

interface SearchKey {
    search_key: string,
    search_name: string,
    search_value: string,
    type: string
}


const SearchTypeItem: React.FC<FormComponentProps & SearchTypeFormProps> = props => {
    const {getFieldDecorator, validateFields} = props.form

    const [state, setState] = React.useState(() => {
        return {
            dialogVisible: false,
            confirmLoading: false
        }
    })

    const changeDialogVisible = () => {
        setState(() => ({...state, dialogVisible: !state.dialogVisible}))
    }

    const handConfirmData = () => {
        validateFields((errors, data) => {
            if (errors) {
                return
            }
            let keys: { search_key: string; search_value: any }[] = []
            Object.keys(data).forEach((key: string) => {
                keys.push({
                    search_key: key,
                    search_value: data[key]
                })
            })

            setState(prevState => ({...prevState, confirmLoading: true}))

            Axios({
                url: SEARCH_GET_DATA,
                method: "PUT",
                data: {
                    search_code: props.searchInfoType.search_code,
                    keys
                }
            }).then(({data, code, msg}) => {
                if (code) {
                    message.error(msg)
                    setState(prevState => ({...prevState, dialogVisible: true, confirmLoading: false}))
                    return
                }
                let {list, id} = data
                props.onGetSearchData && props.onGetSearchData({
                    id,
                    list,
                    searchCode: props.searchInfoType.search_code
                })

                setState(prevState => ({...prevState, dialogVisible: false, confirmLoading: false}))

            }).catch((err) => {
                setState(prevState => ({...prevState, dialogVisible: true, confirmLoading: false}))
            })
        })
    }

    const getBase64 = (img: any, callback: any) => {
        const reader = new FileReader()
        reader.addEventListener("load", () => callback(reader.result))
        reader.readAsDataURL(img)
    }


    const fileOnChange = (res: UploadChangeParam, search_key: string) => {
        getBase64(res.file, (imageBase64: string) => {
            props.form.setFieldsValue({
                [search_key]: imageBase64
            })
        })
    }

    const uploadButton = (
        <Button>
            <Icon type="plus"/> 选择照片
        </Button>
    )

    return (
        <>
            <Button onClick={changeDialogVisible}>{props.searchInfoType.search_name}</Button>

            <Modal title={props.searchInfoType.search_name}
                   onCancel={changeDialogVisible}
                   onOk={handConfirmData}
                   visible={state.dialogVisible}
                   confirmLoading={state.confirmLoading}>

                <Form {...formItemLayout}>
                    {props.searchInfoType.keys.map((item: SearchKey) => {

                        if (item.type === 'image_base64') {

                            return (
                                <Form.Item label={item.search_name}
                                           key={item.search_key}>
                                    <Upload onChange={(res) => {
                                        fileOnChange(res, item.search_key)
                                    }}
                                            listType="picture"
                                            showUploadList={false}
                                            beforeUpload={() => {
                                                return false
                                            }}
                                            multiple={false}>
                                        {props.form.getFieldValue(item.search_key) ?
                                            <img src={props.form.getFieldValue(item.search_key)} alt="avatar"
                                                 style={{maxHeight: '100px'}}/> : uploadButton}
                                    </Upload>

                                    {getFieldDecorator(item.search_key, {})(<Input style={{display: "none"}}/>)}
                                </Form.Item>
                            )
                        }

                        if (item.type === 'string') {
                            return (
                                <Form.Item label={item.search_name}
                                           key={item.search_key}>
                                    {getFieldDecorator(item.search_key, {})(<Input/>)}
                                </Form.Item>
                            )
                        }
                    })}
                </Form>
            </Modal>
        </>
    )
}

export default Form.create<FormComponentProps & SearchTypeFormProps>()(SearchTypeItem)
