import React, { useState, useEffect, useContext } from 'react';
import { Form, Row, Col, Tabs } from 'antd';
import ActiveField from '../ActiveField';
import { MyContext } from '../../utils/contextManage';
// @ts-ignore
import { modelFormDetailToBoolean } from "../../utils/common.js"
import { FormInstance } from 'antd/lib/form';

export interface GFormProps {
    [propsName: string]: any
}

const GForm: React.FC<GFormProps> = (props) => {
    console.log('GForm的props', props);
    const { tableRrn, formDetail, parentFormDetail, form: form, formType, layout, fieldData, fieldRefRule, adTableList }: {
        form?: FormInstance;
        [propsName: string]: any
    } = props
    const { state } = useContext(MyContext);
    let formInstance: any = form; // Form.useForm()[0]
    const [fieldList, setFieldList] = useState<any[]>([])
    const [referRuleInfo, setReferRuleInfo] = useState<any>({})
    const [fullFormContent, setFullFormContent] = useState<any>({})
    const [refValues, setRefValues] = useState<any>({})

    useEffect(() => {
        if (tableRrn) {
            getTableInfo()
        }
    }, [tableRrn])
    useEffect(() => {
        if (fieldData && fieldRefRule) {
            setFieldList(fieldData)
            setReferRuleInfo(fieldRefRule)
        }
    }, [fieldData, fieldRefRule])

    useEffect(() => {
        if (formDetail) {
            formInstance.resetFields()
            // formDetail里的'Y'和'N'转换成布尔值
            const newDetail = modelFormDetailToBoolean(formDetail)
            setFullFormContent(newDetail)
        }
    }, [formDetail])
    useEffect(() => {
        if (fullFormContent && refValues) {
            console.log('fullFormContent', { ...fullFormContent }, 'refValues', refValues);
            const mergeContent = { ...fullFormContent, ...refValues }
            console.log('更新表单的值', mergeContent);
            formInstance.setFieldsValue(mergeContent)
        }
    }, [fullFormContent, refValues])

    // 根据传入的tableRrn查询出动态表单的内容
    const getTableInfo = () => {
        const params = {
            ENTITYMODEL: state.entityModel,
            OBJECTRRN: `${tableRrn}`
        }
        state.getEntity(params)
            .then((res: any) => {
                if (res.Header.RESULT === 'SUCCESS') {
                    const tableInfo = res.Body.DATA
                    setFieldList(tableInfo.ADFIELDLIST)
                    // 获取子表单的级联信息 referRuleInfo
                    const obj = {} as any
                    tableInfo.ADFIELDLIST?.filter((x: any) => (!x.ISFROMPARENT) && x.REFERENCERULE && /[a-zA-Z0-9]+.[a-zA-Z0-9]+/g.test(x.REFERENCERULE))
                        .forEach((x: any) => {
                            const arr = x.REFERENCERULE.toUpperCase().split('.')
                            const key = arr[0]
                            const value = arr[1]
                            if (obj[key]) {
                                obj[key].push({ name: x.NAME, value })
                            } else {
                                obj[key] = [{ name: x.NAME, value }]
                            }
                        })
                    setReferRuleInfo(obj)
                    if (parentFormDetail) {
                        // console.log('父表单数据', parentFormDetail);
                        // 获取子表单中来源于父值的字段
                        const isFromParentList = tableInfo.ADFIELDLIST?.filter((item: any) => item.ISFROMPARENT && item.REFERENCERULE)
                        // console.log('需要从父表单取值的字段列表', isFromParentList);
                        isFromParentList.forEach((e: any) => {
                            const k = e.REFERENCERULE.toUpperCase()
                            const v = parentFormDetail[k]
                            formInstance.setFieldsValue({
                                [e.NAME.toUpperCase()]: v
                            })
                        })
                    }
                }
            })
            .catch((err: any) => {
                console.log('getTableInfo 请求失败，todo解锁加载中', err)
            })
    }
    // 搜索表单 / EditTable的添加、编辑表单
    const renderSearchForm = () => {
        // console.log('搜索/EditTable表单的fieldList', fieldList);
        return (
            fieldList.length > 0 ? fieldList.filter(x => x.ISDISPLAY).map((item: any) => {
                return <ActiveField
                    key={item.OBJECTRRN}
                    field={item}
                    referRuleInfo={referRuleInfo}
                    formDetail={fullFormContent}
                    formType={formType}
                    onChange={(val) => {
                        setRefValues({ ...val })
                    }}
                />
            }) : <div />
        )
    }
    // 基础信息 数据里有ISBASIC字段
    const renderBasicInfo = () => {
        const isZh = state.lang === 'zh-CN'
        const list = JSON.parse(JSON.stringify(fieldList))
            .filter((x: any) => x.ISBASIC && x.ISDISPLAY)
            .sort((a: any, b: any) => a.SEQNO - b.SEQNO) || []
        // console.log('动态编辑表单数据adfieldlist', list)
        return (
            list.length > 0 ?
                <>
                    {formType === 'form' ?
                        <div style={{
                            height: '30px',
                            fontWeight: 'bold',
                            borderBottom: '1px solid #e8e8e8',
                            marginBottom: '15px'
                        }}>{isZh ? '基本信息' : 'Basic Info'}
                        </div> : <div></div>}
                    <Row gutter={24}>
                        {list.map((item: any) => <Col span={24 / (props.GRIDYBASIC || 1)}>
                            <ActiveField
                                key={item.OBJECTRRN}
                                field={item}
                                referRuleInfo={referRuleInfo}
                                formDetail={fullFormContent}
                                formType="form"
                                onChange={(val) => {
                                    setRefValues({ ...val })
                                }} />
                        </Col>)}
                    </Row>
                </> : <div />)
    }
    // 动态选项卡， ISBASIC: false
    const renderTabs = () => {
        const isZh = state.lang === 'zh-CN'
        console.log('adTableList', adTableList)
        const tabList = adTableList.map((x: any, i: number) => {
            return (
                <Tabs.TabPane key={i} tab={isZh ? x.LABELZH : x.LABEL}>
                    <Row gutter={24}>
                        {x.ADFIELDLIST ? x.ADFIELDLIST.filter((field: any) => field.ISDISPLAY && !field.ISBASIC).map(
                            (item: any) => <Col span={24 / (x.GRIDY || 1)}>
                                <ActiveField
                                    key={item.OBJECTRRN}
                                    field={item}
                                    referRuleInfo={referRuleInfo}
                                    formDetail={fullFormContent}
                                    formType="form"
                                    onChange={(val) => {
                                        setRefValues({ ...val })
                                    }}
                                /></Col>
                        ) : null}
                    </Row>
                </Tabs.TabPane>
            )
        })
        return (
            <Tabs default-active-key={0}>
                {tabList}
                {/* 自定义添加tab*/}
                {props.renderAddCustomTabs && props.renderAddCustomTabs(fullFormContent)}
            </Tabs>
        )
    }

    return (
        <>
            {formInstance && <Form
                form={formInstance}
                layout={layout ? layout : 'horizontal'}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
                labelAlign="left"
                onFinish={(val: any) => {
                    console.log('formFinish', val)
                }}
                onValuesChange={(val: any, allvals) => {
                    console.log('onValuesChange', val, 'allvals', allvals);
                    setFullFormContent({ ...fullFormContent, ...allvals })
                }}
            >
                {(fieldList && fieldList.length > 0) ? ((formType === 'searchForm' || formType === 'addForm') ? renderSearchForm() : renderBasicInfo()) : null}
                {props.renderCustomTabs ? props.renderCustomTabs(fullFormContent) : (adTableList && adTableList.length > 0) ? renderTabs() : null}
            </Form>}
        </>
    )
}

export default GForm;