import React, { useState, useEffect, useContext } from 'react';
import { Input, Modal, Form, Button, Table } from 'antd';
import { SearchOutlined, RedoOutlined } from '@ant-design/icons';
import './index.less';
import { MyContext } from '../../utils/contextManage';
import ActiveField from '../ActiveField';
// @ts-ignore
import sqlUtil from '../../utils/sqlUtil'

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

const GSearch: React.FC<GSearchProps> = (props) => {
    console.log('GSearch组件的props', props)
    const { REFTABLERRN, formDetail, value, onChange } = props
    const { state } = useContext(MyContext);
    const [searchForm] = Form.useForm();
    const [options, setOptions] = useState<any>()
    const [dataListParams, setDataListParams] = useState<any>({})
    const [columns, setColumns] = useState<any>()
    const [fieldList, setFieldList] = useState<any[]>([])
    const [searchVisible, setSearchVisible] = useState<any>({
        creator: false
    });
    const [fullFormContent, setFullFormContent] = useState<any>({})
    useEffect(() => {
        searchForm.resetFields()
        searchForm.setFieldsValue(formDetail)
        setFullFormContent(formDetail)
    }, [formDetail])
    const [referRuleInfo, setReferRuleInfo] = useState<any>({})
    const [dataList, setDataList] = useState<any[]>([])
    const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const getRefTableInfo = () => {
        const params = {
            ENTITYMODEL: 'com.glory.framework.activeentity.model.ADRefTable',
            OBJECTRRN: REFTABLERRN
        }
        state.getEntity(params)
            .then((res: any) => {
                if (res.Header.RESULT === 'SUCCESS') {
                    console.log('REFTABLE信息', res.Body.DATA)
                    const refInfo = res.Body.DATA
                    setOptions({
                        value: refInfo.KEYFIELD.toUpperCase(),
                        LABEL: refInfo.TEXTFIELD.toUpperCase()
                    })
                    getTableInfo(refInfo)
                }
            })
            .catch((err: any) => {
                console.log('getRefTableInfo 请求失败，todo解锁加载中', err)
            })
    }
    const getTableInfo = (info: any) => {
        const params = {
            ENTITYMODEL: state.entityModel,
            OBJECTRRN: info.TABLERRN
        }
        state.getEntity(params)
            .then((res: any) => {
                if (res.Header.RESULT === 'SUCCESS') {
                    console.log(res.Body.DATA)
                    const tableInfo = res.Body.DATA
                    const WHERECLAUSE = (info.WHERECLAUSE && tableInfo.WHERECLAUSE)
                        ? `${info.WHERECLAUSE} and ${tableInfo.WHERECLAUSE}`
                        : `${info.WHERECLAUSE || ''}${tableInfo.WHERECLAUSE || ''}`
                    setDataListParams({
                        WHERECLAUSE,
                        ENTITYMODEL: tableInfo.MODELCLASS,
                        ORDERBYCLAUSE: tableInfo.ORDERBYCLAUSE
                    })
                    const isZh = state.lang === 'zh-CN'
                    const cols = tableInfo.ADFIELDLIST
                        .filter((x: any) => x.ISMAIN)
                        .filter((x: any) => x.ISDISPLAY)
                        .sort((a: any, b: any) => a.SEQNO - b.SEQNO)
                        .map((item: any) => ({
                            title: isZh ? item.LABELZH : item.LABEL,
                            dataIndex: item.NAME.toUpperCase()
                        }))
                    setColumns(cols)
                    setFieldList(tableInfo.ADFIELDLIST)
                    // 获取子表单的级联信息 referRuleInfo
                    const obj = {} as any
                    tableInfo.ADFIELDLIST?.filter((x: any) => 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)
                    setSearchVisible({
                        creator: true
                    })
                }
            })
            .catch((err: any) => {
                console.log('getTableInfo 请求失败，todo解锁加载中', err)
            })
    }

    const renderSearchFormModal = () => {
        // console.log('fieldList', fieldList)
        if (searchVisible.creator) {
            return (
                <Modal
                    width="50%"
                    title="search"
                    visible={searchVisible.creator}
                    onOk={handleOk}
                    onCancel={handleCancel}
                    destroyOnClose={true}
                >
                    <Form form={searchForm} layout="horizontal">
                        {/* {console.log('渲染formItem')} */}
                        {fieldList.filter(x => x.ISDISPLAY && x.ISQUERY).map((item: any) => {
                            return (
                                <ActiveField
                                    key={item.OBJECTRRN}
                                    field={item}
                                    referRuleInfo={referRuleInfo}
                                    formDetail={fullFormContent}
                                    formType="searchForm"
                                    onChange={(val) => {
                                        setFullFormContent({ ...fullFormContent, ...val })
                                    }}
                                />
                            )
                        })}
                    </Form>
                    <div style={{ textAlign: 'right', margin: '10px 0' }}>
                        <Button type="primary" icon={<SearchOutlined />} size="small" onClick={onSearch}>
                            {state.lang === 'zh-CN' ? '搜索' : 'Search'}
                        </Button>&nbsp;
                        <Button size="small" icon={<RedoOutlined />} onClick={onReset}>
                            {state.lang === 'zh-CN' ? '重置' : 'Reset'}
                        </Button>
                    </div>
                    <Table
                        columns={columns}
                        dataSource={dataList}
                        rowKey={(r: any) => r.OBJECTRRN}
                        size="small"
                        pagination={dataList.length > 2
                            ? {
                                showQuickJumper: true,
                                hideOnSinglePage: true,
                                showLessItems: true,
                                showTotal(total) {
                                    return `共${total}条`
                                }
                            } : false}
                        scroll={{ y: 400 }}
                        rowSelection={{
                            onChange: (selKeys: any, srkRow: any) => {
                                setSelectedRowKeys(selKeys);
                                setSelectedRows(srkRow)
                            },
                            selectedRowKeys,
                            type: 'radio',
                            columnWidth: '30px',
                        }}
                        onRow={(record: any) => {
                            return {
                                onClick: () => {
                                    setSelectedRowKeys([record.OBJECTRRN]);
                                    setSelectedRows([record])
                                },
                            };
                        }}
                    >
                    </Table>
                </Modal>
            )
        } else {
            return (<div></div>)
        }
    }

    const handleOk = () => {
        const name = options.value
        // 使用react不需要获取表单字段名拼对象属性
        console.log('name', name);
        console.log('selectedRows', selectedRows);
        if (selectedRows.length > 0 && selectedRows[0]) {
            onChange(selectedRows[0].NAME)
            setSearchVisible({
                creator: false
            })
        } else {
            setSearchVisible({
                creator: false
            })
        }
    }
    const handleCancel = () => {
        setSearchVisible({
            creator: false
        })
        searchForm.resetFields()
        setSelectedRowKeys([])
        setSelectedRows([])
    }
    const onSearch = () => {
        searchForm.validateFields().then(values => {
            // console.log('搜索表单', values);
            getDataList(values)
            setSelectedRowKeys([]);
            setSelectedRows([])
        }).catch(errorInfo => {
            console.log(errorInfo)
        })
    }
    const onReset = () => {
        searchForm.resetFields()
        setSelectedRowKeys([])
        setSelectedRows([])
    }
    const getDataList = (otherParams: any) => {
        const params = JSON.parse(JSON.stringify(dataListParams))
        if (otherParams) {
            const sqlwhere = sqlUtil.convertSqlWhere(otherParams)
            if (sqlwhere) {
                params.WHERECLAUSE = params.WHERECLAUSE ? `${params.WHERECLAUSE} and ${sqlwhere}` : sqlwhere
            }
        }
        // console.log('请求表格数据参数', params)
        setDataList([])
        state.getEntityList(params).then((res: any) => {
            console.log('res:', res);
            if (res.Header.RESULT === 'SUCCESS') {
                if (res.Body.DATALIST.length > 0) {
                    const listData = res.Body.DATALIST.map((x: any, i: number) => {
                        x.key = x.OBJECTRRN || i
                        if (params.ENTITYMODEL === 'com.glory.framework.security.model.ADUserGroup') {
                            x.NAME = x.USERGROUPID
                        }
                        return x
                    })
                    console.log('搜索到的表格数据', listData);
                    setDataList(listData)
                } else {
                    setDataList([])
                }
            }
        })
            .catch((err: any) => {
                console.log('请求失败，todo解锁加载中', err)
            })
            .finally(() => {
            })
    }
    return (
        <>
            <Input.Search
                value={value}
                onSearch={(value) => {
                    console.log('触发GSearch的搜索', value)
                    getRefTableInfo()
                }}
                onChange={onChange}
            />
            {searchVisible.creator ? renderSearchFormModal() : null}
        </>
    )
}

export default GSearch;