/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-07-28 11:33:30
 * @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 { createFromIconfontCN, MenuOutlined } from '@ant-design/icons';
import { ActionType, arrayMoveImmutable, ProFormSelect, useRefFunction } from '@ant-design/pro-components';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { InputNumber, Dropdown, Input, MenuProps, message, Modal, Popconfirm, Space, Form, Table, Tabs } from 'antd';

import { TransferItem, TransferProps } from 'antd/es/transfer';
import React, { Key } from 'react';
import { useEffect, useImperativeHandle, useRef, useState } from 'react';

import { getMedicalGroup, getEmpTableDataFromMedicalGroup, addMedicalGroup, editMedicalGroup, delLeftReportData, addMedicalGroupEmp, updateMedicalGroupEmpInfo, delTableData, getAllUnitList, addGroupItemList, editGroupItemList } from './service';

import './style.less';
import '../../../../utils/zhongtaiB';
import '../../../../utils/zhongtaiA'
import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
import { getSecondaryProjectDistriData } from '../secondaryProjectDistribute/service';

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

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



const DragHandle = SortableHandle(() => (
    <MenuOutlined style={{ cursor: 'grab', color: '#999' }} />
));

let _currentSelectedType: { groupCode: any; } | undefined = undefined;


const SecondaryDistriGroupSet = () => {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();

    const [typeList, set_typeList] = useState<any[]>([]);
    const [showTypeListArr, set_showTypeListArr] = useState<any[]>([]);
    const [currentSelectedType, set_currentSelectedType] = useState<any | undefined>(undefined);

    const [tableSelectedKeys, set_tableSelectedKeys] = useState<any[]>([]);

    const [selectedAddKeys, set_selectedAddKeys] = useState<Key[]>([]);

    const [ifShowModal, set_ifShowModal] = useState(false);

    const [currentEditLeftData, set_currentEditLeftData] = useState<any | undefined>(undefined);

    const [ifEditTable, set_ifEditTable] = useState(false);

    const [currentTabKey, set_currentTabKey] = useState('1');

    const tableRef = useRef<ActionType>();

    const [dataSource,set_dataSource] = useState<any[]>([]);

    const ref = React.createRef<{ save: any; getSelectedKeys: any }>();

    const [tableColumns,set_tableColumns] = useState<ProColumns[]>([]);

    const [tableDataSearchKeywords,set_tableDataSearchKeywords] = useState('');


    const columnOne:ProColumns[] = [

        {
            title: '核算单元名称',
            ellipsis: true,
            dataIndex: 'unitName',

        },
        {
            title: '核算单元代码',
            dataIndex: 'unitCode',

        },
        {
            title: '职类',
            dataIndex: 'unitTypeName',

        },
        {
            title: '操作',
            key: 'option',
            valueType: 'option',
            render: (_: any, record: any) => {
                console.log({currentSelectedType});
                return [
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableDataHanfle(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },
    ];
    const columnTwo = [
        {
            title: '排序',
            dataIndex: 'sort',
            width: 60,
            className: 'drag-visible',
            render: () => <DragHandle />,
        },
        {
            title: '项目名称',
            ellipsis: true,
            dataIndex: 'itemName',

        },
        {
            title: '占比',
            dataIndex: 'weightPercent',

        },
        {
            title: '评价方式',
            dataIndex: 'evaluationName',

        },
        {
            title: '来源',
            dataIndex: 'sourceName',

        }
    ]

    


    const getTableData = async (params?:any)=>{
        if(!_currentSelectedType)return false;
        const { groupCode:secondGroupCode } = _currentSelectedType;
        let keywords=params?params.keywords:''
        
        if (secondGroupCode) {
            const resp = await getEmpTableDataFromMedicalGroup(currentTabKey == '1'?{secondGroupCode,unitName:keywords}:{secondGroupCode,itemName:keywords},currentTabKey == '1'?1:2);
            if (resp) {
                set_dataSource(resp);
            }
        }
    }

    const switchChangeHandle = async (checked: boolean, record: any, key: string) => {
        const result = { ...record, medicalGroupManager: checked ? 1 : 0 }
        const resp = await updateMedicalGroupEmpInfo(result);
        if (resp) {
            tableRef.current?.reload();
        }
    }

    const delTableDataHanfle = async (record?: { id: number; }) => {
        const resp = await delTableData(record ? [record.id] : [...tableSelectedKeys]);
        console.log({currentSelectedType});
        if (resp) {
            set_tableSelectedKeys([]);
            getTableData();
        }
    }

    //获取左侧数据
    const getPageLeftData = async () => {
        const resp = await getMedicalGroup();

        if (resp) {

            set_typeList(resp);
            set_showTypeListArr(resp);
        }
    }


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

        // console.log({formVal,type});

        if (type == 'ADD_LEFTDATA') {
            const resp = await addMedicalGroup({
                groupName: formVal.groupName,
                description: formVal.description,
            });
            if (resp) {
                getPageLeftData();
            }
        }



        if (type == 'EDIT_LEFTDATA') {
            const resp = await editMedicalGroup({
                id: formVal.id,
                groupName: formVal.groupName,
                description: formVal.description
            });
            if (resp) {
                getPageLeftData();
            }
        }

        return true;

    }

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

        const getTrriger = () => {
            if (type == 'ADD') {
                return <span className='add'>添加</span>
            }
            if (type == 'EDIT') {
                return <a key="edit" >编辑</a>
            }
            if (type == 'ADD_LEFTDATA') {
                return (
                    <div className='add'>
                        <img src={require('../../../../../static/addIcon_black.png')} alt="" />
                    </div>
                )
            }
            if (type == 'EDIT_LEFTDATA') {
                return <a key="edit" >编辑</a>
            }
        }

        return (
            <ModalForm
                title={type == 'ADD_LEFTDATA' ? `新增分组` : `编辑分组`}
                width={352}
                initialValues={type == 'EDIT_LEFTDATA' ? { ...record } : {}}
                trigger={
                    getTrriger()
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT_LEFTDATA' ? { ...record, ...val } : val, type);
                }}
            >

                <ProFormText
                    label='分组名称：'
                    name='groupName'
                    rules={[{ required: true, message: '名称不能为空!' }]}
                />
                <ProFormTextArea
                    label='说明：'
                    name='description'
                />
            </ModalForm>
        )
    }


    interface TableSelecterProps extends TransferProps<TransferItem> {
        tableSelecterColumn: any[];
        record: any
    }


    const tableSelecterUnitColumn: any[] =  [
        {
            title: '核算单元名称',
            dataIndex: 'unitName',
        },
        {
            title: '职类',
            dataIndex: 'unitTypeName',
        },
    ];

    const addGroupEmpHandle = () => {

        const ref = React.createRef<{ save: any; getSelectedKeys: any }>();
      
        set_ifShowModal(true);
    }

    const TableSelecter = React.forwardRef(({ tableSelecterColumn, record }: TableSelecterProps, ref) => {

        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
        const [showList, set_showList] = useState<any[]>([]);

        //获取表格数据
        const getFuncList = async () => {
            const resp = await getAllUnitList({ secondGroupCode: currentSelectedType.groupCode });
            if (resp) {
                set_datasource(resp);
                set_showList(resp);
            }
        }


        const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
            setSelectedKeys([...newSelectedRowKeys]);

        };

        const save = async () => {
            const result = {
                secondGroupCode: currentSelectedType.groupCode as string,
                unitCodeList: selectedKeys
            };

            const resp = await addMedicalGroupEmp(result);

            if (resp) {
                message.success('添加成功！');
                set_ifShowModal(false);
                getTableData();
                
            }
        }

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

        return (
            <div className='TableSelecter'>
                <Input placeholder={'请输入'} allowClear
                    suffix={
                        <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />
                    }
                    style={{ marginBottom: 8 }}
                    onChange={(e) => {
                        if (e.target.value.length != 0) {
                            const result = datasource.filter(item => item.unitName.indexOf(e.target.value) != -1);
                            set_showList(result);
                        } else {
                            set_showList(datasource);
                        }

                    }}

                />
                <BMSTable columns={tableSelecterColumn}
                    options={{
                        density: true,
                        setting: {
                            listsHeight: 100,
                        },
                    }}
                    rowKey='code'
                    // scroll={{y:300}}
                    tableAlertRender={false}
                    rowSelection={{
                        // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                        // 注释该行则默认不显示下拉选项
                        selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                        onChange: onSelectChange,
                    }}
                    pagination={{ showSizeChanger: false, pageSize:9, simple: true, showTitle: false }}
                    dataSource={showList}
                />
                <div className='footer'>
                    <span className='cancel' onClick={() => set_ifShowModal(false)}>取消</span>
                    <span className='ok' onClick={() => save()}>{`确认(${selectedKeys.length > 0 && selectedKeys.length})`}</span>
                </div>
            </div>

        )
    });

    const moreItems: MenuProps['items'] = [
        {
            key: '1',
            label: <UpDataActBtn key={'act'} record={currentEditLeftData} type='EDIT_LEFTDATA' />,
        },
        {
            key: '2',
            label: (
                <a onClick={async (e) => {
                    e.preventDefault();
                    const resp = await delLeftReportData(currentEditLeftData.id);
                    if (resp) {
                        getPageLeftData();
                    }
                }}>
                    删除
                </a>
            ),
        }
    ];

    
    const onTableSelectChange = (newSelectedRowKeys: React.Key[]) => {
        set_tableSelectedKeys([...newSelectedRowKeys]);
    };

    const updateSecondaryDistriItemSet = async (itemList:any[],type:'ADD'|'EDIT')=>{

           if(type == 'ADD'){
            const totalWeight = itemList.reduce((prev,cur)=>{
                console.log({'prev':prev,'cur.weight':cur.weight})
                return (prev)+cur.weight
            },0);
            console.log({totalWeight,itemList});
            if(totalWeight.toFixed(2) != 1){
                  message.error('占比总和必须等于1！');
                  return false
            }
            const result = {
             secondGroupCode:currentSelectedType.groupCode,
             itemList:itemList.map((a:any)=>({
                 secondItemCode:a.secondItemCode?a.secondItemCode:a.itemCode,
                 weight:a.weight
             }))
            }
            const resp = await addGroupItemList(result);
            if(resp){
                 getTableData();
                 return true;
            }
            return false
           }

           if(type == 'EDIT'){
               const resp = await editGroupItemList(itemList);
               if(resp){
                  getTableData();
               }
           }
           
    }

    const AddItemComponent = () => {

   
        const [scoreList, set_scoreList] = useState<any[]>([]);
        const [scoreInitList, set_scoreInitList] = useState({});

        const addIndicator = () => {

            const key = Math.random();

            const temp = [...scoreList, { tempId: key, id: key, [`secondItemCode${key}`]: '', [`weight${key}`]: '' }];

            set_scoreInitList({ ...scoreInitList, [`secondItemCode${key}`]: '', [`weight${key}`]: '' });

            set_scoreList([...temp]);

        }

        const delGroupIndic = (data: any, index: number) => {
            let temp = [...scoreList];
            let defaultFormData: { [key: string]: any } = {};
            const result = temp.filter((a: any) => a.id != data.id);
            result.forEach((a: any) => {
                defaultFormData[`secondItemCode${a.id}`] = a.secondItemCode;
                defaultFormData[`weight${a.id}`] = a.weight;
            });

            set_scoreInitList({ ...defaultFormData });
            set_scoreList([...result]);
        }

        
        useEffect(() => {
            let defaultFormData: { [key: string]: any } = {};
                if (true) {
                    const defaultVal = dataSource.map((a: any) => {
                        defaultFormData[`secondItemCode${a.id}`] = a.itemCode;
                        defaultFormData[`weight${a.id}`] = a.weight;
                        return { ...a, tempId: Math.random() }
                    });

                    set_scoreInitList({ ...defaultFormData });
            
                    set_scoreList([...defaultVal]);
                }    
        },[]);

        return (
            <ModalForm
                title={`二次分配项目设置(${currentSelectedType.groupName})`}
                className='SecondaryDistriGroupSet-ModalForm'
                width={355}
                initialValues={{...scoreInitList}}
                trigger={
                    <a className='score'>添加</a>
                }
                onFinish={(val) => {
                    return updateSecondaryDistriItemSet(scoreList,'ADD');
                }}
                modalProps={{ destroyOnClose: true }}
            >
                {
                    (
                        <div>
                            {
                                scoreList.map((item: any, index: number) => {

                                    return (
                                        <div className='item' key={index}>
                                            <ProFormSelect label="管理指标：" width={160} 
                                                name={`secondItemCode${item.id}`}
                                                 request={async () => {
                                                    const resp = await getSecondaryProjectDistriData({pageSize:1000,current:1});
                                                    if (resp) {
                                                        return resp.list.map((a: any) => ({
                                                            label: a.name,
                                                            value: a.code
                                                        }))
                                                    }
                                                    return []

                                                }}
                                                fieldProps={{
                                                    //   labelInValue:true,
                                                    onChange(value, option: any) {
                                                        // console.log({value,option});
                                                        const temp = [...scoreList];
                                                        const newArr = temp.map((a: any) => {
                                                            if (a.id == item.id) {
                                                                return { ...a, secondItemCode: value, secondItemName: option.label }
                                                            }
                                                            return a
                                                        });

                                                        set_scoreList([...newArr]);
                                                    },
                                                }}
                                            />
                                            <Form.Item name={`weight${item.id}`} label='占比：'>
                                                <InputNumber
                                                    style={{ width: 120, height: 24, position: 'relative', top: 0 }}
                                                    onChange={(value) => {
                                                        //console.log({value,index,indicatorData});
                                                        const temp = [...scoreList];
                                                        const newArr = temp.map((a: any) => {
                                                            if (a.id == item.id) {
                                                                return { ...a, weight: value }
                                                            }
                                                            return a
                                                        });

                                                        set_scoreList([...newArr]);
                                                    }}
                                                />
                                            </Form.Item>
                                            <span className='delIcon' onClick={() => delGroupIndic(item, index)}><IconFont   type="iconshanchu" /></span>
                                        </div>
                                    )
                                })
                            }
                            <div className='addBtn' onClick={() => addIndicator()}>
                                <AddIconFont type="icon-zengjia" style={{ color: '#3376FE' }} /><span>增加一行</span>
                            </div>
                        </div>
                    )
                }
            </ModalForm>
        )
    }

    const onTabChange = (activeKey:string) => {
        set_currentTabKey(activeKey);
        activeKey == '1'?set_tableColumns(columnOne):set_tableColumns(columnTwo);
    }

    
    
    const SortableItem = SortableElement((props: any) => <tr {...props} />);
    const SortContainer = SortableContainer((props: any) => <tbody {...props} />);

    const onSortEnd = useRefFunction(
        ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
            if (oldIndex !== newIndex) {
                const newData = arrayMoveImmutable({
                    array: [...dataSource],
                    fromIndex: oldIndex,
                    toIndex: newIndex,
                }).filter((el) => !!el);
                const updatedSortArr = newData.map((item: any, index: number) => ({ ...item, sort: index }))
                set_dataSource([...updatedSortArr]);
                updateSecondaryDistriItemSet(updatedSortArr,'EDIT');
            }
        },
    );

    const DraggableContainer = (props: any) => (
        <SortContainer
            useDragHandle
            disableAutoscroll
            helperClass="row-dragging"
            onSortEnd={onSortEnd}
            {...props}
        />
    );

    const DraggableBodyRow = (props: any) => {
        const { className, style, ...restProps } = props;
        // function findIndex base on Table rowKey props and should always be a right array index
        const index = dataSource.findIndex(
            (x) => x.id === restProps['data-row-key'],
        );

        return <SortableItem index={index} {...restProps} />;
    };

    useEffect(() => {
        _currentSelectedType = currentSelectedType;
        if (currentSelectedType) {
            set_tableDataFilterParams({ ...tableDataFilterParams, secondGroupCode: currentSelectedType.groupCode });
            getTableData();
            
        }
    }, [currentSelectedType])

    useEffect(() => {
        if (showTypeListArr.length > 0) {
            set_currentSelectedType(showTypeListArr[0]);
            //set_tableDataFilterParams({ ...tableDataFilterParams, medicalGroupCode: showTypeListArr[0].code });
        }
    }, [showTypeListArr]);

    useEffect(()=>{
        getPageLeftData();
    },[currentTabKey]);

    useEffect(()=>{
          
    },[tableDataFilterParams])


    useEffect(() => {
        getPageLeftData();
        set_tableColumns(columnOne);
    }, [])



    return (
        <BMSPagecontainer title={false} className='SecondaryDistriGroupSet'>

            <ModalForm title={'新增分组核算单元'} width={400} 
            submitter={{
                render: (props, defaultDoms) => []
            }} 
            open={ifShowModal} modalProps={{
                closable: false,
            }}>
                <TableSelecter
                    ref={ref}
                    record={undefined}
                    tableSelecterColumn={tableSelecterUnitColumn}
                ></TableSelecter>
            </ModalForm>

            <div className='left'>
                <div className='toolbar'>
                    <Input placeholder={'请输入分组名称'} allowClear
                        suffix={
                            <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" />
                        }
                        style={{ width: 156 }}
                        onChange={(e) => {
                            const result = typeList.filter(item => item.groupName.indexOf(e.target.value) != -1);
                            set_showTypeListArr(result);
                        }}
                    />

                    <UpDataActBtn key={'act'} record={undefined} type='ADD_LEFTDATA' />

                </div>

                <div className='wrap'>
                    {
                        showTypeListArr.map((item, index) => {
                            return (
                                <div className={currentSelectedType ? currentSelectedType.id == item.id ? 'type on' : 'type' : 'type'}
                                    key={index}
                                    onClick={() => {
                                        if (ifEditTable) {
                                            //编辑状态还未保存
                                            Modal.confirm({
                                                title: '当前存在编辑未保存，请保存后再操作！',
                                                okText: '放弃编辑',
                                                cancelText: '继续编辑',
                                                onOk(...args) {
                                                    set_ifEditTable(false);
                                                    set_currentSelectedType(item);

                                                },
                                            })
                                        } else {
                                            set_currentSelectedType(item)
                                        }
                                    }}
                                >
                                    <div className='content'>
                                        <div className='name'>{item.groupName}</div>
                                    </div>

                                    <Dropdown menu={{ items: moreItems }} placement="bottom" onOpenChange={(bool) => { bool && set_currentEditLeftData(item) }}>
                                        <div className='more'>
                                            <img src={require('../../../../../static/more_point_gray.png')} alt="" />
                                        </div>
                                    </Dropdown>
                                </div>
                            )
                        })
                    }
                </div>
            </div>
            <div className='right'>
                <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={currentTabKey == '1'?'核算单元名称':'请输入项目名称'} allowClear
                                suffix={
                                    <IconFont style={{ color: '#99A6BF' }} type="iconsousuo" onClick={() => getTableData({keywords:tableDataSearchKeywords})} />
                                }
                                onChange={(e) => {
                                    set_tableDataSearchKeywords(e.target.value);
                                    if (e.target.value.length == 0) {
                                        getTableData({keywords:''});
                                    }
                                }}
                                onPressEnter={(e) => {
                                    getTableData({keywords:tableDataSearchKeywords});
                                }}

                            />
                        </div>
                    </div>
                    <div className='btnGroup'>
                        {currentTabKey == '1'?<span className='manaBtn' onClick={() => addGroupEmpHandle()}>添加</span>:<AddItemComponent />}
                    </div>
                </div>
                <div style={{ marginTop: 16 }}>
                    {(currentSelectedType&&currentTabKey) && <BMSTable actionRef={tableRef} columns={tableColumns}
                        rowKey='id'
                        pagination={false}
                        tableAlertRender={false}
                        rowSelection={ currentTabKey == '1'?{
                            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                            // 注释该行则默认不显示下拉选项
                            //selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT, Table.SELECTION_NONE,],
                            onChange: onTableSelectChange,

                        }:false}
                        tableAlertOptionRender={() => {
                            return (

                                <Space size={16}>
                                    <Popconfirm
                                        title="是否确认删除？"
                                        key="del"
                                        onConfirm={() => delTableDataHanfle()}
                                    >
                                        <a>批量删除</a>
                                    </Popconfirm>
                                </Space>
                            );
                        }}
                        params={tableDataFilterParams}
                        dataSource={dataSource}
                        //request={currentTabKey == '1'?(params, sort, filter) => getTableData(params, sort, filter):undefined}
                        components={currentTabKey == '2' ? {
                            body: {
                                wrapper: DraggableContainer,
                                row: DraggableBodyRow,
                            },
                        } : undefined}
                    />}
                </div>
            </div>
            {
                tableSelectedKeys.length > 0 && (
                    <div className='bottomToolbar'>
                        <span className='leftAccount'>已选择<a>{tableSelectedKeys.length}</a>项</span>
                        <div className='btnGroup'>
                            <span className='cancel' onClick={() => tableRef.current?.clearSelected && tableRef.current?.clearSelected()}>取消选择</span>
                            <Popconfirm
                                title="是否确认删除？"
                                key="del"
                                onConfirm={() => delTableDataHanfle()}
                            >
                                <span className='batchDel'>批量删除</span>
                            </Popconfirm>

                        </div>
                    </div>
                )
            }

        </BMSPagecontainer >
    )
}


export default SecondaryDistriGroupSet;
