/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-03-29 16:27:12
 * @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, ProForm, ProFormDigit, ProFormInstance, ProFormSelect } from '@ant-design/pro-components';
import { ModalForm, ProFormDependency, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Form, Input, InputNumber, message, Modal, Popconfirm, Table, Transfer } from 'antd';
import { DefaultOptionType } from 'antd/es/select';
import { ColumnsType, TableRowSelection } from 'antd/es/table/interface';
import { TransferItem, TransferProps } from 'antd/es/transfer';
import React, { useImperativeHandle } from 'react';
import { useEffect, useRef, useState } from 'react'
import { getManaIndicListData } from '../manaIndicItemSet/service';

import difference from 'lodash/difference';

import { addData, addIndicGroup, addUnitForGroup, delData, editData, getAllUnit, getData } from './service';

import './style.less';
import { omit } from 'lodash';

import { create, all } from 'mathjs'

const config = {
    number: 'bignumber',
    precision: 2
}
const math = create(all, config as any);


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

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



export default function IndicGroupWeightSet() {

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

    const [currentOperateRow, set_currentOperateRow] = useState<any | undefined>(undefined);  //当前操作的表格行数据

    const tableRef = useRef<ActionType>();




    const columns = [

        {
            title: '分组名称',
            dataIndex: 'groupName',
            width: 150
        },
        {
            title: '组内单元名称',
            dataIndex: 'unitInfoVos',
            width: 250,
            ellipsis: true,
            render: (_: any, record: any) => {


                if (record.unitInfoVos && typeof record.unitInfoVos == 'object') {
                    return record.unitInfoVos.reduce((prev: any, cur: any) => `${prev.length > 0 ? prev + ' | ' : prev}${cur.unitName}`, '')
                }
                return ''

            }
        },
        {
            title: '管理指标',
            ellipsis: true,
            width: 250,
            dataIndex: 'indicatorWeights',
            render: (_: any, record: any) => {


                if (record.indicatorWeights && typeof record.indicatorWeights == 'object') {
                    return record.indicatorWeights.reduce((prev: any, cur: any) => `${prev.length > 0 ? prev + ' | ' : prev}${cur.indicatorName}`, '')
                }
                return ''

            }
        },
        {
            title: '总分下限',
            dataIndex: 'floor',
            width: 80
        },
        {
            title: '总分上限',
            dataIndex: 'ceiling',
            width: 80
        },
        {
            title: '说明',
            dataIndex: 'depiction',
        },
        {
            title: '操作',
            key: 'option',
            width: 160,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <a key={'fuc'} onClick={() => addFuncHandle(record)}>单元</a>,
                    <UpDataActBtn key={'act_INDICATOR'} record={record} type='INDICATOR' />,
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },

    ]


    const getTableData = async (params: any) => {
        const resp = await getData(params);
        if (resp) {
            return {
                data: resp,
                success: true,
            }
        }
        return []
    }

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

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

        if (type == 'ADD') {
            const resp = await addData({ ...formVal });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }
        if (type == 'EDIT') {
            const resp = await editData({ ...formVal });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }

        if (type == 'INDICATOR') {
            const resp = await addIndicGroup({ ...formVal });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            } else {
                return false
            }
        }


        return true;

    }


    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 = [
        {
            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 addFuncHandle = (record: any) => {
        set_currentOperateRow(record);
        const ref = React.createRef<{ save: any; }>();

        Modal.confirm({
            title: `添加分组核算单元（${record.groupName}）`,
            icon: <></>,
            okText: '确定',
            cancelText: '取消',
            width: 688,
            centered: true,
            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();
            if (resp) {

                if (record) {

                    if (record.unitInfoVos) {
                        const defaultSelctedkeys = record.unitInfoVos.map((item: any) => item.unitCode);
                        setTargetKeys(defaultSelctedkeys);
                    }

                    set_datasource([...resp, ...(record.unitInfoVos ? record.unitInfoVos.map((a: any) => ({ ...a, code: a.unitCode })) : [])]);

                }

            }
        }

        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 }))

                const resp = await addUnitForGroup({
                    id: record.id,
                    unitInfoVos: result
                });
                if (resp) {
                    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'}
                            tableAlertRender={false}
                            pagination={{ simple: true, pageSize: 9, showTotal: () => false }}
                            locale={{ emptyText: '无数据' }}
                            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 UpDataActBtn = ({ record, type }: { record: any, type: 'EDIT' | 'ADD' | 'INDICATOR' | 'UNIT' }) => {


        const [indicatorData, set_indicatorData] = useState<any[]>([]);

        const [indicatorIniData, set_indicatorIniData] = useState({});

        const formRef = useRef<ProFormInstance>();

        const triggerNode = () => {
            if (type == 'ADD') {
                return <span className='add'>新增</span>
            }
            if (type == 'EDIT') {
                return <a key="edit" >编辑</a>
            }
            if (type == 'INDICATOR') {
                return <a key="INDICATOR" >指标</a>
            }
            if (type == 'UNIT') {
                return <a key="UNIT" >单元</a>
            }
        }

        const title = () => {
            if (type == 'ADD') {
                return `新增指标分组`
            }
            if (type == 'EDIT') {
                return `编辑指标分组（${record.groupName}）`
            }
            if (type == 'INDICATOR') {
                return `分组指标设置（${record.groupName}）`
            }
            if (type == 'UNIT') {
                return `单元设置（${record.groupName}）`
            }
        }


        const addIndicator = () => {

            const key = Math.random();

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

            set_indicatorIniData({ ...indicatorIniData, [`indicatorCode${key}`]: '', [`weight${key}`]: '' });

            set_indicatorData([...temp]);

        }

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

            set_indicatorIniData({ ...defaultFormData });
            set_indicatorData([...result]);
        }





        useEffect(() => {
            if (type == 'INDICATOR') {
                let defaultFormData: { [key: string]: any } = {};
                if (record.indicatorWeights && record.indicatorWeights.length > 0) {
                    const _indicatorWeights = record.indicatorWeights.map((a: any) => ({ ...a, id: Math.random() }))
                    const defaultVal = _indicatorWeights.map((a: any) => {
                        defaultFormData[`indicatorCode${a.id}`] = a.indicatorCode;
                        defaultFormData[`weight${a.id}`] = a.weight;
                        return { ...a, tempId: Math.random() }
                    });

                    set_indicatorIniData({ ...defaultFormData });

                    set_indicatorData([...defaultVal]);
                } else {
                    set_indicatorData([{}]);
                }
            }
        }, [record]);

        // useEffect(() => {
        //     console.log({ 'change': indicatorData });
        // }, [indicatorData]);

        return (

            <ModalForm
                title={title()}
                width={356}
                className='IndicGroupWeightSet-ModalForm'
                initialValues={type == 'EDIT' ? { ...record } : type == 'INDICATOR' ? { ...indicatorIniData } : {}}
                formRef={formRef}
                trigger={
                    triggerNode()
                }
                modalProps={{ destroyOnClose: true }}
                onFinish={(val) => {
                    if (type == 'ADD') {
                        return updateTable({ ...val }, type)
                    }
                    if (type == 'EDIT') {
                        return updateTable({ ...record, ...val }, type)
                    }
                    if (type == 'INDICATOR') {

                        return updateTable({ id: record.id, indicatorWeights: indicatorData.map(a => ({ ...a, indicatorCode: `${a.indicatorCode}` })) }, type);
                    }

                    return Promise.resolve(true);
                    // if (type == 'UNIT') {
                    //     return { id:record.id,indicatorWeights:indicatorData }
                    // }
                }}
            >
                {
                    (type == 'EDIT' || type == 'ADD') && (
                        <>
                            <ProFormText
                                name="groupName"
                                label="分组名称："
                                placeholder="请输入"
                                fieldProps={{ maxLength: 8, showCount: true }}
                                rules={[{ required: true, message: '名称不能为空!' }]}
                            />
                            <div style={{ display: 'flex', flexDirection: 'row', width: '320px', justifyContent: 'space-between' }}>
                                <span>总分上下限：</span>
                                <ProFormDigit name='floor' width={100} placeholder='总分下限' />
                                <span>-</span>
                                <ProFormDigit name='ceiling' width={100} placeholder='总分上限' />
                            </div>

                            <ProFormTextArea name={'depiction'} label='说明：' />
                        </>
                    )
                }
                {
                    type == 'INDICATOR' && (
                        <div>
                            <div style={{ maxHeight: 442, overflowY: 'scroll' }}>
                                {
                                    indicatorData.map((item: any, index: number) => {

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

                                                    }}
                                                    fieldProps={{
                                                        //   labelInValue:true,
                                                        onChange(value, option: any) {
                                                            // console.log({ value, option });
                                                            const temp = [...indicatorData];
                                                            const newArr = temp.map((a: any) => {
                                                                if (a.id == item.id) {
                                                                    return {
                                                                        ...a, indicatorCode: value, indicatorName: option.label, scoringMethod: option.scoringMethod,
                                                                        weight: option.scoringMethod == 1 ? a.weight : 0
                                                                    }
                                                                }
                                                                return a
                                                            });
                                                            set_indicatorData([...newArr]);

                                                        },
                                                    }}
                                                />


                                                {
                                                    item.scoringMethod == 2 ? (
                                                        <InputNumber
                                                            style={{ width: 120, height: 24, position: 'relative', top:2 }}
                                                            precision={4}
                                                            value={0.0000}
                                                            disabled={true}
                                                        />
                                                    ) : (
                                                        <Form.Item name={`weight${item.id}`} label='权重(请输入小数)：'>
                                                            <InputNumber
                                                                style={{ width: 120, height: 24, position: 'relative', top: 0 }}
                                                                precision={4}
                                                                onChange={(value) => {
                                                                    //console.log({value,index,indicatorData});
                                                                    const temp = [...indicatorData];
                                                                    const newArr = temp.map((a: any) => {
                                                                        if (a.id == item.id) {
                                                                            return { ...a, weight: value }
                                                                        }
                                                                        return a
                                                                    });

                                                                    set_indicatorData([...newArr]);
                                                                }}
                                                            />
                                                        </Form.Item>
                                                    )
                                                }


                                                {/* <ProFormText label='占比(请输入小数)：' name={`weight${item.id}`}  width={120} fieldProps={{
                                                onChange(value) {
                                                    //console.log({value,index,indicatorData});
                                                    const temp = [...indicatorData];
                                                    const newArr = temp.map((a:any)=>{
                                                        if(a.id == item.id){
                                                              return {...a,weight:value}
                                                        }
                                                        return a
                                                    });

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

            </ModalForm>
        )
    }


    useEffect(() => {

    }, [])

    return (
        <BMSPagecontainer className='IndicGroupWeightSet' title={'指标分组权重设置'}>
            <div className='toolBar'>
                <div className='filter'>

                </div>
                <div className='btnGroup' style={{ position: 'absolute', right: 16, top: 16 }}>
                    <UpDataActBtn record type='ADD' />
                </div>
            </div>
            <div style={{ marginTop: 16 }}>
                <BMSTable columns={columns as ProColumns[]} pagination={false} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </BMSPagecontainer>
    )
}
