/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-04-01 10:05:50
 * @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, ProFormRadio } from '@ant-design/pro-components';
import { ModalForm, ProFormCascader, ProFormDependency, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react'

import { addData, delData, editData, getManaIndicListData } from './service';

import './style.less';

import '../../../../utils/zhongtaiB';
import SQLEditor from '@/components/SQLEditor';
const IconFont = createFromIconfontCN({
    scriptUrl: '',
});



export default function manaIndicItemSet() {

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




    const columns: ProColumns[] = [

        {
            title: '管理指标名称',
            dataIndex: 'name',
        },
        {
            title: '指标导向',
            dataIndex: 'guideName',
        },
        {
            title: '指标类型',
            dataIndex: 'scoringMethod',
            renderText(num, record, index, action) {
                return num == 1 ? '系数指标' : '加扣分指标'
            },
        },
        {
            title: '得分下限',
            dataIndex: 'scoreFloor',
            renderText(num, record, index, action) {
                const { scoringMethod } = record;
                return scoringMethod == 1 ? `${num * 100}%` : num
            },
        },
        {
            title: '得分上限',
            dataIndex: 'scoreCeiling',
            renderText(num, record, index, action) {
                const { scoringMethod } = record;
                return scoringMethod == 1 ? `${num * 100}%` : num
            },
        },
        {
            title: '数据格式',
            dataIndex: 'dataTypeName',
        },
        {
            title: 'SQL',
            dataIndex: 'sql',
        },
        {
            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 resp = await getManaIndicListData(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") => {

        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('操作成功！');
            }
        }
        return true;

    }


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

        const [expand, set_expand] = useState(false);

        useEffect(() => {
            if (record) {
                set_expand(record.source == 2)
            }
        }, [record])

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}管理指标项目${record.name ? `（${record.name}）` : ''}`}
                width={expand ? 960 : 352}
                formRef={formRef}
                initialValues={type == 'EDIT' ? { ...record } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val, sql: val.sql ? val.sql : '' } : { ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <div className='formContent' style={{ display: 'flex', flexDirection: 'row', alignItems: 'flex-start' }}>
                    <div className='left' style={{ width: expand ? 322 : 327, marginRight: 16 }}>
                        <ProFormText
                            name="name"
                            label="管理指标名称："
                            placeholder="请输入"
                            rules={[{ required: true, message: '指标名称不能为空!' }]}
                        />
                        <ProFormSelect
                            name="guide"
                            label="指标导向"
                            placeholder="请选择"
                            options={[
                                { label: '正向', value: 1 },
                                { label: '负向', value: 2 }
                            ]}
                            rules={[{ required: true, message: '指标导向不能为空!' }]}
                        />
                        <ProFormRadio.Group
                            name="scoringMethod"
                            label="指标类型："
                            fieldProps={{
                                buttonStyle: 'solid'
                            }}
                            options={[
                                {
                                    label: '系数指标',
                                    value: 1,
                                },
                                {
                                    label: '加扣分指标',
                                    value: 2,
                                },
                            ]}
                            rules={[{ required: true, message: '默认不能为空!' }]}
                        />
                        <div style={{ display: 'flex', width: 352, flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'center', marginBottom: 15 }}>
                            <div><span style={{ position: 'relative', color: '#ff4d4f', paddingRight: 4, paddingLeft: 4, fontSize: 15 }}>*</span>得分上下限：</div>
                            <ProFormDigit
                                colProps={{ span: 6 }}
                                noStyle
                                name="scoreFloor"
                                // label="得分下限："
                                placeholder="请输入"
                                min={-1000000}
                                rules={[{ required: true, message: '得分下限不能为空!' }]}
                            />
                            <div style={{ padding: '0 10px' }}>-</div>
                            <ProFormDigit
                                colProps={{ span: 6 }}
                                name="scoreCeiling"
                                // label="得分上限："
                                noStyle
                                placeholder="请输入"
                                min={-1000000}
                                rules={[{ required: true, message: '得分上限不能为空!' }]}
                            />
                            <Tooltip title="加扣分指标：请填写指标分数的上下限分值非加扣分指标：请填写得分系数，指标的上下限分值=指标标准分值*上下限得分系数">
                                <IconFont type="iconshuoming" style={{ fontSize: 20 }} />
                            </Tooltip>
                        </div>


                        <ProFormDigit
                            name="sort"
                            label="顺序号："
                            placeholder="请输入"
                            min={0}
                            rules={[{ required: true, message: '顺序号不能为空!' }]}
                        />
                        <ProFormRadio.Group
                            name="dataType"
                            label="数据格式："
                            fieldProps={{
                                buttonStyle: 'solid'
                            }}
                            options={[
                                {
                                    label: '数值',
                                    value: 1,
                                },
                                {
                                    label: '百分比',
                                    value: 2,
                                },
                            ]}
                            rules={[{ required: true, message: '默认不能为空!' }]}
                        />

                        <ProFormRadio.Group
                            name="source"
                            label="数据来源："
                            fieldProps={{
                                buttonStyle: 'solid',
                                onChange(e) {
                                    if (e.target.value == 2) {
                                        set_expand(true);
                                    } else {
                                        set_expand(false);
                                    }
                                },
                            }}
                            options={[
                                {
                                    label: '填报',
                                    value: 1,
                                },
                                {
                                    label: '自动获取',
                                    value: 2,
                                },
                            ]}
                            rules={[{ required: true, message: '默认不能为空!' }]}
                        />
                    </div>

                    <ProFormDependency name={['source']}>
                        {
                            ({ source }) => source == 2 && (
                                <div className='right' style={{ width: 'calc(880px - 290px)' }}>
                                    <SQLEditor
                                        name="sql"
                                        label="SQL："
                                        rules={[{ required: true, message: 'SQL不能为空!' }]}
                                        form={formRef}
                                        height={'380px'}
                                    />
                                </div>

                            )
                        }
                    </ProFormDependency>

                </div>


            </ModalForm>
        )
    }

    const tableDataSearchHandle = (paramName: string) => {


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


    useEffect(() => {

    }, [])

    return (
        <BMSPagecontainer className='ManaIndicItemSet' 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'>
                    <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>
    )
}
