/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-05-30 11:27:59
 * @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, ProFormInstance } from '@ant-design/pro-components';
import { ModalForm, ProFormDependency, ProFormSelect } 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 { getClolumnTableData, getReportColumn } from '../reportSetting/service';

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

import './style.less';


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



export default function ReportNavSet() {

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

    const columns: ProColumns[] = [

        {
            title: '源报表名称',
            dataIndex: 'reportName',
        },
        {
            title: '报表列名称',
            dataIndex: 'reportColumnName',
        },
        {
            title: '目标报表名称',
            dataIndex: 'redirectReportName',
            // render:(_:any)=>_ == 1?'指标':'自定义SQL'
        },
        {
            title: '跳转参数',
            width: 400,
            ellipsis: true,
            dataIndex: 'redirectParameterDisplay',
            render: (_: any, record: any) => {
                if (record.redirectParameterDisplay) {
                    const a = JSON.parse(record.redirectParameterDisplay);
                    if (a) {
                        return (a.map((item: any) => item.label)).join('|');
                    } else {
                        return ''
                    }
                }
            }
        },
        {
            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 getReportListTableData(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({
                redirectReportCode: formVal.targetReport.value,
                redirectReportName: formVal.targetReport.label,
                reportColumnCode: formVal.reportColumn.value,
                reportColumnName: formVal.reportColumn.label,
                reportCode: formVal.report.value,
                reportName: formVal.report.label,
                redirectParameter: (formVal.redirectParameter.map((a: any) => a.value)).join('|'),
                redirectParameterDisplay: JSON.stringify(formVal.redirectParameter)
            });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }

        }
        if (type == 'EDIT') {

            const resp = await editData({
                id: formVal.id,
                redirectReportCode: formVal.targetReport.value,
                redirectReportName: formVal.targetReport.label,
                reportColumnCode: formVal.reportColumn.value,
                reportColumnName: formVal.reportColumn.label,
                reportCode: formVal.report.value,
                reportName: formVal.report.label,
                redirectParameter: (formVal.redirectParameter.map((a: any) => a.value)).join('|'),
                redirectParameterDisplay: JSON.stringify(formVal.redirectParameter)
            });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }
        return true;

    }


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

        const redirectParameter = JSON.parse(record.redirectParameterDisplay ? record.redirectParameterDisplay : '[]');

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}报表跳转`}
                width={400}
                formRef={formRef}
                initialValues={type == 'EDIT' ? {
                    ...record,
                    report: { label: record.reportName, value: record.reportCode },
                    reportColumn: { label: record.reportColumnName, value: record.reportColumnCode },
                    targetReport: { label: record.redirectReportName, value: record.redirectReportCode },
                    redirectParameter: redirectParameter
                } : {}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <span className='add'>新增</span>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } : { ...val }, type);
                }}
                modalProps={{destroyOnClose:true}}
                colProps={{ span: 24 }}
                grid
            >

                <ProFormSelect
                    name="report"
                    label="源报表标题："
                    placeholder="请选择"
                    request={async () => {
                        const resp = await getReportColumn();

                        if (resp) {
                            return resp.map((a: any) => ({ label: a.reportName, value: a.code }))
                        }
                    }}
                    fieldProps={{
                        labelInValue: true,
                        onChange(value, option) {
                            formRef?.current?.setFieldsValue({
                                reportColumn:null,
                                redirectParameter:[]
                            })
                        },
                    }}
                    rules={[{ required: true, message: '源报表名称不能为空!' }]}
                />

                <ProFormDependency name={['report']}>
                    {
                        ({ report }) => {
                            // console.log({report});
                            return (
                                <ProFormSelect
                                    name="reportColumn"
                                    label="报表列标题："
                                    disabled={!report}
                                    placeholder="请选择"
                                    params={report}
                                    request={async () => {
                                        if (report) {
                                            const { value: reportCode } = report;
                                            const resp = await getClolumnTableData({ reportCode });
                                            if (resp) {
                                                return resp.map((a: any) => ({ label: a.columnHeaderText, value: a.columnCode }))
                                            }
                                        } else {
                                            return []
                                        }

                                    }}
                                    fieldProps={{
                                        labelInValue: true
                                    }}
                                    rules={[{ required: true, message: '报表列名称不能为空!' }]}
                                />

                            )
                        }
                    }
                </ProFormDependency>
                <ProFormSelect
                    name="targetReport"
                    label="目标报表名称："
                    placeholder="请选择"
                    request={async () => {
                        const resp = await getReportColumn();

                        if (resp) {
                            return resp.map((a: any) => ({ label: a.reportName, value: a.code }))
                        }
                    }}
                    fieldProps={{
                        labelInValue: true
                    }}
                    rules={[{ required: true, message: '目标报表名称不能为空!' }]}
                />

                <ProFormDependency name={['report']}>
                    {
                        ({ report }) => {
                            // console.log({report});
                            return (
                                <ProFormSelect
                                    name="redirectParameter"
                                    label="跳转参数："
                                    disabled={!report}
                                    placeholder="请选择"
                                    params={report}
                                    request={async () => {
                                        if (report) {
                                            const { value: reportCode } = report;
                                            const resp = await getClolumnTableData({ reportCode });
                                            if (resp) {
                                                return resp.map((a: any) => ({ label: a.columnHeaderText, value: a.columnName }))
                                            }
                                        } else {
                                            return []
                                        }

                                    }}
                                    fieldProps={{
                                        labelInValue: true,
                                        mode: 'multiple',
                                        maxTagCount: 'responsive'
                                    }}
                                    rules={[{ required: true, message: '跳转参数不能为空!' }]}
                                />

                            )
                        }
                    }
                </ProFormDependency>

            </ModalForm>
        )
    }

    const tableDataSearchHandle = (paramName: string) => {

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

    }


    useEffect(() => {

    }, [])

    return (
        <BMSPagecontainer className='ReportNavSet' 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('reportName')} />
                            }
                            onChange={(e) => {
                                set_tableDataSearchKeywords(e.target.value);
                                if (e.target.value.length == 0) {
                                    set_tableDataFilterParams({
                                        ...tableDataFilterParams,
                                        reportName: ''
                                    });
                                }
                            }}
                            onPressEnter={(e) => {

                                set_tableDataFilterParams({
                                    ...tableDataFilterParams,
                                    reportName: (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>
    )
}
