/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-02-17 17:30:51
 * @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, DownOutlined, InboxOutlined } from '@ant-design/icons';
import { ActionType, ProFormDependency, ProFormInstance, ProFormText, ProFormSelect } from '@ant-design/pro-components';
import { ModalForm, ProFormCascader, ProFormCheckbox, ProFormDigit, ProFormRadio, ProFormSwitch, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Drawer, Dropdown, Input, MenuProps, message, Popconfirm, Popover, Switch, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';


import { addData, delData, editData, generateTableDataReq, getCurrentHospAlldeps, getTableList, uploadFilesReq, withdrawReq } from './service';

import './style.less';


import QualifiDicMana from '@/pages/qualificationMana/qualifiDicMana';
import Dragger from 'antd/es/upload/Dragger';
import { useModel } from '@umijs/max';
import { getDicDataBySysId } from '@/services/getDic';
import { KcimCenterSysId } from '@/constant';
import React from 'react';
import generateTableData from './generateTableData';



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

//填报周期
export const DATAFILL_PERIODTYPE = [
    { label: '月度', value: 1 },
    { label: '季度', value: 2 },
    { label: '年度', value: 3 },
    { label: '变动时', value: 4 },
];
//填报主体类型
export const DATAFILL_MAINTYPE = [
    { label: '职能科室填报 ', value: 1 },
    { label: '科室填报', value: 2 },
];

//填报维度
export const DATAFILL_DIMENSIONTYPE = [
    { label: '按全院  ', value: 1 },
    { label: '按科室', value: 2 },
];


type Data = {
    [key: number]: string;
};

type LabelValue = {
    label: string;
    value: number;
};

function transformToLabelValue(data: Data): LabelValue[] {

    const result: LabelValue[] = [];
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            result.push({
                label: data[key],
                value: parseInt(key)
            });
        }
    }
    return result;
}



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);
}


let detailTableColumns: ProColumns[] = [];




