/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:47:11
 * @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 KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { formatMoneyNumber } from '@/utils/format';
import { createFromIconfontCN } from '@ant-design/icons';
import FormItem from 'antd/es/form/FormItem';

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

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';



import { addData, delData, editData, getDiseaseComparisonTableData, importDataPost, matchDiseaseTypeMap } from './service';

import './style.less';
import KCIMUpload from '@/components/KCIMUpload';
import { downloadTemplateReq } from '@/utils/tooljs';
import { getDiseaseTableData } from '../diseaseMana/service';


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



export default function DiseaseDiagnosisComparison() {

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

        {
            title: '诊断代码',
            dataIndex: 'diagCode',
        },
        {
            title: '诊断名称',
            dataIndex: 'diagName',
        },
        {
            title: '国家编码',
            dataIndex: 'icdCode',
        },
        {
            title: '病种编码',
            dataIndex: 'diseaseTypeCode',
        },
        {
            title: '病种名称',
            dataIndex: 'diseaseTypeCodeName',
        },
        {
            title: '操作',
            key: 'option',
            width: 90,
            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 getDiseaseComparisonTableData({ ...params,type:stopStat });
        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") => {
        const result = {
            ...formVal,
            diseaseTypeCode:formVal.diseaseTypeCode == -1?'':formVal.diseaseTypeCode
        }

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

        }
        if (type == 'EDIT') {

            const resp = await editData({ 
                ...result,
                diseaseTypeCodeName:formVal.diseaseTypeCode == -1?'':formVal.diseaseTypeCodeName
             });
            if (resp) {
                tableRef.current?.reload();
                message.success('操作成功！');
            }
        }
        return true;

    }


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

        return (
            <ModalForm
                title={`${type == 'EDIT' ? '编辑' : '新增'}诊断`}
                width={350}
                formRef={formRef}
                initialValues={type == 'EDIT' ? {
                    ...record,
                    diseaseTypeCode:record.diseaseTypeCode?record.diseaseTypeCode:-1
                } : {diseaseTypeCode:-1}}
                trigger={
                    type == 'EDIT' ? <a key="edit" >编辑</a> : <a className='add'>新增</a>
                }
                onFinish={(val) => {
                    return updateTable(type == 'EDIT' ? { ...record, ...val } :{ ...val}, type);
                }}
                modalProps={{ destroyOnClose: true }}
                colProps={{ span: 24 }}
                grid
            >
                <ProFormText
                    name="diagCode"
                    label="诊断编码："
                    placeholder="请输入"
                    rules={[{ required: true, message: '诊断编码不能为空!' }]}
                />
                <ProFormText
                    name="diagName"
                    label="诊断名称："
                    placeholder="请输入"
                    rules={[{ required: true, message: '诊断名称不能为空!' }]}
                />
                <ProFormText
                    name="icdCode"
                    label="国家编码："
                    placeholder="请输入"
                    rules={[{ required: true, message: '国家编码不能为空!' }]}
                />
                <ProFormSelect
                    name="diseaseTypeCode"
                    label="病种名称："
                    placeholder="请输入"
                    showSearch
                    request={async()=>{
                          const resp = await getDiseaseTableData({pageSize:500,current:1});
                          if(resp){
                              const arr = resp.list.map((a:any)=>({label:`${a.name}(${a.code})`,value:a.code}));
                              return [
                                {label:'暂不选择',value:-1},
                                ...arr
                              ]
                          }
                          return []
                    }}
                    fieldProps={{
                          onChange(value, option) {
                                console.log({value});
                                if(!value){
                                     formRef.current?.setFieldValue('diseaseTypeCode',undefined);
                                }
                          },
                    }}
                />
            </ModalForm>
        )
    }

    const tableDataSearchHandle = (paramName: string) => {

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

    }


    const downloadTemplate = async () => {
        await downloadTemplateReq('/costAccount/setting/exportDiseaseTypeMap');
    };

    const mapBtnHandle = () => {

        Modal.confirm({
          title: '注意',
          content: '对照操作只会自动匹配未对照的项目，是否继续操作？',
          okText:'确定',
          cancelText:'取消',
          onOk: async (...args) => {
            const resp = await matchDiseaseTypeMap();
            if (resp) {
              message.success('操作成功！');
              tableRef.current?.reload();
            }
          },
        })
    }

    const importData = () => {
        return (
            <ModalForm
                width={360}
                title={`导入数据`}
                trigger={
                    <a className="import" key="3">
                        导入  
                    </a>
                }
                submitter={{
                    render: (props, defaultDoms) => {
                        const needBtn = defaultDoms.filter((b) => {
                            return b.key != 'rest';
                        });
                        return [
                            ...needBtn,
                        ];
                    },
                }}
                onFinish={async (values) => {
                    const {
                        importFile: { fileList },
                    } = values;

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

                    if (resp) {
                        tableRef.current?.reload();
                        return true;
                    }
                }}
            >
                <FormItem name={'importFile'}>
                    <KCIMUpload downloadTemplateFile={() => downloadTemplate()} />
                </FormItem>
            </ModalForm>
        );
    };


    useEffect(() => {

    }, [])

    return (
        <KCIMPagecontainer className='DiseaseDiagnosisComparison' title={false}>
            <div className='toolBar'>
                <div className='filter'>
                    <div className='filterItem'>
                        <span className='label' style={{ whiteSpace: 'nowrap' }}> 检索：</span>
                        <Input placeholder={'诊断名称/国家编码'} allowClear autoComplete='off'
                            suffix={
                                <IconFont type="iconsousuo"  style={{color:'#99A6BF'}} 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 style={{ paddingRight: 16 }}><ProFormSwitch noStyle fieldProps={{
                        size: 'small', onChange: (bool) => {
                            set_stopStat(bool ? 1 : 0);
                            tableRef.current?.reload();
                        }
                    }} /> 显示未对照项目</span>
                    <span className='mapBtn' onClick={()=>mapBtnHandle()}>对照</span>
                    {importData()}
                    <UpDataActBtn record type='ADD' />
                </div>
            </div>

            <div style={{ marginTop: 16 }}>
                <KCIMTable  scroll={{y:`calc(100vh - 233px)`}} columns={columns as ProColumns[]} actionRef={tableRef} rowKey='id' params={tableDataFilterParams} request={(params) => getTableData(params)} />
            </div>
        </KCIMPagecontainer>
    )
}
