/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-06-15 17:50:40
 * @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 } from '@ant-design/pro-components';

import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Modal, Popconfirm, Switch } 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, { Key, useImperativeHandle } from 'react';
import { useEffect, useRef, useState } from 'react'

import { getViewUnitTableData, getAllCheckUnit, saveCheckViewUnit, postCheckViewAll } from './service';

import './style.less';
import '../../../../utils/zhongtaiB';

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


export default function ViewUnitPermSet() {

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

    const columns = [

        {
            title: '工号',
            dataIndex: 'account',
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '职务',
            dataIndex: 'jobTitleName',
        },
        {
            title: '职称',
            dataIndex: 'titleName',
        },
        {
            title: '岗位',
            dataIndex: 'positionName',
        },
        {
            title: '检视单元',
            width: 300,
            ellipsis: true,
            dataIndex: 'unitList',
            render: (_: any, record: any) => {
                if (record.unitList) {
                    return record.unitList.reduce((prev: any, cur: any) => {
                        if (cur.unitCode != '0') {
                            return `${prev ? prev + '｜' : ''}${cur.unitName}`
                        } else {
                            return <span style={{ color: '#FF8C19' }}>{cur.unitName}</span>
                        }

                    }, undefined)
                }
                return ''
            }
        },
        {
            title: '操作',
            key: 'option',
            width: 200,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <a key={'option'} onClick={() => selectpositionHandle(record)}>选择单元</a>,
                    <a key={'viewAll'} onClick={() => checkViewAllHandle(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: 'unitName',
        },
        {
            title: '职类',
            width: 120,
            dataIndex: 'unitTypeName',
            ellipsis: true
        },
    ];


    const selectpositionHandle = (record: any) => {

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

        Modal.confirm({
            title: `添加检视单元(${record.name})`,
            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 checkViewAllHandle = async (record: any) => {
        const resp = await postCheckViewAll(record.id);
        if (resp) {
            tableRef.current?.reload();
        }
    }

    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 getAllCheckUnit();
            if (resp) {

                const defaultSelctedkeys = record.unitList ? record.unitList.map((item: any) => item.unitCode) : [];
                const defalt = record.unitList ? record.unitList : [];
                set_datasource([...resp, ...defalt]);
                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 saveCheckViewUnit({
                    userId: record.id,
                    unitList: needData.map((a: any) => ({
                        unitCode: a.code as string,
                        unitName: a.unitName as string,
                        unitType: a.unitType as string
                    }))
                });

                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"
                            pagination={{ showSizeChanger: false,pageSize:9,simple:true,showTotal:()=>false }}
                            rowKey={'code'}
                            tableAlertRender={false}
                            style={{ pointerEvents: listDisabled ? 'none' : undefined }}
                            onRow={({ code, disabled: itemDisabled }) => ({
                                onClick: () => {
                                    if (itemDisabled || listDisabled) return;
                                    onItemSelect(code, !listSelectedKeys.includes(code));
                                },
                            })}
                        />
                    );
                }}
            </Transfer>
        )
    });


    const tableDataSearchHandle = (paramName: string) => {

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

    }


    const getTableData = async (params: any, sort: any, filter: any) => {
        const resp = await getViewUnitTableData({ ...params });
        if (resp) {
            return {
                data: resp.list,
                success: true,
                total: resp.totalCount,
                pageSize: resp.pageSize,
                totalPage: resp.totalPage,
            }
        }
        return []
    }


    return (
        <BMSPagecontainer className='ViewUnitPermSet' title={false}>
            <div className='tableToolbar'>
                <div className='search'>
                    <span>检索：</span><Input className='searchInput' allowClear placeholder="请输入工号、姓名" onChange={(e) => {
                        set_tableDataSearchKeywords(e.target.value);
                        if (e.target.value.length == 0) {
                            set_tableDataFilterParams({ ...tableDataFilterParams, name: '' });
                        }
                    }} suffix={
                        <IconFont style={{color:'#99A6BF'}} type="iconsousuo" onClick={() => tableDataSearchHandle('name')} />
                    }

                        onPressEnter={(e) => {

                            set_tableDataFilterParams({
                                ...tableDataFilterParams,
                                name: (e.target as HTMLInputElement).value
                            });
                        }}
                    />
                </div>
                <div className='btnGroup'>
                    <Switch size="small" onChange={(bool:boolean)=>set_tableDataFilterParams({...tableDataFilterParams,hide:bool?1:0})} />
                    <span style={{marginLeft:8}}>隐藏未设定人员</span>
                </div>
            </div>
            <div style={{ marginTop: 16 }}>
                <BMSTable columns={columns as ProColumns[]} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params, sort, filter) => getTableData(params, sort, filter)} />
            </div>
        </BMSPagecontainer>
    )
}
