/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-08-27 17:40:13
 * @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, BMSTablePageDefaultConfig } from '@/components/BMSTable';
import { deepEqual } from '@/utils/tooljs';
import { createFromIconfontCN } from '@ant-design/icons';
import { ActionType } from '@ant-design/pro-components';
import { ModalForm, ProFormDigit, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Modal, Popconfirm, Table } from 'antd';
import { ColumnsType, TableRowSelection } from 'antd/es/table/interface';
import Transfer, { TransferItem, TransferProps } from 'antd/es/transfer';
import React from 'react';
import { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { getAllUnit } from '../indicGroupWeightSet/service';

import difference from 'lodash/difference';

import {  copyGroupUnit, delData, editUnitIndicTargetTbaleData, getUnitGroupList, getUnitIndicTargetTableData, getUnitUnderGroupById } from './service';


import './style.less';

import '../../../../utils/zhongtaiB'
const IconFont = createFromIconfontCN({
    scriptUrl: '',
});



const UnitIndicTargetSet = () => {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const [tableColumn, set_tableColumn] = useState<ProColumns[] | any[]>([]);
    const [typeList, set_typeList] = useState<any[]>([]);
    const [showTypeListArr, set_showTypeListArr] = useState<any[]>([]);
    const [currentSelectedType, set_currentSelectedType] = useState<any | undefined>(undefined);

    const tableRef = useRef<ActionType>();



    const getTableData = async (params: any) => {
        const { groupId } = params;
        if (groupId) {
            const resp = await getUnitIndicTargetTableData(params);
            if (resp) {

                const { title, unitWeightData } = resp;
                const columns = title.map((item: any) => {

                    return {
                        title: item.name,
                        dataIndex: `${item.code}`,
                        key: `${item.code}`,
                        // render:(_:number,record:any)=>{
                        //      return `${Number(_ * 100).toFixed(2)}%`
                        // }
                        // width: 140,

                    }
                });
                set_tableColumn([{
                    title: '核算单元',
                    dataIndex: 'unitName',
                    fixed:'left'

                }, ...columns, {
                    title: '操作',
                    key: 'option',
                    width: 120,
                    fixed:'right',
                    valueType: 'option',
                    render: (_: any, record: any) => {
                        return [
                            <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                            <a key={'copy'} onClick={()=>copyHandle(record)}>复制</a>
                        ]
                    },
                }]);

                const data = unitWeightData.map((item: any) => {

                    let rowData: { [key: string]: any } = {};

                    for (let index = 0; index < item.value.length; index++) {

                        for (const key in item.value[index]) {
                            if (key == 'code') {
                                rowData[`${item.value[index][`code`]}`] = item.value[index][`target`];
                                rowData[`targetValue${item.value[index][`code`]}`] = item.value[index][`targetValue`]    
                            }
                        }
                    }

                    return { ...item, ...rowData, columns }
                });
    
                return {
                    data,
                    success: true
                }

            }
            return []
        }
        return []
    }

    //获取左侧单元
    const getTypeList = async () => {
        const resp = await getUnitGroupList();
        if (resp) {
            set_typeList(resp);
            set_showTypeListArr(resp);
        }
    }


    const updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {
        
        const temp = formVal.columns.map((a:any)=>{
              return {
                code:a.key,
                targetValue:formVal[`targetValue${a.key}`],
                
              }
        })
        
        if (type == 'EDIT') {
            const result = {
                unitCode:formVal.unitCode,
                unitName:formVal.unitName,
                value:temp
            }
            const resp = await editUnitIndicTargetTbaleData(result);
            if (resp) {
                tableRef.current?.reload();
            }
        }

        return true;

    }

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

        return (
            <ModalForm
                title={`设定指标目标值（${record.unitName}）`}
                width={352}
                initialValues={type == 'EDIT' ? { ...record } : { }}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : val, type);
                }}
            >
                {
                    record.value.map((item:any, index:number) => {
                        const label = record.columns.filter((a:ProColumns)=>a.key == item.code);
                      
                        if(label.length>0){
                            return (
                                <ProFormDigit
                                    key={index}
                                    name={`targetValue${item.code}`}
                                    label={`${label[0].title}`}
                                    placeholder="请输入"
                                    rules={[{ required: true, message:`请填写${label[0].title}` }]}
    
                                />
                            )
                        }
                        
                    })
                }
            </ModalForm>
        )
    }
     


    interface DataType {
        key: string;
        title: string;
        description: string;
        disabled: boolean;
        tag: string;
    }

    interface TableTransferProps extends TransferProps<TransferItem> {
        dataSource: DataType[];
        leftColumns: ColumnsType<DataType>;
        rightColumns: ColumnsType<DataType>;
        record: any
    }
    

    const transferTableColumn:any[] = [
        {
            title: '核算单元',
            dataIndex: 'unitName',
            key: 'unitName',

        },
        {
            title: '职类',
            dataIndex: 'unitType',
            key: 'unitType',
            render: (_: any, record: any) => {
                switch (parseInt(record.unitType)) {
                    case 1:
                        return '临床'
                        break;
                    case 2:
                        return '医技'
                        break;
                    case 3:
                        return '护理'
                        break;
                    case 6:
                        return '行政后勤'
                        break;
                    default:
                        break;
                }
            }
        },
    ];

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

        Modal.confirm({
            title: `复制单元考核目标设定信息（${record.unitName}）`,
            icon: <></>,
            width: 690,
            okText: '确定',
            cancelText: '取消',
            content: <TableTransfer
                ref={ref}
                record={record}
                leftColumns={transferTableColumn}
                rightColumns={transferTableColumn} dataSource={[]}
            ></TableTransfer>,
            onOk: () => {
                return ref.current && ref.current.save();
            }
        })
    }

    const TableTransfer = React.forwardRef(({ leftColumns, rightColumns, record, ...restProps }: TableTransferProps, ref) => {

        const [_data, _set_data] = useState<any>();
        const [targetKeys, setTargetKeys] = useState<string[]>([]);
        const [datasource, set_datasource] = useState<any[]>([]);
        const [selectedKeys, setSelectedKeys] = useState<string[]>([]);

        //获取单元
        const getFuncList = async () => {
            const resp = await getAllUnit(currentSelectedType.id);
            if (resp) {

                set_datasource(resp);

                if (record && record.unitInfoVos) {

                    const defaultSelctedkeys = record.unitInfoVos.map((item: any) => item.unitCode);

                    setTargetKeys(defaultSelctedkeys);
                }

            }
        }

        const onChange = (nextTargetKeys: string[]) => {
            setTargetKeys(nextTargetKeys);
        };

        const onSelectChange = (sourceSelectedKeys: string[], targetSelectedKeys: string[]) => {
            //console.log('sourceSelectedKeys:', sourceSelectedKeys,'targetSelectedKeys:',targetSelectedKeys);
            setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
        };

        useImperativeHandle(ref, () => ({
            save: async () => {

                const needData = datasource.filter(item => targetKeys.includes(item.code));

                const result = needData.map(a=>({unitCode:a.code,unitName:a.unitName}));

                // console.log({result,record});
        
                const resp = await copyGroupUnit({
                    unitInfos:result,
                    value:record.value
                });
                if (resp) {
                    message.success('操作成功！');
                    tableRef.current?.reload();
                }
            }
        }));

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

        return (
            <Transfer className='TableTransfer' showSearch
                titles={['待选项', '已选项']}
                locale={{
                    itemUnit: '项',
                    itemsUnit: '项',
                    searchPlaceholder: '请输入'
                }}
                onChange={onChange}
                onSelectChange={onSelectChange}
                dataSource={datasource}
                rowKey={record => record.code}
                targetKeys={targetKeys}
                selectedKeys={selectedKeys}
                filterOption={(inputValue, item) => {
                    return item.unitName!.indexOf(inputValue) !== -1

                }}
            >
                {({
                    direction,
                    filteredItems,
                    onItemSelectAll,
                    onItemSelect,
                    selectedKeys: listSelectedKeys,
                    disabled: listDisabled,
                }) => {

                    // console.log({ filteredItems, listSelectedKeys,direction });
                    const columns = direction === 'left' ? leftColumns : rightColumns;

                    const rowSelection: TableRowSelection<TransferItem> = {
                        getCheckboxProps: (item) => ({ disabled: listDisabled || item.disabled }),
                        onSelectAll(selected, selectedRows) {
                            const treeSelectedKeys = selectedRows.map(({ code }) => code);
                            const diffKeys = selected
                                ? difference(treeSelectedKeys, listSelectedKeys)
                                : difference(listSelectedKeys, treeSelectedKeys);
                            onItemSelectAll(diffKeys as string[], selected);
                        },
                        onSelect({ code }, selected) {
                            onItemSelect(code as string, selected);
                        },
                        selectedRowKeys: listSelectedKeys,
                    };

                    return (
                        <BMSTable
                            rowSelection={rowSelection}
                            columns={columns as TransferItem[]}
                            dataSource={filteredItems}
                            size="small"
                            rowKey={'code'}
                            scroll={{y:345}}
                            tableAlertRender={false}
                            pagination={{simple:true,pageSize:10}}
                            style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                            onRow={({ code, disabled: itemDisabled }) => ({
                                onClick: () => {
                                    if (itemDisabled || listDisabled) return;
                                    onItemSelect(code as string, !listSelectedKeys.includes(code as string));
                                },
                            })}
                        />
                    );
                }}
            </Transfer>
        )
    });

    const tableDataSearchHandle = (paramName: string) => {


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

    useEffect(() => {
        if (currentSelectedType) {
            set_tableDataFilterParams({ ...tableDataFilterParams, groupId: currentSelectedType.id })
        }
    }, [currentSelectedType])

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

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



    return (
        <BMSPagecontainer title={false} className='UnitIndicTargetSet'>
            <div className='left'>
                <Input placeholder={'请输入'} allowClear
                    suffix={
                        <IconFont type="iconsousuo" />
                    }
                    onChange={(e) => {
                        const result = typeList.filter(item => item.groupName.indexOf(e.target.value) != -1);
                        set_showTypeListArr(result);
                    }}

                />
                <div className='wrap'>
                    {
                        showTypeListArr.map((item, index) => {
                            return (
                                <div className={currentSelectedType ? currentSelectedType.id == item.id ? 'type on' : 'type' : 'type'}
                                    key={index}
                                    onClick={() => set_currentSelectedType(item)}
                                >{item.groupName}</div>
                            )
                        })
                    }
                </div>
            </div>
            <div className='right'>
                <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('unitCode')} />
                                }
                                onChange={(e) => {
                                    set_tableDataSearchKeywords(e.target.value);
                                    if (e.target.value.length == 0) {
                                        set_tableDataFilterParams({
                                            ...tableDataFilterParams,
                                            unitCode: ''
                                        });
                                    }
                                }}
                                onPressEnter={(e) => {

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

                            />
                        </div>
                    </div>
                    <div className='btnGroup'>
                        {/* <UpDataActBtn record type='ADD' /> */}
                    </div>
                </div>
                <div style={{ marginTop: 16 }}>
                    {currentSelectedType && <BMSTable scroll={{x:872,y:tableColumn.length * 150}} actionRef={tableRef} columns={tableColumn} rowKey='unitCode' params={tableDataFilterParams} request={(params) => getTableData(params)} />}
                </div>
            </div>
        </BMSPagecontainer>
    )
}


export default UnitIndicTargetSet;
