import React, { useEffect, memo, useState } from 'react';
import { View, TextField, Button, Text, Picker, Colors, DateTimePicker } from 'react-native-ui-lib'
import { useForm, Controller } from "react-hook-form";
import _ from 'lodash';
import { useAsyncEffect } from "ahooks";
import AntdIcons from 'react-native-vector-icons/AntDesign';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import moment from 'moment';
import ImagePicker from '../ImagePicker';
import ListPicker from '../ListPicker';
import Buttonloading from "../Buttonloading";


let ControlDom = ({ children, it, value, title, control, required, errors, column }) => (
    <View bg-white paddingH-12>
        <View row spread centerHkey={it} style={{ overflow: "hidden", height: 50, borderBottomColor: "#f0f0f0", borderBottomWidth: 1 }}>
            <View row center paddingR-12>
                {(errors[it]) && <AntdIcons name={'exclamationcircle'} size={12} style={{ marginRight: 4, color: "red" }}></AntdIcons>}
                {(required) && <FontAwesome5 name={'star-of-life'} size={6} style={{ marginRight: 4, color: "red" }}></FontAwesome5>}
                <Text subbody>
                    {title}
                </Text>
            </View>
            <View right bg-grey90 flex-1 >
                {
                    column ?
                        column() :
                        <Controller
                            control={control}
                            rules={{
                                required,
                            }}
                            render={({ field: { onChange, onBlur, value } }) => React.cloneElement(children, { onChange, onBlur, value })}
                            name={it}
                        />
                }

            </View>
        </View>
        {
            column ? <Controller
                control={control}
                rules={{
                    required,
                }}
                render={({ field: { onChange, onBlur, value } }) => React.cloneElement(children, { onChange, onBlur, value })}
                name={it}
            /> : null
        }
    </View>
), RenderInput = ({ onChange, onBlur, value, item }) => (
    <TextField
        style={{ textAlign: "right", height: 30, marginTop: 10 }}
        placeholder="请输入"
        onBlur={onBlur}
        secureTextEntry={item?.type == "password"}
        onChangeText={onChange}
        value={value}
    />
), RenderSelect = ({ onChange, onBlur, value, item, setValue, setigger, option }) => (
    <Picker
        placeholder="请选择"
        value={value}
        enableModalBlur={false}
        onChange={(val) => {
            if (item?.linked) {
                item?.linked.map(name => {
                    setValue(name, null, {
                        shouldValidate: true,
                        shouldDirty: true
                    })
                });
                setigger(new Date().getTime())
            }
            onChange(val)
        }}
        topBarProps={{ title: item?.title ?? "标题", doneLabel: "保存" }}
        style={{ marginTop: 10 }}
        showSearch
        searchPlaceholder={'请选择'}
        mode={item?.multiple ? Picker.modes.MULTI : null}
        searchStyle={{ color: Colors.blue30, placeholderTextColor: Colors.grey50 }}
    // onSearchChange={value => console.warn('value', value)}
    >
        {_.map(option[item?.name[0]], cur => (
            <Picker.Item key={cur?.value} value={cur} label={cur?.label} disabled={cur?.disabled} />
        ))}
    </Picker>
), RenderDatePicker = ({ onChange, onBlur, value, item, setValue, setigger, option }) => {
    let format = item?.showTime ? {
        timeFormat: item?.format,
    } : {
            dateFormat: item?.format,
        }

    return (
        <DateTimePicker
            onChange={onChange}
            value={value}
            style={{ marginTop: 10 }}
            placeholder="请选择"
            mode={item?.showTime ? "time" : "date"}
            {...format}
        >
        </DateTimePicker>
    )
}, RenderImagePicker = ({ onChange, onBlur, value, item, setValue, setigger, option }) => (
    <ImagePicker
        onChange={onChange}
        value={value}
        item={item}
    >
    </ImagePicker>
), RenderList = memo(({ onChange, onBlur, value, item, setValue, setigger, option }) => {
    let alldata = item?.dataSource ? item?.dataSource.map(it => ({
        id: it.id
    })) : []
    let newColumns = item?.columns.map(it => {
        if (it?.submittype) {
            return {
                ...it,
                render: (cur, row) => {
                    let judge = it.judge ?? [], //判断规则
                        ifs = row[it?.submittype],//判断条件
                        curtype = judge.filter(it => it?.val == ifs)[0];//当前规则

                    let { key, type } = curtype ?? {};//结构结果


                    let newvalue = value ?? alldata,//初始化idlist
                        curval = newvalue.filter(it => it.id == row.id)[0];//当前行val
                    curval = curval ?? {};
                    // console.log(newvalue,444);
                    // console.log(item?.dataSource,222);
                    // console.log(alldata,333);
                    

                    if (type == "select") {
                        return <View height={20}>
                            <Picker
                                placeholder="请选择"
                                topBarProps={{ title: curval[key] ?? "请选择", doneLabel: "保存" }}
                                style={{ textAlign: "right", height: 20, marginTop: 0 }}
                                value={typeof (curval[key]) == "object" ? curval[key] : {
                                    value: curval[key],
                                    label: it?.options?.filter(it => it.value == curval[key]).length > 0 ? it?.options?.filter(it => it.value == curval[key])[0]?.label : ""
                                }}
                                onChange={(val) => {
                                    let changeval = newvalue.map(it => {
                                        // console.log(it);
                                        
                                        if (it.id == row.id) {
                                            return {
                                                ...it,
                                                [key]: val
                                            }
                                        } else {
                                            return {
                                                ...it
                                            }
                                        }
                                    });
                                    // console.log(changeval,111);

                                    onChange(changeval)
                                }}
                            >
                                {_.map(it?.options ?? [], item => (
                                    <Picker.Item key={item?.value} value={item} label={item?.label} disabled={item?.disabled} />
                                ))}
                            </Picker>
                        </View>
                    } else if (type == "input") {
                        return <View height={20}>
                            <TextField
                                keyboardType='numeric'
                                style={{ textAlign: "right", height: 20, marginTop: 0 }}
                                placeholder="请输入"
                                value={curval[key]}
                                onChangeText={(val) => {
                                    let changeval = newvalue.map(it => {
                                        if (it.id == row.id) {
                                            return {
                                                ...it,
                                                [key]: val
                                            }
                                        } else {
                                            return {
                                                ...it
                                            }
                                        }
                                    })
                                    onChange(changeval)
                                }}
                            />
                        </View>
                    }

                }
            }
        } else {
            return {
                ...it
            }
        }
    })

    return (
        <ListPicker
            onChange={onChange}
            value={value}
            item={item}
            columns={newColumns}
        >
        </ListPicker>
    )
})




