/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-07-24 13:51: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 { createFromIconfontCN } from '@ant-design/icons';

import { ActionType } from '@ant-design/pro-components';
import { ModalForm, ProFormDatePicker, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form'
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, DatePicker } from 'antd';
import { useEffect, useRef, useState } from 'react'

import { addData, afterImport, delData, editData, getData, getSpecialImportTable, tableDataImport } from './service';
import FormItem from 'antd/es/form/FormItem';

import './style.less';
import '../../../utils/zhongtaiA'
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { getComputeDate } from '@/pages/Home/service';
import BMSUpload from '@/components/BMSUpload';

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



export default function DicClassfication() {

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




    const columns: ProColumns[] = [

        {
            title: '所属年月',
            dataIndex: 'computeDate',
            ellipsis: true
        },
        {
            title: '数据库表名称',
            dataIndex: 'tableNameDisplay',
            ellipsis: true
        },
        {
            title: '文件名称',
            dataIndex: 'fileName',
            ellipsis: true,
            renderText(text, record, index, action) {
                return <a href={record.url} target='_blank'>{record.fileName}</a>
            },
        },
        {
            title: '导入时间',
            dataIndex: 'createTime',
            ellipsis: true
        },
        {
            title: '导入人员',
            dataIndex: 'createUserName',
            ellipsis: true
        },
        {
            title: '操作',
            key: 'option',
            width: 120,
            valueType: 'option',
            render: (_: any, record: any) => {
                return [
                    <Popconfirm
                        title={`是否${record.importStatus == 1?'复原导入':'撤销导入'}?`}
                        key="del"
                        onConfirm={() => afterImportHandle(record)}
                    >
                        <a>{record.importStatus == 1?'复原导入':'撤销导入'}</a>
                    </Popconfirm>
                ]
            },
        },

    ];

    const getCurrentComputeDate = async () => {
        const resp = await getComputeDate();
        set_currentComputeDate(resp);
        //set_tableDataFilterParams({...tableDataFilterParams,computeDate:resp})
    }

    const afterImportHandle =async (record:any) => {
         const {importStatus} = record;
         const resp = await afterImport(record.id,importStatus?'RECOVERY':'CANCEL');
         if(resp){
            message.success('操作成功！');
            tableRef.current?.reload();
         }
    }


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


    const importData = () => {

        function downloadTemplate(): void {
           
        }

        return (
            <ModalForm
                className='SpecialDataImport-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);
                    formData.append('computeDate', values.computeDate);
                    formData.append('tableName', values.tableName);

                    const resp = await tableDataImport(formData);

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

                }}
            >
                <div className='tip'>本操作为追加导入，会保留已有的数据并将文件的所有记录追加到数据表</div>
                <ProFormDatePicker.Month label='所属年月' name='computeDate' width={326} rules={[{ required: true, message: '所属年月不能为空!' }]} />
                <ProFormSelect label='数据库表名称' name='tableName' width={326}
                    request={async () => {
                        const resp = await getSpecialImportTable();
                        if (resp) {
                            
                            return resp.list.map((a: any) => ({
                                label: a.name,
                                value: a.code
                            }))
                        }
                        return []
                    }}
                    rules={[{ required: true, message: '数据库表名称不能为空!' }]} />
                <FormItem name={'importFile'}>
                    {currentComputeDate && <BMSUpload downloadTemplateFile={() => downloadTemplate()} ifShowTip={false} ifShowTemplateDownload={false} />}
                </FormItem>

            </ModalForm>
        )
    }

    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 tableDataSearchHandle = (paramName: string) => {

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


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

    return (
        <BMSPagecontainer className='SpecialDataImport' title={`核算年月：${currentComputeDate}`}>
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        {(<div className='search'>
                            <span>所属年月：</span>
                            <DatePicker
                                onChange={(data, dateString) => {
                                    set_tableDataFilterParams({ ...tableDataFilterParams, computeDate: dateString })
                                }}
                                picker='month'
                                locale={locale}
                                //defaultValue={moment(currentComputeDate, 'YYYY-MM')}
                                format='YYYY-MM' placeholder="选择年月" />
                        </div>)}
                    </div>
                    <div className='filterItem' style={{ marginLeft: 16 }}>
                        <span className='label'>表名称：</span>
                        <ProFormSelect
                            noStyle
                            allowClear
                            placeholder="请选择"
                            style={{ width: 160, marginRight: 16 }}
                            request={async () => {
                                const resp = await getSpecialImportTable();
                                if (resp) {
                                    return resp.list.map((a: any) => ({
                                        label: a.name,
                                        value: a.code
                                    }))
                                }
                                return []
                            }}
                            fieldProps={{
                                onChange(value, option) {
                                    set_tableDataFilterParams({ ...tableDataFilterParams,tableName: value })
                                },
                            }}
                        />
                    </div>
                </div>
                <div className='btnGroup'>
                    {importData()}
                </div>
            </div>
            <div style={{ marginTop: 16 }}>
                {currentComputeDate && <BMSTable columns={columns as ProColumns[]} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params, sort, filter) => getTableData(params)} />}
            </div>
        </BMSPagecontainer>
    )
}
