/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-05-30 11:15:43
 * @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 { getComputeDate } from '@/pages/Home/service';
import { getDataByKeyFromDic, getPubDicData } from '@/services/getDic';
import { createFromIconfontCN } from '@ant-design/icons';

import { ActionType, ProFormDependency, ProFormRadio } from '@ant-design/pro-components';
import { ModalForm, ProFormCascader, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Form, Input, InputNumber, message, Popconfirm } from 'antd';
import { useEffect, useRef, useState } from 'react'
import { getSecondaryProjectDistriData } from '../secondaryProjectDistribute/service';


import { addData, delData, editData, gainData,getNonCheckProjectTableData, saveScoreData } from './service';

import './style.less';

import '../../../../utils/zhongtaiB';
import '../../../../utils/zhongtaiA'

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

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



export default function NonAssessmentProjectMana() {

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




    const columns: ProColumns[] = [

        {
            title: '项目代码',
            dataIndex: 'code',
        },
        {
            title: '项目名称',
            dataIndex: 'name',
        },
        {
            title: '分配方式',
            dataIndex: 'distributionTypeName',
        },
        {
            title: '分配对象',
            dataIndex: 'distributionTargetName',
        },
        {
            title: '上限值',
            dataIndex: 'ceiling',
        },
        {
            title: '评分项',
            dataIndex: 'secondItem',
            width: 400,
            ellipsis: true,
            render: (_, record) => {
                return record.secondItem ? (record.secondItem.map((a: any) => a.secondItemName)).join('|') : '-'
            }

        },
        {
            title: '操作',
            key: 'option',
            width: 200,
            valueType: 'option',
            render: (_: any, record: any) => {
                return record.distributionType == 1?[
                    <UpDataActBtn key={'SCORE'} record={record} type='SCORE' />,
                    <UpDataActBtn key={'act'} record={record} type='EDIT' />,
                    <Popconfirm
                        title="是否确认删除？"
                        key="del"
                        onConfirm={() => delTableData(record)}
                    >
                        <a>删除</a>
                    </Popconfirm>
                ]:[
                    <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 getNonCheckProjectTableData(params);
        if (resp) {
            return {
                data: resp.list,
                success: true,
                total: resp.totalCount,
                pageSize: resp.pageSize,
                totalPage: resp.totalPage,
            }
        }
        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" | 'SCORE') => {

        const result = {
            name: formVal.name,
            distributionType: formVal.distributionType,
            distributionTarget: formVal.distributionTarget,
            isCeiling: formVal.isCeiling,
            ceiling: formVal.ceiling
        }

        let flag = true;

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

        if (type == 'SCORE') {
            console.log({formVal});
            // const result = {
            //     nonAssessmentCode:formVal.nonAssessmentCode,
            //     secondItem:formVal.secondItem.map(())
            // }
            const resp = await saveScoreData({...formVal});
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }else{
                flag = false
            }
        }

        return flag;
    }

    const [dicData, set_dicData] = useState<any[]>([]);

    const getDirecData = async (key?: string) => {

        const data = await getPubDicData();
        if (data) {
            set_dicData(data);
        }
    }

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

   
        const [scoreList, set_scoreList] = useState<any[]>([]);
        const [scoreInitList, set_scoreInitList] = useState({});

        const addIndicator = () => {

            const key = Math.random();

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

            set_scoreInitList({ ...scoreInitList, [`secondItemCode${key}`]: '', [`weight${key}`]: '' });

            set_scoreList([...temp]);

        }

        const delGroupIndic = (data: any, index: number) => {
            let temp = [...scoreList];
            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_scoreInitList({ ...defaultFormData });
            set_scoreList([...result]);
        }

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

                    set_scoreInitList({ ...defaultFormData });
            
                    set_scoreList([...defaultVal]);
                } else {
                    set_scoreList([{}]);
                }
            }
        },[record]);


        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}${type == 'SCORE'?'评分项':'非考核项目'}`}
                className='NonAssessmentProjectMana-ModalForm'
                width={352}
                initialValues={type == 'EDIT' ? { ...record } :type == 'SCORE'?{...scoreInitList}:{}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> :type != 'SCORE'?<span className='add'>新增</span>:<a className='score'>评分项</a>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : type == 'SCORE'?{secondItem:scoreList,nonAssessmentCode:record.code}:{ ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
            >
                {
                    type == 'SCORE' && (
                        <div>
                            {
                                scoreList.map((item: any, index: number) => {

                                    return (
                                        <div className='item' key={index}>
                                            <ProFormSelect label="评分项：" width={160} 
                                                name={`secondItemCode${item.id}`}
                                                 request={async () => {
                                                    const resp = await getSecondaryProjectDistriData({pageSize:1000,current:1});
                                                    if (resp) {
                                                        return resp.list.map((a: any) => ({
                                                            label: a.name,
                                                            value: a.code
                                                        }))
                                                    }
                                                    return []

                                                }}
                                                fieldProps={{
                                                    //   labelInValue:true,
                                                    onChange(value, option: any) {
                                                        // console.log({value,option});
                                                        const temp = [...scoreList];
                                                        const newArr = temp.map((a: any) => {
                                                            if (a.id == item.id) {
                                                                return { ...a, secondItemCode: value, secondItemName: option.label }
                                                            }
                                                            return a
                                                        });

                                                        set_scoreList([...newArr]);
                                                    },
                                                }}
                                            />
                                            <Form.Item name={`weight${item.id}`} label='占比(请输入小数)：'>
                                                <InputNumber
                                                    style={{ width: 120, height: 24, position: 'relative', top: 0 }}
                                                    onChange={(value) => {
                                                        //console.log({value,index,indicatorData});
                                                        const temp = [...scoreList];
                                                        const newArr = temp.map((a: any) => {
                                                            if (a.id == item.id) {
                                                                return { ...a, weight: value }
                                                            }
                                                            return a
                                                        });

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

                {
                    type != 'SCORE' && (
                        <>
                            <ProFormText
                                name="name"
                                label="项目名称："
                                placeholder="请输入"
                                rules={[{ required: true, message: '名称不能为空!' }]}
                            />
                            <ProFormSelect
                                name="distributionType"
                                label="分配方式："
                                placeholder="请输入"
                                options={[
                                    { label: '占比', value: 1 },
                                    { label: '绝对数', value: 2 },
                                    { label: '自动计算', value: 3 },
                                ]}
                                rules={[{ required: true, message: '分配方式不能为空!' }]}
                            />
                            <ProFormDependency name={['distributionType']}>
                                {
                                    ({ distributionType }) => {
                                        return distributionType == 2 && (
                                            <ProFormSelect
                                                name="distributionTarget"
                                                label="分配对象："
                                                placeholder="请输入"
                                                options={[
                                                    { label: '员工', value: 1 },
                                                    { label: '核算单元', value: 2 },
                                                    { label: '医疗组', value: 3 },
                                                ]}
                                                rules={[{ required: true, message: '分配对象不能为空!' }]}
                                            />
                                        )
                                    }
                                }
                            </ProFormDependency>

                            <ProFormRadio.Group
                                name="isCeiling"
                                label="是否有上限："
                                fieldProps={{
                                    buttonStyle: 'solid'
                                }}
                                options={[
                                    {
                                        label: '有',
                                        value: 1,
                                    },
                                    {
                                        label: '无',
                                        value: 0,
                                    }
                                ]}
                                rules={[{ required: true, message: '评价方式不能为空!' }]}
                            />
                            <ProFormDependency name={['isCeiling']}>
                                {
                                    ({ isCeiling }) => {
                                        return isCeiling == 1 && (
                                            <ProFormDigit
                                                name="ceiling"
                                                label="上限值："
                                                placeholder="请输入"
                                                rules={[{ required: true, message: '上限值不能为空!' }]}
                                            />
                                        )
                                    }
                                }
                            </ProFormDependency>
                        </>
                    )
                }

            </ModalForm>
        )
    }

    const tableDataSearchHandle = (paramName: string) => {

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


    //获取按钮点击后获取数据
    const getDataBySQL = async () => {
        const resp = await getComputeDate();
        if (resp) {
            const respStat = await gainData({ compute_date: resp });
            if (respStat) {
                tableRef.current?.reload();
            }
        }
    }


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

    return (
        <BMSPagecontainer className='NonAssessmentProjectMana' title={false}>
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                        <Input placeholder={'请输入项目名称'} allowClear
                            suffix={
                                <IconFont type="iconsousuo" onClick={() => tableDataSearchHandle('name')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        name: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

                                set_tableDataFilterParams({
                                    ...tableDataFilterParams,
                                    name: (e.target as HTMLInputElement).value
                                });
                            }}

                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    {/* <span className='getDataBtn' onClick={() => getDataBySQL()}>获取</span> */}
                    <UpDataActBtn record type='ADD' />
                </div>
            </div>
            <div style={{ marginTop: 16 }}>
                <BMSTable columns={columns as ProColumns[]} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </BMSPagecontainer>
    )
}