let InitForm = ({
    fields,
    submit,
    submitLabel,
    loading
}) => {
    let {
        control,
        handleSubmit,
        formState: { errors },
        watch,
        setValue,
        getValues,
        reset
    } = useForm({
        defaultValues: {

        }
    }),
        [option, cop] = useState({}),
        [tigger, setigger] = useState();

    const onSubmit = (data) => {
        let resdata = {};
        for (let i in fields) {
            if (fields[i].type == "datepicker") {
                resdata[i] = data[i] ? moment(data[i]).format(fields[i].format) : null;
            } else if (fields[i].type == "select") {
                resdata[i] = data[i] ? data[i].value : null;
            } else {
                resdata[i] = data[i];
            }
        }
        submit && submit(resdata, reset)
    };
    async function setoptions(item) {
        let { options, belinked } = item;
        if (!options && !belinked) {
            return
        }

        if (Array.isArray(options)) {
            return options
        }

        if (options?.database) {
            let { database, params } = options,
                res = await database(params)
            return res?.data?.dataList;
        }

        if (belinked?.options) {
            let { database, params } = belinked.options, newparams = {};
            for (let i in params) {
                if (params[i] == 'linked') {
                    newparams[i] = getValues(i)?.value;
                } else {
                    newparams[i] = params[i];
                }
            }
            let res = await database({ ...newparams, key: item?.name[0] })
            return res?.data?.dataList;
        }
    }

    useAsyncEffect(async () => {
        for (let i in fields) {
            let resop = await setoptions(fields[i]);
            cop((cur) => ({
                ...cur,
                [i]: resop
            }))
            fields[i].value && setValue(i, fields[i].value);
        }
    }, [tigger])



    return <View style={{ borderRadius: 8, overflow: "hidden" }} bg-white>
        {
            Object.keys(fields).map((it) => {
                let item = fields[it];
                let { title, required, type, value, hides } = item,
                    controlprops = {
                        key: it,
                        it,
                        value,
                        title,
                        control,
                        required,
                        errors
                    }

                if (type == "input" || type == "password") {
                    if (hides) {
                        return
                    }
                    return <ControlDom {...controlprops}>
                        <RenderInput item={item}></RenderInput>
                    </ControlDom>
                } else if (type == "select") {
                    if (hides) {
                        return
                    }
                    return <ControlDom {...controlprops}>
                        <RenderSelect item={item} setValue={setValue} setigger={setigger} option={option}></RenderSelect>
                    </ControlDom>
                } else if (type == "datepicker") {
                    if (hides) {
                        return
                    }
                    return <ControlDom {...controlprops}>
                        <RenderDatePicker item={item}></RenderDatePicker>
                    </ControlDom>
                } else if (type == "upload") {
                    if (hides) {
                        return
                    }
                    return <ControlDom {...controlprops} column={() => {
                        let num = watch(it) ? watch(it).length : null
                        return <View center height={50}><Text
                            body
                            style={{ color: "#707070", fontSize: 16, paddingRight: 2 }}
                        >{num ? `已选择(${num + "/" + item?.limit})` : "请选择"}</Text></View>
                    }}>
                        <RenderImagePicker item={item}></RenderImagePicker>
                    </ControlDom>
                } else if (type == "list") {
                    if (hides) {
                        return
                    }
                    return <ControlDom {...controlprops} column={() => {
                        return <View center height={50}><Text
                            body
                            style={{ color: "#ccc", fontSize: 16, paddingRight: 2 }}
                        ></Text></View>
                    }}>
                        <RenderList item={item}></RenderList>
                    </ControlDom>
                }




            })
        }
        {
            !loading && <Button disabled={loading} backgroundColor={Colors.secondaryColor} borderRadius={8} marginT-23 title="Submit" onPress={handleSubmit(onSubmit)} label={submitLabel ?? "提交"} />
        }
        {
            loading && <Buttonloading style={{ marginTop: 23 }} />

        }


    </View>

}

export default InitForm
