/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-06-08 13:54:15
 * @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 BMSPagecontainer from '@/components/BMSPageContainer';
import { BMSTable } from '@/components/BMSTable';
import { getDataByKeyFromDic, getPubDicData } from '@/services/getDic';
import { createFromIconfontCN } from '@ant-design/icons';

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


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

import './style.less';
import '../../../../utils/zhongtaiB'

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



export default function CheckUnitClassficationMana() {

    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: 'className',
        },
        {
            title: '分类代码',
            dataIndex: 'code',
        },
        {
            title: '职类',
            dataIndex: 'unitTypeName',
        },
        {
            title: '序号',
            dataIndex: 'sort',
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            title: '说明',
            width: 200,
            dataIndex: 'description',
            ellipsis: true,
        },
        {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <UpDataActBtn key={'add'} record={record} type='ADDCHILD' />,
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },

    ]


    const getTableData = async (params: any) => {
        const resp = await getCheckUnitClassTableData(params);
        if (resp) {
            return {
                data: resp,
                success: true
            }
        }
        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') => {

        let flag = false;

        if (type == 'ADD' || type == 'ADDCHILD') {
            const resp = await addData({
                ...formVal,
                parentClassCode: formVal.parentClassCode ? formVal.parentClassCode : '0'
            });
            if (resp) {
                flag = true;
                tableRef.current?.reload();
                message.success('操作成功！');
            }

        }
        if (type == 'EDIT') {

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

    }

    const [dicData, set_dicData] = useState<any[]>([]);

    const getDirecData = async (key?: string) => {

        const data = await getPubDicData();
        if (data) {
            set_dicData(data);
        }
    }


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

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}核算单元分类`}
                width={400}
                formRef={formRef}
                initialValues={type == 'EDIT' ? {
                    ...record,

                } : {}}
                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, parentClassCode: record.code,unitType:record.unitType} : { ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <ProFormText
                    name="className"
                    label="分类名称："
                    placeholder="请输入"
                    rules={[{ required: true, message: '名称不能为空!' }]}
                />
                <ProFormText
                    name="code"
                    label="分类代码："
                    placeholder="请输入"
                    rules={[{ required: true, message: '代码不能为空!' }]}
                />
                {
                    type == 'ADD' && (
                        <ProFormSelect label="职类："
                            name='unitType'
                            options={(getDataByKeyFromDic(dicData, '1')).list}
                            rules={[{ required: true, message: '职类不能为空!' }]}
                        />
                    )
                }
                <ProFormDigit
                    name="sort"
                    label="序号："
                    placeholder="请输入"
                    rules={[{ required: true, message: '序号不能为空!' }]}
                />
                <ProFormTextArea
                    name="description"
                    label="说明："
                    placeholder="请输入"

                />
            </ModalForm>
        )
    }

    const tableDataSearchHandle = (paramName: string) => {

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

    }


    useEffect(() => {
        getDirecData();
    }, [])

    return (
        <BMSPagecontainer className='CheckUnitClassficationMana' title={false}>
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                        <Input placeholder={'请输入分类名称'} allowClear
                            suffix={
                                <IconFont style={{color:'#99A6BF'}} type="iconsousuo" onClick={() => tableDataSearchHandle('unitTypeName')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        unitTypeName: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

                                set_tableDataFilterParams({
                                    ...tableDataFilterParams,
                                    unitTypeName: (e.target as HTMLInputElement).value
                                });
                            }}

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    <UpDataActBtn record type='ADD' />
                </div>
            </div>

            <div style={{ marginTop: 16 }}>
                <BMSTable columns={columns as ProColumns[]} pagination={false} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </BMSPagecontainer>
    )
}
