/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-06-09 10:57:54
 * @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 KCUpload from '@/components/KCUpload';
import { getAllHosp } from '@/service/hospList';
import { downloadTemplateReq } from '@/utils';
import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { message, Modal, Popconfirm } from 'antd';
import FormItem from 'antd/lib/form/FormItem';
import { useEffect, useState } from 'react'
import { addData, delData, editData, getDepartmentData, getDepartmentType, getRelaHosp, importDepartmentData } from './service';

import './style.less';



export default function DepartmentMana() {

    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 [types, set_types] = useState([]);




    const columns = [
        {
            title: '科室代码',
            dataIndex: 'code',
        },
        {
            title: '科室名称',
            dataIndex: 'name',
        },
        {
            title: '院区',
            dataIndex: 'hospName',

        },
        {
            title: '类型',
            dataIndex: 'type',
            valueType: 'select',
            fieldProps: {
                options: types
            }
        },
        {
            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 getDepartmentData(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 updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {

        if (type == 'ADD') {
            const resp = await addData(formVal);
            if (resp) {
                set_reload(true);
            }
        }

        if (type == 'EDIT') {
            const resp = await editData({ ...formVal });
            if (resp) {
                set_reload(true);
            }
        }


    }

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

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}科室`}
                width={352}
                initialValues={type == 'EDIT' ? { ...record } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit">编辑</a> : <span className='add' style={{background:'#3377FF',color:'#fff'}}>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...val, id: record.id } : val, type);
                }}
            >
                <ProFormText
                    name="name"
                    label="科室名称："
                    placeholder="请输入"
                    rules={[{ required: true, message: '科室名称不能为空!' }]}
                />
                <ProFormText
                    name="code"
                    label="科室代码："
                    placeholder="请输入"
                    rules={[{ required: true, message: '科室代码不能为空!' }]}
                />
                <ProFormSelect
                    name="type"
                    label="类型："
                    placeholder="请选择类型"
                    rules={[{ required: true, message: '类型不能为空!' }]}
                    request={async () => {
                        return types
                    }}
                />
                <ProFormSelect
                    name="hospId"
                    label="院区："
                    placeholder="请选择院区"
                    rules={[{ required: true, message: '院区不能为空!' }]}
                    request={async () => {
                        const resp = await getRelaHosp();
                        if (resp) {
                            const data: any = resp?.map((a:any) => ({
                                label: a.name,
                                value: a.id
                            }));

                            return data;
                        }
                        return []

                    }}
                />
                <ProFormTextArea
                    name="remark"
                    label="说明："
                    placeholder="请输入"

                />
            </ModalForm>
        )
    }


    const tableDataSearchHandle = (paramName: string) => {


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


    const downloadTemplateFileHandle =async () => {
        await downloadTemplateReq('/centerSys/sysdepartment/export');
    }


    const importData = ( name: string) => {

        return (
            <ModalForm
                title={`导入${name}数据`}
                width={352}
                trigger={
                    <span  key="3">导入</span>
                }
                onFinish={async (values) => {
                    
                    const { importFile: { fileList } } = values;

                    let formData = new FormData();
                    formData.append('file', fileList[0].originFileObj);
                    const resp = await importDepartmentData(formData);

                    if (resp) {
                        set_reload(true);
                        return true;
                    }

                }}
            >
                <FormItem name={'importFile'}>
                    <KCUpload downloadTemplateFile={()=>downloadTemplateFileHandle()} />
                </FormItem>

            </ModalForm>
        )
    }


    const getAllDepartmentType = async () => {
        const resp = await getDepartmentType();
        if (resp) {
            const data: any = resp?.map((a) => ({
                label: a.name,
                value: a.code
            }));
            set_types(data);
        }
    }


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

    return (
        <div className='DepartmentMana'>
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem' style={{ marginRight: 16 }}>
                        <span className='label'>类型：</span>
                        {
                            types.length > 0 && (
                                <ProFormSelect
                                    name="type"
                                    noStyle
                                    style={{ width: 160 }}
                                    placeholder="请选择类型"
                                    rules={[{ required: true, message: '类型不能为空!' }]}
                                    request={async () => {
                                        return types
                                    }}
                                    fieldProps={{
                                        onChange: (e) => {

                                            if (e) {
                                                set_tableDataFilterParams({
                                                    ...tableDataFilterParams,
                                                    departType: e
                                                });
                                            } else {
                                                set_tableDataFilterParams({
                                                    ...tableDataFilterParams,
                                                    departType: ''
                                                });
                                            }

                                        }
                                    }}
                                />
                            )
                        }
                    </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,
                                        departName: ''
                                    });
                                }
                            }}
                            onSearch={() => tableDataSearchHandle('departName')}

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    {importData('科室')}
                    <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>
    )
}
