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

import { addData, delData, downloadTemplateReq, editData, gainData, getBillProjectData, importBillingProjectRelaFiles } from './service';

import './style.less';

import '../../../../utils/zhongtaiB'
import FormItem from 'antd/es/form/FormItem';
import BMSUpload from '@/components/BMSUpload';

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



export default function BilingProjectMana() {

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




    const columns = [

        {
            title: '项目代码',
            dataIndex: 'itemCode',
        },
        {
            title: '项目名称',
            dataIndex: 'itemName',
        },
        {
            title: '项目类别',
            dataIndex: 'itemType',
        },
        {
            title: '点值',
            dataIndex: 'orderPointValue',
        },
        {
            title: '大类',
            dataIndex: 'kcBigType',
        },
        {
            title: '小类',
            dataIndex: 'kcSmallType',
        },
        {
            title: '指标类别',
            dataIndex: 'kcIndicatorType',
        },
        {
            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 getCurrentComputeDate = async () => {
        const resp = await getComputeDate();
        set_currentComputeDate(resp);
    }


    const getTableData = async (params: any) => {
        const resp = await getBillProjectData(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") => {
        
        let flag = false;
        const result = {
            itemCode: formVal.itemCode,
            itemName: formVal.itemName,
            itemTypeCode: formVal.itemType.value,
            itemType: formVal.itemType.label,
            coreFlag: formVal.coreFlag,
            orderPointValue: formVal.orderPointValue,
            kcBigType:formVal.kcBigType,
            kcSmallType:formVal.kcSmallType,
            kcIndicatorType:formVal.kcIndicatorType,
        }

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

        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' }) => {

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}收费项目`}
                width={352}
                initialValues={type == 'EDIT' ? { ...record,itemType:{label:record.itemType,value:record.itemTypeCode} } : {coreFlag:1}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val,orderPointValue:val.orderPointValue?val.orderPointValue:undefined} : { ...val }, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >

                <ProFormText
                    name="itemName"
                    label="项目名称："
                    placeholder="请输入"
                    rules={[{ required: true, message: '名称不能为空!' }]}
                />
                <ProFormText
                    name="itemCode"
                    label="项目代码："
                    placeholder="请输入"
                    rules={[{ required: true, message: '代码不能为空!' }]}
                />

                <ProFormSelect label="项目类别："
                    name='itemType'
                    options={(getDataByKeyFromDic(dicData, 'ITEM_TYPE')).list}
                    fieldProps={{ labelInValue: true }}
                    rules={[{ required: true, message: '类别不能为空!' }]}
                />

                <ProFormDigit
                    name="orderPointValue"
                    label="点值："
                    placeholder="请输入"
                />
                <ProFormRadio.Group
                    name="coreFlag"
                    label="类型："
                    fieldProps={{
                        buttonStyle: 'solid'
                    }}
                    options={[
                        {
                            label: '核心',
                            value: 1,
                        },
                        {
                            label: '非核心',
                            value: 0,
                        },
                        {
                            label: '不计',
                            value: 2,
                        },
                    ]}
                />
                <ProFormText
                    name="kcBigType"
                    label="康程大类："
                    placeholder="请输入"
                />
                <ProFormText
                    name="kcSmallType"
                    label="康程小类："
                    placeholder="请输入"
                />
                <ProFormText
                    name="kcIndicatorType"
                    label="指标类别："
                    placeholder="请输入"
                />

            </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) {
                message.success('获取成功！');
                tableRef.current?.reload();
            }
        }
    }

    const downloadTemplate = async ()=>{
        await downloadTemplateReq(currentComputeDate as string);
    }


    const importData = () => {

        return (
            <ModalForm
                className='BilingProjectMana-Modal'
                width={360}
                title={`导入收费项目数据`}
                trigger={
                    <span key="3" className='importBtn'>导入</span>
                }
                submitter={{
                    render: (props, defaultDoms) => {
                        const needBtn = defaultDoms.filter((b) => {
                            return b.key != 'rest'
                        })
                        return [
                            ...needBtn,
                        ];
                    },
                }}
                onFinish={async (values) => {
                    // console.log({values});
                    const { importFile: { fileList } } = values;

                    let formData = new FormData();
                    formData.append('file', fileList[0].originFileObj);
                   
                    const resp = await importBillingProjectRelaFiles(formData);

                    if (resp) {
                        tableRef.current?.reload();
                        return true;
                    }

                }}
            >
                <FormItem name={'importFile'}>
                    <BMSUpload downloadTemplateFile={() => downloadTemplate()} />
                </FormItem>

            </ModalForm>
        )
    }


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

    return (
        <BMSPagecontainer className='BilingProjectMana' title={false}>
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                        <Input placeholder={'请输入项目名称'} allowClear
                            suffix={
                                <IconFont style={{color:'#99A6BF'}} 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'>
                    {importData()}
                    <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>
    )
}
