/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-24 16:26:31
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */



import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';

import { createFromIconfontCN } from '@ant-design/icons';
import { ActionType, ProFormDependency, ProFormInstance, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { ModalForm, ProFormDigit, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Popover, Switch, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';


import { addData, delData, editData, getTableList } from './service';

import './style.less';

import { renameChildListToChildren } from '@/utils/tooljs';


const IconFont = createFromIconfontCN({
    scriptUrl: '',
});

let selectableLevelList: any[] = [];
let currentRow: any = undefined;

export const searchTree = (tree: any[], searchTerm: string) => {
    const searchTermLower = searchTerm.toLowerCase();

    function searchNode(node: any) {
        const matchedChildren: any[] = [];

        if (node.children && node.children.length > 0) {
            node.children.forEach((child: any) => {
                const matchedChild = searchNode(child);
                if (matchedChild) {
                    matchedChildren.push(matchedChild);
                }
            });
        }

        if (node.responsibilityName.toLowerCase().includes(searchTermLower) || (node.responsibilityCode && node.responsibilityCode.toLowerCase().includes(searchTermLower))) {
            return {
                ...node,
                children: matchedChildren.length > 0 ? matchedChildren : node.children
            };
        } else if (matchedChildren.length > 0) {
            return {
                ...node,
                children: matchedChildren
            };
        }

        return null;
    }

    return tree.map(rootNode => searchNode(rootNode)).filter(node => node !== null);
}


export default function QualificationClassifiMana() {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const tableRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const columns: ProColumns[] = [
        {
            title: '分类名称',
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: '分类编码',
            ellipsis: true,
            dataIndex: 'code',
        },
        {
            title: '顺序号',
            ellipsis: true,
            dataIndex: 'sort',
        },
        {
            title: '说明',
            ellipsis: true,
            dataIndex: 'description',
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            fixed: 'right',
            valueType: 'option',
            render: (_: any, record: any) => {
                const { code, allowDelete } = record;
                return code != '0' ? [
                    <UpDataActBtn key={'act'} record={record} type='ADDCHILD' />,
                    <UpDataActBtn key={'act1'} record={record} type='EDIT' />,
                    <>
                        {
                            allowDelete == 1 ? (
                                <Popconfirm
                                    title="是否确认删除？"
                                    key="del"
                                    onConfirm={() => delTableData(record)}
                                >
                                    <a>删除</a>
                                </Popconfirm>
                            ) : (
                                <Tooltip title="分类下已有资质，不可删除" placement='topRight'>
                                    <span style={{ color: '#99A6BF', cursor: 'not-allowed' }}>删除</span>
                                </Tooltip>
                            )
                        }
                    </>,
                ] : [
                    <UpDataActBtn key={'act'} record={record} type='ADDCHILD' />,
                ]
            },
        },

    ]


    const getTableData = async (params: any) => {
        const { filter } = params;
        const resp = await getTableList({ ...params });
        if (resp) {
            return {
                data: resp,
                success: true,
                total: resp.totalCount,
                pageSize: resp.pageSize,
                totalPage: resp.totalPage,
            }
        }
        return []
    }

    const delTableData = async (record: any) => {
        const resp = await delData(record.id);
        if (resp) {
            message.success('操作成功！');
            tableRef.current?.reload();
            // message.success('操作成功!');
        }
    }

    const updateTable = async (formVal: any, type: 'EDIT' | "ADD" | "ADDCHILD") => {

        try {

            if (type == 'ADD' || type == 'ADDCHILD') {

                const resp = await addData(formVal);
                if (resp) {
                    tableRef.current?.reload();
                    message.success('操作成功！');
                }

            }
            if (type == 'EDIT') {
                try {
                    const resp = await editData({ ...formVal });
                    if (resp) {
                        tableRef.current?.reload();
                        message.success('操作成功！');
                    }
                } catch (error) {
                    console.log({ error });
                }

            }

        } catch (error) {
            console.log('新增/编辑error', error);
        }

        return true;

    }


    const UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'ADD' | 'ADDCHILD' }) => {

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}分类`}
                width={350}
                formRef={formRef}
                initialValues={type == 'EDIT' ? {
                    ...record,
                } : { selectedSharelevel: 0, sort: 0 }}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : type == 'ADDCHILD' ? <a className='add'>添加</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : type == 'ADDCHILD' ? { ...val, parentCode: record.code } : { ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <ProFormText
                    label="资质分类名称："
                    rules={[
                        {
                            required: true,
                            message: '资质分类名称是必填项',
                        },
                    ]}
                    name="name"
                />
                <ProFormText
                    disabled={type == 'EDIT'}
                    label="资质分类编码："
                    rules={[
                        {
                            required: true,
                            message: '资质分类编码是必填项',
                        },
                    ]}
                    name="code"
                />
                <ProFormDigit
                    label="顺序号："
                    width={120}
                    rules={[
                        {
                            required: true,
                            message: '顺序号是必填项',
                        },
                    ]}
                    name="sort"
                />
                <ProFormTextArea
                    label="资质分类说明："
                    name="description"
                />

            </ModalForm>
        )
    }

    const tableDataSearchHandle = (paramName: string) => {

        set_tableDataFilterParams({
            ...tableDataFilterParams,
            currnt: 1,
            [`${paramName}`]: tableDataSearchKeywords
        })

    }

    useEffect(() => {

    }, [])

    return (
        <KCIMPagecontainer className='QualificationClassifiMana' title={false}>
            <div className='pageContent'>
                <div className='toolBar'>
                    <div className='filter'>
                        <div className='filterItem'>
                            <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                            <Input placeholder={'分类编码、分类名称'} allowClear autoComplete='off'
                                suffix={
                                    <IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle('queryCondition')} />
                                }
                                onChange={(e) => {
                                    set_tableDataSearchKeywords(e.target.value);
                                    if (e.target.value.length == 0) {
                                        set_tableDataFilterParams({
                                            ...tableDataFilterParams,
                                            current: 1,
                                            queryCondition: ''
                                        });
                                    }
                                }}
                                onPressEnter={(e) => {

                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        current: 1,
                                        queryCondition: (e.target as HTMLInputElement).value
                                    });
                                }}

                            />
                        </div>
                    </div>
                    <div className='btnGroup'>
                        {/* <UpDataActBtn record type='ADD' /> */}
                    </div>
                </div>
                <KCIMTable pagination={false} columns={columns as ProColumns[]}
                    scroll={{ y: 'calc(100vh - 192px)' }} actionRef={tableRef} rowKey='code'
                    expandable={{
                        defaultExpandedRowKeys: ['0']
                    }}
                    params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </KCIMPagecontainer>
    )
}
