/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-03-22 17:40:53
 * @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<any | undefined>();
    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 = [
        {
            title: '主题',
            dataIndex: 'title',

        },
        {
            title: '消息内容',
            dataIndex: 'content',
        },
        {
            title: '院区',
            dataIndex: 'hospName',
        },
        {
            title: '系统',
            dataIndex: 'systemName',
        },
        {
            title: '接收类型',
            dataIndex: 'receiveTypeName',
        },
        {
            title: '接收对象',
            dataIndex: 'receiveTargetName',
        },
        {
            title: '消息级别',
            dataIndex: 'receiveLevelName',
        },
        {
            title: '处理链接',
            dataIndex: 'resolvePath',
        },
        {
            title: '备注',
            dataIndex: 'remark',
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            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 resp = await getData(params);
        set_reload(false);
        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.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.value, 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={688}
                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="院区："
                    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={{
                        fieldNames: {
                            label: 'name',
                            value: 'code'
                        },
                    }}
                    rules={[{ required: true, message: '系统不能为空!' }]}
                />

                <ProFormSelect
                    name="receiveType"
                    label="接收类型："
                    options={setSelectorData('RECEIVE_TYPE').list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择!' }]}
                />
                <ProFormSelect
                    name="receiveTarget"
                    label="接收对象："
                    options={setSelectorData('RECEIVE_TARGET').list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择!' }]}
                />
                <ProFormSelect
                    name="receiveLevel"
                    label="消息级别："
                    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 tableDataSearchHandle = (paramName: string) => {


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


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

    return (
        <div className='PubDicTypeMana'>
            <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={{
                                onChange(value, option) {
                                    set_tableDataFilterParams({ ...tableDataFilterParams, 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={{
                                fieldNames: {
                                    label: 'name',
                                    value: 'code'
                                },
                                onChange(value: any, option: any) {
                                    set_tableDataFilterParams({ ...tableDataFilterParams, 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,
                                        title: ''
                                    });
                                }
                            }}
                            onSearch={() => tableDataSearchHandle('title')}

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    <UpDataActBtn record type='ADD' />
                </div>
            </div>
            <div style={{ marginTop: 16 }}>
                <KCTable columns={columns as ProColumns[]} reload={reload} rowKey='id' newVer params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </div>
    )
}
