/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-03-31 13:23:29
 * @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 { ActionType } from '@ant-design/pro-components';
import { ModalForm, ProFormDigit } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import {  message } from 'antd';
import { useEffect, useRef, useState } from 'react'

import {editData, getData } from './service';

import './style.less';


export default function ClassAssessAndGradeSet() {

    const [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
    const [tableColumn, set_tableColumn] = useState<ProColumns[] | any[]>([]);
    const [respColumns,set_respColumns ] = useState([]);

    const tableRef = useRef<ActionType>();

    const getTableData = async (params: any) => {
        const resp = await getData(params);
        if (resp) {

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

                    const children = item.children.map((a: any) => ({
                        title: a.name,
                        dataIndex: `${a.code}${item.code}`,
                    }))

                    return {
                        title: item.name,
                        dataIndex: `${item.code}`,
                        key: `${item.code}`,
                        // width: 140,
                        children: children

                    }
                } else {
                    return {
                        title: item.name,
                        dataIndex: `${item.code}`,
                        key: `${item.code}`,
                        // width: 140,

                    }
                }
            });
            set_respColumns(columns);
            set_tableColumn([{
                title: '职类',
                dataIndex: 'unitTypeName',
                key: 'unitTypeName',
                width: 140,
                fixed: 'left',

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

            const data = unitTypeData.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[`${key}${item.value[index].code}`] = item.value[index][`${key}`]
                        }
                    }
                }

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

        }
        return []
    }



    const updateTable = async (formVal: any, type: 'EDIT' | "ADD") => {
        
        let result = {
            unitTypeCode:formVal.unitTypeCode,
            unitTypeName:formVal.unitTypeName,
            value:formVal.record.columns.map((a:any)=>{
                  
                  return ({
                    code:a.key,
                    floor:formVal[`floor${a.key}`],
                    rate:formVal[`rate${a.key}`],
                    ceiling:formVal[`ceiling${a.key}`],
                  })
            })
        }
        
        if (type == 'EDIT') {
            const resp = await editData(result);
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }
        return true;

    }

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

        const [formData,set_formData] = useState([]);

        useEffect(()=>{
             if(record.columns.length != record.value.length){
                const valueCodes = record.value.map((a:any)=>a.key);
                const newData = record.columns.map((b:any)=>{
                       if(!valueCodes.includes(b.key)){
                            return {
                                code:b.key,
                                floor:'',
                                range:'',
                                rate:''
                            }
                       }
                       const temp = record.value.filter((c:any)=>c.code == b.key);
                       return temp[0]
                });

                set_formData(newData);

             }else{
                set_formData(record.value);
             } 
        },[record])
    
        return (
            <ModalForm
                title={`考核分级设定（${record.unitTypeName}）`}
                className='ClassAssessAndGradeSet-ModalForm'
                width={400}
                initialValues={type == 'EDIT' ? { ...record } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    // console.log({val});
                    return updateTable(type == 'EDIT' ? {unitTypeCode:record.unitTypeCode,unitTypeName:record.unitTypeName,value:record.value, ...val,record} : { ...val }, type);
                }}

            >
                <div className='tip'>区间的上限及下限至少填写一个，没填表示无</div>
                {
                    formData.map((item: any, index: number) => {

                        let label = record.columns.filter((a:any) => a.key == item.code);

                        return (
                            <div className='list' key={index}>
                                <div className='label'>{label.length > 0 ? `${label[0].title}：` : ''}</div>
                                <div className='wrap'>
                                    <ProFormDigit width={100} name={`floor${item.code}`} placeholder='分数下限' />
                                    <ProFormDigit width={100} name={`ceiling${item.code}`} placeholder='分数上限' />
                                    <ProFormDigit width={144} name={`rate${item.code}`} placeholder='奖惩系数' />
                                </div>
                            </div>
                        )
                     
                    })
                }
            </ModalForm>
        )
    }


    useEffect(() => {

    }, [])

    return (
        <BMSPagecontainer className='ClassAssessAndGradeSet' title={'职类考核分级设定'}>
            <div style={{ marginTop: 16 }}>
                <BMSTable actionRef={tableRef} bordered rowKey='unitTypeCode' pagination={false} columns={tableColumn as ProColumns[]} params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </BMSPagecontainer>
    )
}