export default function FillingMana() {
    const { initialState, setInitialState } = useModel('@@initialState');
    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const tableRef = useRef<ActionType>();
    const formRef = useRef<ProFormInstance>();
    const [tableDataSource, set_tableDataSource] = useState<any[]>([]);
    const [tableColumns, set_tableColumns] = useState<ProColumns[]>([]);
    const [currentEditRow, set_currentEditRow] = useState<any>(undefined)
    const [actionType, set_actionType] = useState<'NORMAL' | 'DETAIL' | undefined>('NORMAL');
    const [currentEditTableRow, set_currentEditTableRow] = useState<any>(undefined);

    const tableColumns_default: ProColumns[] = [
        {
            title: '操作',
            key: 'option',
            fixed: 'right',
            width: 120,
            valueType: 'option',
            render: (_: any, record: any) => {
                return <a key={'edit'} onClick={() => { set_currentEditTableRow(record) }}>编辑</a>
            },
        }
    ];

    const columns: ProColumns[] = [
        {
            title: '填报项目',
            ellipsis: true,
            dataIndex: 'name'
        },
        {
            title: '填报周期',
            ellipsis: true,
            dataIndex: 'periodType',
            renderText(code, record, index, action) {
                const item = DATAFILL_PERIODTYPE.find(item => item.value === code);
                return item ? item.label : '';
            }
        },
        {
            title: '填报维度',
            ellipsis: true,
            dataIndex: 'dimensionType',
            renderText(code, record, index, action) {
                const item = DATAFILL_DIMENSIONTYPE.find(item => item.value === code);
                return item ? item.label : '';
            }
        },
        {
            title: '填报主体类型',
            ellipsis: true,
            dataIndex: 'type',
            renderText(code, record, index, action) {
                const item = DATAFILL_MAINTYPE.find(item => item.value === code);
                return item ? item.label : '';
            }
        },
        {
            title: '填报主体',
            ellipsis: true,
            dataIndex: 'typeName',
        },
        {
            title: '填报单位',
            ellipsis: true,
            dataIndex: 'unit',
        },
        {
            title: '填报说明',
            ellipsis: true,
            dataIndex: 'description',
        },
        {
            title: '启用',
            width: 60,
            ellipsis: true,
            dataIndex: 'status',
            renderText(num, record) {
                return <Switch size='small' checked={num} onChange={(bool) => updateTable({...record,status:bool?1:0,}, 'EDIT')} />
            },
        },
        {
            title: '操作',
            key: 'option',
            fixed: 'right',
            width: 120,
            valueType: 'option',
            render: (_: any, record: any) => {
                const { applyStatus } = record;

                return [
                    <a key={'detail'} onClick={() => { set_currentEditRow(record) }}>详情</a>,
                    <UpDataActBtn record={record} type={'EDIT'} />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>

                ]

            },
        },

    ];


    const getGenerateTableData = async () => {
        //   const resp = await generateTableDataReq({periodType:1,dataYear:'2025',});
        //   if(resp){

        //   }

        const itemTitles = [
            { code: "fillItemName", name: "项目名称" },
            { code: "dimensionName", name: "维度名称" },
            { code: "1", name: "数值1" },
            { code: "2", name: "数值2" },
            { code: "3", name: "数值3" },
            { code: "4", name: "数值4" },
            { code: "5", name: "数值5" },
            { code: "6", name: "数值6" },
            { code: "7", name: "数值7" },
            { code: "8", name: "数值8" },
            { code: "9", name: "数值9" },
            { code: "10", name: "数值10" },
            { code: "11", name: "数值11" },
            { code: "12", name: "数值12" },
        ];

        const itemDatas = [
            {
                code: "fillItemName",
                value: "test",
                itemDic: {
                    id: 1,
                    hospId: "48",
                    code: "1",
                    name: "test",
                    type: 1,
                    typeName: "职能部门",
                    dimensionType: 1,
                    dimensionTypeName: "全院",
                    periodType: 1,
                    periodTypeName: "月度",
                    unit: "test",
                    status: 1,
                    description: "1",
                    delFlag: 0,
                },
            },
            { code: "dimensionName", value: "全院" },
            { code: "1", value: "20.0000" },
            { code: "2", value: undefined },
            { code: "3", value: undefined },
        ];


        const { columns, dataSource } = generateTableData(itemTitles, itemDatas);
        detailTableColumns = columns;

        set_tableColumns(columns);
        set_tableDataSource(dataSource);

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


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


    const updateTable = async (data: any, type: 'ADD' | 'EDIT') => {
        try {
            const result = {
                name: data.name,
                type: data.type,
                dimensionType: data.dimensionType,
                periodType: data.periodType,
                unit: data.unit,
                status:type == 'ADD'?null:data.status,
                description: data.description,
                fillDeptList: data.fillDeptList ? data.fillDeptList.map((a: any) => ({ departmentCode: a.value, departmentName: a.label })) : [],
                relateDeptList: data.relateDeptList ? data.relateDeptList.map((a: any) => ({ departmentCode: a.value, departmentName: a.label })) : []
            }

            if (type == 'ADD') {
                const resp = await addData(result);
                if (resp) {
                    message.success('操作成功！');
                    tableRef.current?.reload();
                    return true
                }
            }
            if (type == 'EDIT') {
                const resp = await editData({ code: data.code, ...result });
                if (resp) {
                    message.success('操作成功！');
                    tableRef.current?.reload();

                }
                return true

            }

        } catch (error) {
            console.log({ 'updateTable error': error })
        }


        return false

    }

    const tableDataSearchHandle = (paramName: string) => {

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

    }


    const UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'ADD' }) => {
        const ref = React.createRef<{ save: any; }>();
        const [maintype, set_maintype] = useState(undefined);
        const [dimensionType, set_dimensionType] = useState(undefined);

        useEffect(() => {
            if (type !== undefined) {
                formRef.current?.setFieldValue('fillDeptList', []); // 清空填报主体
            }
        }, [maintype]);

        useEffect(() => {
            if (dimensionType !== undefined) {
                formRef.current?.setFieldValue('relateDeptList', []); // 清空填相关科室
            }
        }, [dimensionType]);

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}`}
                width={352}
                formRef={formRef}
                initialValues={type == 'EDIT' ? {
                    ...record,
                    fillDeptList: record?.fillDeptList?.map((a: any) => ({ label: a.departmentName, value: Number(a.departmentCode) })) || [],
                    relateDeptList: record?.relateDeptList?.map((a: any) => ({ label: a.departmentName, value: Number(a.departmentCode) })) || []
                } : { periodType: 1, type: 1, dimensionType: 1 }}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <a className='add'>新增</a>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : { ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >

                {
                    (
                        <>
                            <ProFormText
                                name="name"
                                label="填报项目："
                                placeholder="请输入"
                                // disabled={type == 'EDIT'}
                                rules={[{ required: true, message: '填报项目不能为空!' }]}
                            />

                            <ProFormRadio.Group
                                label="填报周期："
                                name="periodType"
                                disabled={type == 'EDIT'&&record.limitFlag}
                                options={DATAFILL_PERIODTYPE}
                                rules={[{ required: true }]}
                            />
                            <ProFormRadio.Group
                                label="填报主体类型："
                                name="type"
                                disabled={type == 'EDIT'&&record.limitFlag}
                                options={DATAFILL_MAINTYPE}
                                rules={[{ required: true }]}
                                fieldProps={{
                                    onChange(e) {
                                        set_maintype(e.target.value)
                                    },
                                }}
                            />
                            <ProFormDependency name={['type']}>
                                {({ type }) => {
                                    return (
                                        <ProFormSelect
                                            label="填报主体："
                                            name="fillDeptList"
                                            disabled={type == 'EDIT'&&record.limitFlag}
                                            fieldProps={
                                                type === 1
                                                    ? {
                                                        mode: 'tags',
                                                        maxTagCount: 'responsive',
                                                        labelInValue: true,
                                                    }
                                                    : { labelInValue: true }
                                            }
                                            rules={[{ required: true, message: '填报主体不能为空!' }]}
                                            request={async () => {
                                                const depLists = await getCurrentHospAlldeps();
                                                if (depLists) {
                                                    return transformToLabelValue(depLists);
                                                }
                                                return [];
                                            }}
                                        />
                                    );
                                }}
                            </ProFormDependency>
                            <ProFormRadio.Group
                                label="填报维度："
                                name="dimensionType"
                                disabled={type == 'EDIT'&&record.limitFlag}
                                options={DATAFILL_DIMENSIONTYPE}
                                rules={[{ required: true }]}
                            />
                            <ProFormDependency name={['dimensionType']}>
                                {
                                    ({ dimensionType }) => {
                                        return dimensionType == 1 && <ProFormSelect
                                            label='相关科室：'
                                            disabled={type == 'EDIT'&&record.limitFlag}
                                            name={'relateDeptList'}
                                            fieldProps={{
                                                mode: 'tags',
                                                maxTagCount: 'responsive',
                                                labelInValue: true
                                            }}
                                            rules={[{ required: true, message: '相关科室不能为空!' }]}
                                            request={async () => {
                                                const depLists = await getCurrentHospAlldeps();
                                                if (depLists) {
                                                    return transformToLabelValue(depLists);
                                                }
                                                return [];
                                            }}
                                        />
                                    }
                                }
                            </ProFormDependency>
                            <ProFormText
                                name="unit"
                                label="填报单位："
                                placeholder="请输入"
                                rules={[{ required: true, message: '填报单位不能为空!' }]}
                            />
                            <ProFormTextArea
                                name="description"
                                label="填报说明："
                                placeholder="请输入"
                                rules={[{ required: false }]}
                            />

                        </>
                    )
                }

            </ModalForm>
        )
    }

    useEffect(() => {
        // if (currentEditTableRow) {
        //     const fetchTableData = async () => {
        //         const { columns, dataSource } = await getGenerateTableData();
        //         set_tableColumns(columns);
        //         set_tableDataSource(dataSource);
        //     };

        //     fetchTableData();
        // }
    }, [currentEditTableRow]);

    useEffect(() => {
        if (currentEditRow) {
            set_actionType('DETAIL');
            getGenerateTableData();
        } else {
            set_actionType('NORMAL');
        }
    }, [currentEditRow])

    return (
        <KCIMPagecontainer className='FillingMana' title={false}>
            {
                actionType == 'DETAIL' && (
                    <div className='FillingMana-detail'>
                        <div className='FillingMana-detail-header'>
                            <div className='FillingMana-detail-header-title'>
                                <div className='backBtn' onClick={() => set_currentEditRow(undefined)}><IconFont style={{ fontSize: 15 }} type={'iconfanhui'} /></div><span>{currentEditRow?.name}</span>
                            </div>
                            <div className='FillingMana-detail-header-title-sub'>
                                <span>填报周期：{currentEditRow&&`${(DATAFILL_PERIODTYPE.find(item => item.value === currentEditRow.periodType))?(DATAFILL_PERIODTYPE.find(item => item.value === currentEditRow.periodType))?.label:''}`}</span>
                                <span>填报维度：{currentEditRow&&`${(DATAFILL_DIMENSIONTYPE.find(item => item.value === currentEditRow.dimensionType))?(DATAFILL_DIMENSIONTYPE.find(item => item.value === currentEditRow.periodType))?.label:''}`}</span>
                                <span>填报单位：{currentEditRow?.unit}</span>
                            </div>
                        </div>
                        <div className='FillingMana-detail-content'>
                            <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'>

                                </div>
                            </div>
                            <KCIMTable
                                columns={[...tableColumns, ...tableColumns_default]}
                                scroll={{ y: 'calc(100vh - 232px)' }} rowKey='id'
                                dataSource={tableDataSource}
                                editable={{
                                    editableKeys: currentEditTableRow ? [currentEditTableRow.id] : [],
                                    actionRender: (row, config, defaultDom) => [
                                        defaultDom.save,
                                        defaultDom.cancel,
                                    ],
                                    onSave(key, record, originRow, newLineConfig) {
                                        return Promise.resolve(true);
                                    },
                                    onCancel: (key, record, originRow, newLineConfig) => {
                                        set_currentEditTableRow(undefined);
                                        return Promise.resolve(true)
                                    },
                                }}
                            />
                        </div>
                    </div>
                )
            }
            {
                actionType != 'DETAIL' && (
                    <div style={{ padding: 16, background: '#fff', borderRadius: 4 }}>
                        <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={undefined} type={'ADD'} />
                            </div>
                        </div>
                        <KCIMTable columns={columns as ProColumns[]} scroll={{ y: 'calc(100vh - 232px)' }} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
                    </div>
                )
            }
        </KCIMPagecontainer>
    )
}
