/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-07-19 09:33:25
 * @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 } from '@ant-design/icons';

import { ActionType, ProFormRadio } from '@ant-design/pro-components';
import { ModalForm, ProFormCascader, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Modal, Popconfirm } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import Transfer, { TransferItem, TransferProps } from 'antd/es/transfer';
import { difference } from 'lodash';
import React, { useImperativeHandle } from 'react';
import { useEffect, useRef, useState } from 'react'

import { getData, getPositionDicData, savePositionLevel } from './service';

import './style.less';


export default function PositionLevelRateSet() {

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

    const columns = [
        
        {
            title: '岗位等级',
            dataIndex: 'positionLevelName',
        },
        {
            title: '分级系数',
            dataIndex: 'positionLevelRate',
        },
        {
            title: '岗位名称',
            width:500,
            ellipsis:true,
            dataIndex: 'position',
            render:(_:any,record:any)=>{
                   if(record.position){
                      return record.position.reduce((prev:any,cur:any)=>{
                            return `${prev?prev+'｜':''}${cur.name}`
                      },undefined)
                   }
                return ''
            }
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <a key={'option'} onClick={()=>selectpositionHandle(record)}>选择岗位</a>
                ]
            },
        },

    ];


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

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


    const transferTableColumn: any[] = [
        {
            title: '岗位名称',
            dataIndex: 'name',
            key: 'name',
            ellipsis:true

        },
        {
            title: '岗位代码',
            width: 120,
            dataIndex: 'code',
            key: 'code',
            ellipsis: true
        },
    ];


    const selectpositionHandle = (record:any) => {

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

        Modal.confirm({
            title: `选择岗位`,
            icon: <></>,
            width: 750,
            okText: '确定',
            cancelText: '取消',
            centered:true,
            content: <TableTransfer
                ref={ref}
                record={record}
                leftColumns={transferTableColumn}
                rightColumns={transferTableColumn}

            ></TableTransfer>,
            onOk: () => {
                return ref.current && ref.current.save();
            }
        })
    }

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


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

        //获取岗位字典数据
        const getFuncList = async () => {
            const resp = await getPositionDicData();
            if (resp) {

                const defaultSelctedkeys = record.position?record.position.map((item: any) => item.code):[];
                set_datasource([...resp,...(record.position?record.position:[])]);
                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 resp = await savePositionLevel({
                    positionLevelCode:record.positionLevelCode,
                    positionLevelName:record.positionLevelName,
                    positionLevelRate:record.positionLevelRate,
                    position:needData
                });
                
                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.name!.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"
                            pagination={{showSizeChanger:false,simple:true,pageSize:9,showTitle:false,showTotal:()=>false}}
                            rowKey={'code'}
                            tableAlertRender={false}
                            
                            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 getTableData = async () => {
        const resp = await getData();
        if (resp) {
            return {
                data: resp,
                success: true,
            }
        }
        return []
    }

  
    return (
        <BMSPagecontainer className='PositionLevelRateSet' title={false}>
            <div className='tableTitle'>岗位等级系数设定</div>
            <div style={{ marginTop: 16 }}>
                <BMSTable columns={columns as ProColumns[]} actionRef={tableRef}  rowKey='positionLevelCode'  params={tableDataFilterParams} request={(params) => getTableData()} />
            </div>
        </BMSPagecontainer>
    )
}
