/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-03-07 17:27:16
 * @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, Popconfirm } from 'antd';
import { useEffect, useRef, useState } from 'react';

import { addBusinessDicTableData, delData, editPubDicRelaTbaleData, getBusinessDicTableData, getJobCateory } from './service';


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

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



const BusinessDicMana = () => {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any|undefined>();
    const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
    const [reload, set_reload] = useState(false);
    const [typeList, set_typeList] = useState<any[]>([]);
    const [showTypeListArr, set_showTypeListArr] = useState<any[]>([]);
    const [currentSelectedType, set_currentSelectedType] = useState<any | undefined>(undefined);
    const [columns,set_columns] = useState<any[]>([]);

    const tableRef = useRef<ActionType>();

    const defaultColumns = [
        {
            title: '项目名称',
            dataIndex: 'name',

        },
        {
            title: '项目代码',
            dataIndex: 'code',
        },
        {
            title: '项目值',
            dataIndex: 'value',
        },
        {
            title: '默认',
            dataIndex: 'defaultFlag',
            render: (_: any, record: any) => {
                return record.defaultFlag == 1 ? '是' : '否'
            },

        },
        {
            title: '序号',
            dataIndex: 'dictSort',

        },
        {
            title: '扩展1',
            dataIndex: 'reserved1',

        },
        {
            title: '扩展2',
            dataIndex: 'reserved2',

        },
    
    ];

    const options = [
        {
            title: '操作',
            key: 'option',
            width: 120,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]
            },
        },
    ]


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

    //获取左侧职类
    const getTypeList = async () => {
        const resp = await getJobCateory();
        if (resp) {
            set_typeList(resp);
            set_showTypeListArr(resp);
        }
    }

    const delTableData = async (record: any) => {
        const resp = await delData(record.id);
        if (resp) {
            tableRef.current?.reload();
        }
    }

    const updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {
  
        if (type == 'ADD') {
            const resp = await addBusinessDicTableData({ ...formVal,typeCode: currentSelectedType?.code });
            if (resp) {
                tableRef.current?.reload();
            }
        }
        if (type == 'EDIT') {
            const resp = await editPubDicRelaTbaleData({ ...formVal, typeCode: currentSelectedType?.code });
            if (resp) {
                tableRef.current?.reload();
            }
        }

        return true;

    }

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

        return (
            <ModalForm
                title={`${type == 'EDIT' ? `编辑（${record.name}）` : '新增'}公用字典`}
                width={352}
                initialValues={type == 'EDIT' ? { ...record } : {defaultFlag:0}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                modalProps={{destroyOnClose:true}}
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record,...val} : val, type);
                }}
            >
                <ProFormText
                    name="name"
                    label="项目名称："
                    placeholder="请输入"
                    rules={[{ required: true, message: '项目名称不能为空!' }]}
                />
                <ProFormText
                    name="code"
                    label="项目代码："
                    placeholder="请输入"
                    rules={[{ required: true, message: '项目代码不能为空!' }]}
                />
                <ProFormText
                    name="value"
                    label="项目值："
                    placeholder="请输入"

                />
                <ProFormDigit label="顺序号：" name="dictSort" rules={[{ required: true, message: '顺序号不能为空!' }]} />

                <ProFormRadio.Group
                    name="defaultFlag"
                    label="默认："
                    fieldProps={{
                        buttonStyle: 'solid'
                    }}
                    options={[
                        {
                            label: '是',
                            value: 1,
                        },
                        {
                            label: '否',
                            value: 0,
                        },
                    ]}
                    rules={[{ required: true, message: '默认不能为空!' }]}
                />
                <ProFormText
                    name="reserved1"
                    label="扩展1："
                    placeholder="请输入"

                />
                <ProFormText
                    name="reserved2"
                    label="扩展2："
                    placeholder="请输入"

                />
                
            </ModalForm>
        )
    }



    const tableDataSearchHandle = (paramName: string) => {
        set_tableDataFilterParams({
            ...tableDataFilterParams,
            [`${paramName}`]: tableDataSearchKeywords
        })
    }

    useEffect(() => {
        if (currentSelectedType) {
            const {topic = ''} = currentSelectedType;
            const temp = topic.split('|');
            if(temp.length == 7){
                  const newColumns = defaultColumns.map((a,index)=>{
                       return {
                           ...a,
                           title:temp[index]
                       }
                  });
                  set_columns([...newColumns,...options]);
            }else{
                set_columns([...defaultColumns,...options]);
            }
            set_tableDataFilterParams({ ...tableDataFilterParams, typeCode: currentSelectedType.code });
        }
    }, [currentSelectedType])

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

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

    return (
        <BMSPagecontainer title={false} className='BusinessDicMana'>
            <div className='left'>
                <Input placeholder={'请输入类目名称'} allowClear
                    suffix={
                        <IconFont style={{color:'#99A6BF'}} type="iconsousuo" />
                    }
                    onChange={(e) => {
                        const result = typeList.filter(item => item.name.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.name}</div>
                            )
                        })
                    }
                </div>
            </div>
            <div className='right'>
                <div className='toolBar'>
                    <div className='filter'>
                        <div className='filterItem'>
                            <span className='label'>检索：</span>
                            <Input placeholder={'请输入项目名称'} style={{ width: 160 }} allowClear

                                suffix={
                                    <IconFont style={{color:'#99A6BF'}} type="iconsousuo" onClick={() => tableDataSearchHandle('typeName')} />
                                }
                                onChange={(e) => {
                                    set_tableDataSearchKeywords(e.target.value);
                                    if (e.target.value.length == 0) {
                                        set_tableDataFilterParams({
                                            ...tableDataFilterParams,
                                            typeName: ''
                                        });
                                    }
                                }}

                                onPressEnter={(e)=>{
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        current:1,
                                        typeName:(e.target as HTMLInputElement).value
                                    });
                                }}

                            />
                        </div>
                    </div>
                    <div className='btnGroup'>
                        <UpDataActBtn record type='ADD' />
                    </div>
                </div>
                <div style={{ marginTop: 16 }}>
                    {currentSelectedType && <BMSTable scroll={{y:`calc(100vh - 230px)`}} actionRef={tableRef} columns={columns as ProColumns[]} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />}
                </div>
            </div>
        </BMSPagecontainer>
    )
}


export default BusinessDicMana;
