import './modfield.css'
import {Alert, Button, Input, message, Table, TableProps} from "antd";
import {useEffect, useState} from "react";
import {DeleteOutlined, PlusOutlined} from "@ant-design/icons";
import {pinyin} from "pinyin-pro";
import {uuid} from "../../util/CommonUtil.ts";

export interface IModField {
    projModFieldId: string;
    fieldDesc: string;
    fieldName: string;
    fieldType: string;
}

interface PropsType {
    scrollHeight?: number;
    modFiledArray?: IModField[];
    isEdit?: boolean;
    isFree?: boolean;

    handleChange?(modFieldArray: undefined | IModField[]): void;
}

export default function ModField(props: PropsType) {
    const [messageApi, contextHolder] = message.useMessage();
    const [tableDataArray, setTableDataArray] = useState<IModField[]>([]);

    const isFiledNameExist = function (index: number, fieldName: string) {
        for (let i = 0; i < tableDataArray.length; i++) {
            if (i != index && tableDataArray[i].fieldName === fieldName) {
                return true;
            }
        }
        return false;
    }

    const handleChange = () => {
        props.handleChange?.(tableDataArray.filter(item => item.fieldName));
    }

    useEffect(() => {
        if (props.modFiledArray) {
            setTableDataArray(props.modFiledArray)
        }
    }, [props.modFiledArray])

    const columns: TableProps<IModField>['columns'] = [
        {
            title: '描述*',
            dataIndex: 'fieldDesc',
            render: (text, _record, index) => {
                if (props.isEdit) {
                    return (
                        <Input defaultValue={text} onChange={(e) => {
                            const item = tableDataArray[index];
                            const value = e.target.value;
                            const fieldName = pinyin(value, {
                                pattern: 'first',
                                toneType: 'none',
                                type: 'array'
                            }).join('');
                            if (isFiledNameExist(index, fieldName)) {
                                messageApi.open({
                                    type: 'error',
                                    content: `字段名【${value}】已存在`
                                });
                                item.fieldName = '';
                            } else {
                                item.fieldDesc = value;
                                item.fieldName = fieldName;
                            }
                            setTableDataArray([...tableDataArray]);
                            handleChange();
                        }}/>
                    )
                } else {
                    return text;
                }
            }
        },
        {
            title: '名称',
            dataIndex: 'fieldName',
            align: 'center',
            width: 150,
        },
    ];

    if(props.isEdit) {
        columns.push({
            title: '操作',
            dataIndex: 'option',
            align: 'center',
            width: 100,
            render: (_text, _record, index) => {
                if (props.isEdit) {
                    return (
                        <Button type="primary" size="small" danger onClick={() => {
                            tableDataArray.splice(index, 1);
                            setTableDataArray([...tableDataArray]);
                            handleChange();
                        }}><DeleteOutlined/></Button>
                    )
                } else {
                    return ''
                }
            }
        })
    }

    return (
        <>
            {contextHolder}
            <div className="mod-field-container">
                <Alert
                    message="菜单属性"
                    description="说明：菜单属性会动态建表并添加模拟数据，字段 描述 为中文且在当前菜单中不可重复（这里的不能重复指的是自动生成的拼音名称不能重复），可以有数字，但不能以数字开头，字段 名称 会根据拼音首字母自动生成"
                    type="success"
                />
                {
                    props.isEdit ? (
                        <div className="mod-field-table-btn">
                            <Button type="default" onClick={() => {
                                if(props.isFree && tableDataArray.length >= 3) {
                                    messageApi.error('免费版最多能添加3个字段').then(() => {});
                                    return;
                                }
                                setTableDataArray([
                                    ...tableDataArray,
                                    {
                                        projModFieldId: uuid(),
                                        fieldType: 'string',
                                        fieldDesc: '',
                                        fieldName: '',
                                    }
                                ])
                            }}><PlusOutlined/> 添加属性</Button>
                        </div>
                    ) : <></>
                }
                <Table dataSource={tableDataArray} columns={columns} pagination={false} bordered
                       scroll={{y: props.scrollHeight ? props.scrollHeight : 300}}
                       style={{marginTop: '15px'}}
                       rowKey="projModFieldId"/>
            </div>
        </>
    )
}