/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-05-18 17:56:28
 * @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 { getPubDicData } from '@/services/getDic';
import { createFromIconfontCN } from '@ant-design/icons';

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

import { addCostData, addIncomeData, delData, editCostData, editIncomeData, getCostIncomeProjectTable, getCostProjectTable } from './service';

import './style.less';


const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/c/font_1927152_4nm5kxbv4m3.js',
});



export default function CostIncomeProjectSet() {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const tableRef = useRef<ActionType>();

    const [columns, set_columns] = useState<ProColumns[]>([]);

    const [currentSelectedTabKey, set_currentSelectedTabKey] = useState<string>('1');




    const incomeColumns: ProColumns[] = [

        {
            title: '项目代码',
            dataIndex: 'code',
        },
        {
            title: '项目名称',
            dataIndex: 'name',
        },
        {
            title: '适应范围',
            dataIndex: 'scope',
            renderText(num, record, index, action) {
                return `${record.opdFlag == 1 ? record.opdFlagName : ''}${(record.opdFlag ==1&&record.inpFlag==1)?' | ':''}${record.inpFlag == 1?record.inpFlagName : ''}`
            },
        },
        {
            title: '统计',
            dataIndex: 'statFlag',
            renderText(num, record, index, action) {
                return record.statFlag ? '是' : '否'
            },
        },
        {
            title: '序号',
            dataIndex: 'seqNo',
        },
        {
            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 costCloumns: ProColumns[] = [
        {
            title: '项目名称',
            dataIndex: 'name',
        },
        {
            title: '类型',
            dataIndex: 'itemTypeName',
        },
        {
            title: '汇总',
            dataIndex: 'summaryFlag',
            renderText(num, record, index, action) {
                return record.summaryFlag ? '是' : '否'
            },
        },
        {
            title: '可控',
            dataIndex: 'ctrlFlag',
            renderText(num, record, index, action) {
                return record.ctrlFlag ? '是' : '否'
            },
        },
        {
            title: '统计',
            dataIndex: 'statFlag',
            renderText(num, record, index, action) {
                return record.statFlag ? '是' : '否'
            },
        },
        {
            title: '序号',
            dataIndex: 'seqNo',
        },
        {
            title: '操作',
            key: 'option',
            width: 160,
            valueType: 'option',
            render: (_: any, record: any) => {
                return record.summaryFlag ? [
                    <UpDataActBtn key={'add'} type='ADD' text='添加' record={record} />,
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ] : [
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },

    ]


    const getTableData = async (params: any) => {
        if (currentSelectedTabKey == '1') {
            const resp = await getCostIncomeProjectTable(params);
            if (resp) {
                return {
                    data: resp.list,
                    success: true,
                    total: resp.totalCount,
                    pageSize: resp.pageSize,
                    totalPage: resp.totalPage,
                }
            }
        }
        if (currentSelectedTabKey == '2') {
            const resp = await getCostProjectTable(params);
            if (resp) {
                return {
                    data: resp,
                    success: true,
                }
            }
        }

        return []
    }

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

    const updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {

        console.log({ formVal });

        if(currentSelectedTabKey == '1'){
            const result = {
                name: formVal.name,
                opdFlag: formVal.scope.includes('门诊') ? 1 : 0,
                inpFlag: formVal.scope.includes('住院') ? 1 : 0,
                statFlag: formVal.statFlag,
                seqNo: formVal.seqNo
            }
    
            if (type == 'ADD') {
                const resp = await addIncomeData({ ...result });
                if (resp) {
                    tableRef.current?.reload();
                    message.success('操作成功！');
                }
            }
            if (type == 'EDIT') {
                const resp = await editIncomeData({ id: formVal.id, ...result });
                if (resp) {
                    tableRef.current?.reload();
                    message.success('操作成功！');
                }
            }
        }
        if(currentSelectedTabKey == '2'){
            const result = {
                name: formVal.name,
                parentCode: formVal.parentCode,
                itemType: formVal.itemType,
                summaryFlag: formVal.summaryFlag,
                ctrlFlag: formVal.ctrlFlag,
                statFlag: formVal.statFlag,
                seqNo: formVal.seqNo
            }
    
            if (type == 'ADD') {
                const resp = await addCostData({ ...result });
                if (resp) {
                    tableRef.current?.reload();
                    message.success('操作成功！');
                }
            }
            if (type == 'EDIT') {
                const resp = await editCostData({ id: formVal.id, ...result });
                if (resp) {
                    tableRef.current?.reload();
                    message.success('操作成功！');
                }
            }
        }


        

        return true;
    }

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

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

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

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

        let scope = [];
        if (record.opdFlag) { scope.push('门诊') }
        if (record.inpFlag) { scope.push('住院') }

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}${currentSelectedTabKey == '1' ? '收入项目' : '成本项目'}`}
                width={352}
                initialValues={type == 'EDIT' ? { ...record, scope: scope } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <a className='add'>{text ? text : '新增'}</a>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val,parentCode:record.parentCode} : { ...val,parentCode:record.code?record.code:0 }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >

                {
                    currentSelectedTabKey == '1' && (
                        <>
                            <ProFormText
                                name="name"
                                label="项目名称："
                                placeholder="请输入"
                                rules={[{ required: true, message: '名称不能为空!' }]}
                            />
                            <ProFormCheckbox.Group
                                name="scope"
                                label="适应范围："
                                options={['门诊', '住院']}
                                rules={[{ required: true, message: '适应范围不能为空!' }]}
                            />

                            <ProFormRadio.Group
                                name="statFlag"
                                label="统计："
                                options={[
                                    {
                                        label: '是',
                                        value: 1,
                                    },
                                    {
                                        label: '否',
                                        value: 0,
                                    }
                                ]}
                                placeholder="请选择"
                            />
                            <ProFormDigit
                                name="seqNo"
                                label="序号："
                                rules={[{ required: true, message: '序号不能为空!' }]}
                            />
                        </>
                    )
                }

                {
                    currentSelectedTabKey == '2'&&(
                        <>
                            <ProFormText
                                name="name"
                                label="项目名称："
                                placeholder="请输入"
                                rules={[{ required: true, message: '名称不能为空!' }]}
                            />
                            <ProFormSelect
                                name="itemType"
                                label="类型："
                                placeholder="请选择"
                                options={[
                                    {
                                        label:'人事成本',value:1
                                    },
                                    {
                                        label:'变动成本',value:2
                                    },
                                    {
                                        label:'固定成本',value:3
                                    }
                                ]}
                                rules={[{ required: true, message: '类型不能为空!' }]}
                            />
                            <ProFormRadio.Group
                                name="summaryFlag"
                                label="汇总："
                                options={[
                                    {
                                        label: '是',
                                        value: 1,
                                    },
                                    {
                                        label: '否',
                                        value: 0,
                                    }
                                ]}
                                placeholder="请选择"
                            />
                            <ProFormRadio.Group
                                name="ctrlFlag"
                                label="可控："
                                options={[
                                    {
                                        label: '是',
                                        value: 1,
                                    },
                                    {
                                        label: '否',
                                        value: 0,
                                    }
                                ]}
                                placeholder="请选择"
                            />
                            <ProFormRadio.Group
                                name="statFlag"
                                label="统计："
                                options={[
                                    {
                                        label: '是',
                                        value: 1,
                                    },
                                    {
                                        label: '否',
                                        value: 0,
                                    }
                                ]}
                                placeholder="请选择"
                            />
                            <ProFormDigit
                                name="seqNo"
                                label="序号："
                                rules={[{ required: true, message: '序号不能为空!' }]}
                            />
                        </>
                    )
                }



            </ModalForm>
        )
    }

    const tableDataSearchHandle = (paramName: string) => {


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



    const onTabChange = (activeKey: string) => {
        set_currentSelectedTabKey(activeKey);
    }

    useEffect(() => {
        tableRef.current?.reload();
        if (currentSelectedTabKey == '1') {
            set_columns(incomeColumns)
        }
        if (currentSelectedTabKey == '2') {
            set_columns(costCloumns)
        }
    }, [currentSelectedTabKey])


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

    return (
        <BMSPagecontainer className='CostIncomeProjectSet' title={false}>
            <Tabs
                defaultActiveKey="1"
                onChange={onTabChange}
                items={[
                    {
                        label: `收入项目`,
                        key: '1',
                    },
                    {
                        label: `成本项目`,
                        key: '2',
                    },
                ]}
            />
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                        <Input placeholder={'请输入项目名称'} allowClear
                            suffix={
                                <IconFont type="iconsousuo" onClick={() => tableDataSearchHandle('name')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        name: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

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

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    {/* <span className='getDataBtn' onClick={() => getDataBySQL()}>获取</span> */}
                    <UpDataActBtn record type='ADD' />
                </div>
            </div>
            <div style={{ marginTop: 16 }}>
                <BMSTable columns={columns as ProColumns[]} pagination={currentSelectedTabKey == '2'&&false} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </BMSPagecontainer>
    )
}
