/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-12-02 14:08:21
 * @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 { KCInput } from '@/components/KCInput';
import KCTable from '@/components/kcTable';
import { getAllHosp } from '@/service/hospList';
import { getUserRelaSeletData } from '@/service/user';
import { ModalForm, ProFormCascader, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Popconfirm } from 'antd';
import { useEffect, useState } from 'react'
import { getSysLists } from '../paramsMana/service';
import { addData, delData, editData, getData } from './service';

import './style.less';



export default function PubDicTypeMana() {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<{
        current: number;
        pageSize: number;
        name?: string;
    }>({
        current: 1,
        pageSize: 10
    });
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const [reload, set_reload] = useState(false);
    const [currentEdit, set_currentEdit] = useState<any>(undefined);

    //字典
    const [dirData, set_dirData] = useState<any[]>([]);

    const columns:ProColumns[] = [
        {
            title: '主题',
            dataIndex: 'title',

        },
        {
            title: '消息内容',
            dataIndex: 'content',
            ellipsis:true
        },
        {
            title: '院区',
            dataIndex: 'hospName',
            ellipsis:true
        },
        {
            title: '系统',
            dataIndex: 'systemName',
            ellipsis:true
        },
        {
            title: '接收类型',
            dataIndex: 'receiveTypeName',
            ellipsis:true
        },
        {
            title: '接收对象',
            dataIndex: 'receiveTargetName',
            ellipsis:true
        },
        {
            title: '消息级别',
            dataIndex: 'receiveLevelName',
            ellipsis:true
        },
        {
            title: '处理链接',
            dataIndex: 'resolvePath',
            ellipsis:true
        },
        {
            title: '备注',
            dataIndex: 'remark',
        },
        {
            title: '操作',
            key: 'option',
            width: 90,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },

    ]


    const getTableData = async (params: any) => {
        const { current = 1, pageSize = 10, name } = params;
        const resp = await getData({
            current,
            pageSize,
            name
        });
        set_reload(false);
        if (resp) {
            return {
                data: resp.list,
                success: true,
                total: resp.totalCount
            };
        }
        return {
            data: [],
            success: false,
            total: 0
        };
    }

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


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

        const data = await getUserRelaSeletData(key);
        if (data) {
          set_dirData(data);
        }
    }


    const setSelectorData = (key: string) => {

        let result = dirData.filter((t: any) => (t.code == key));

        if (result.length > 0) {

            let dataArr = result[0].dataVoList;

            let defaultValue = dataArr.filter((t: any) => t.defaultValue == 1);

            dataArr.sort((prev: any, next: any) => {
                return prev.sort - next.sort;
            });

            return {
                defaultvalue: defaultValue[0] ? defaultValue[0].value : '',
                list: dataArr.map((t: any) => ({ label: t.name, value: t.code }))
            }
        }

        return {
            defaultvalue: '',
            list: []
        };
    }




    const updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {
        
        if (type == 'ADD') {
            const resp = await addData({ ...formVal,
                systemPath:formVal.systemId?formVal.systemId.join(','):'',
                systemId:(formVal.systemId&&formVal.systemId.length>0)?formVal.systemId[formVal.systemId.length -1]:''});
            if (resp) {
                set_reload(true);
            }
        }
        if (type == 'EDIT') {
            const resp = await editData({ ...formVal,
                systemPath:formVal.systemId?formVal.systemId.join(','):'',
                systemId:(formVal.systemId&&formVal.systemId.length>0)?formVal.systemId[formVal.systemId.length -1]:''});
            if (resp) {
                set_reload(true);
            }
        }


    }

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

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}消息模板`}
                width={730}
                initialValues={type == 'EDIT' ? { 
                    ...record,
                    systemId:record.systemPath?record.systemPath.split(','):[]
                 } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT'?{...val,id:record.id}:{...val}, type);
                }}
                colProps={{span:12}}
                grid
            >

                <ProFormText
                    name="title"
                    label="消息主题："
                    placeholder="请输入"
                    rules={[{ required: true, message: '主题不能为空!' }]}
                />
                <ProFormText
                    name="content"
                    label="消息内容："
                    placeholder="请输入"
                    rules={[{ required: true, message: '消息内容不能为空!' }]}
                />
                <ProFormSelect
                    name="hospId"
                    label="院区："
                    fieldProps={{size:'small'}}
                    // disabled={type == 'EDIT'}
                    placeholder="请选择院区"
                    rules={[{ required: true, message: '院区不能为空!' }]}
                    request={async () => {
                        const resp = await getAllHosp({ pageSize: 200, current: 1 });
                        if (resp) {
                            const data: any = resp.list?.map((a) => ({
                                label: a.hospName,
                                value: a.id
                            }));

                            return [{
                                  label:'所有院区',
                                  value:'0'
                            },...data];
                        }
                        return []

                    }}
                />

                <ProFormCascader
                    label='系统：'
                    name='systemId'
                    placeholder="请选择"
                    request={async () => {
                        const resp = await getSysLists();
                        if (resp) {
                            return resp
                        }
                        return []

                    }}
                    fieldProps={{
                        size:'small',
                        fieldNames: {
                            label: 'name',
                            value: 'code'
                        },
                    }}
                    rules={[{ required: true, message: '系统不能为空!' }]}
                />

                <ProFormSelect
                    name="receiveType"
                    label="接收类型："
                    options={setSelectorData('RECEIVE_TYPE').list}
                    placeholder="请选择"
                    fieldProps={{size:'small'}}
                    rules={[{ required: true, message: '请选择!' }]}
                />
                <ProFormText
                    name="receiveTarget"
                    label="接收对象："
                    // options={setSelectorData('RECEIVE_TARGET').list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择!' }]}
                />
                <ProFormSelect
                    name="receiveLevel"
                    label="消息级别："
                    fieldProps={{size:'small'}}
                    options={setSelectorData('MESSAGE_LEVEL').list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择!' }]}
                />
                <ProFormText
                    name="resolvePath"
                    label="处理链接："
                    placeholder="请输入"
                />
                <ProFormTextArea
                    colProps={{span:24}}
                    name="remark"
                    label="备注："
                    
                    placeholder="请输入"

                />
            </ModalForm>
        )
    }

    const handleTableChange = (pagination: any) => {
        set_tableDataFilterParams({
            ...tableDataFilterParams,
            current: pagination.current,
            pageSize: pagination.pageSize
        });
    }

    const tableDataSearchHandle = (paramName: string) => {
        set_tableDataFilterParams({
            ...tableDataFilterParams,
            current: 1,
            [`${paramName}`]: tableDataSearchKeywords
        });
    }


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

    return (
        <div className='NotificationTemplate'>
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label'>院区：</span>
                        <ProFormSelect
                            noStyle
                            allowClear
                            placeholder="请选择"
                            style={{ width: 160, marginRight: 16 }}
                            request={async () => {
                                const resp = await getAllHosp({ pageSize: 200, current: 1 });
                                if (resp) {
                                    const data: any = resp.list?.map((a) => ({
                                        label: a.hospName,
                                        value: a.id
                                    }));

                                    return [
                                        {
                                            label: '所有院区', value: '0'
                                        }, ...data
                                    ];
                                }
                                return []

                            }}
                            fieldProps={{
                                size:'small',
                                onChange(value, option) {
                                    set_tableDataFilterParams({ ...tableDataFilterParams,current:1, hospId: value })
                                },
                            }}
                        />
                    </div>
                    <div className='filterItem' style={{ marginRight: 16 }}>
                        <span className='label'>系统名称：</span>
                        <ProFormCascader
                            noStyle
                            allowClear
                            width={160}
                            placeholder="请选择"
                            request={async () => {
                                const resp = await getSysLists();
                                if (resp) {
                                    return resp
                                }
                                return []

                            }}
                            fieldProps={{
                                size:'small',
                                fieldNames: {
                                    label: 'name',
                                    value: 'code'
                                },
                                onChange(value: any, option: any) {
                                    set_tableDataFilterParams({ ...tableDataFilterParams,current:1, systemId: value ? value[value.length - 1] : '' })
                                },
                            }}
                        />
                    </div>
                    <div className='filterItem'>
                        <span className='label'>检索：</span>
                        <KCInput placeholder={'请输入主题名称'} style={{ width: 160 }} search allowClear
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        current:1,
                                        title: ''
                                    });
                                }
                            }}
                            onSearch={() => tableDataSearchHandle('title')}

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    <UpDataActBtn record type='ADD' />
                </div>
            </div>
            <div style={{ marginTop: 16 }}>
                <KCTable
                    columns={columns}
                    scroll={{ y: `calc(100vh - 250px)` }}
                    reload={reload}
                    rowKey="id"
                    newVer
                    params={tableDataFilterParams}
                    request={(params) => getTableData(params)}
                    onChange={handleTableChange}
                />
            </div>
        </div>
    )
}
