/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2023-10-23 16:05:32
 * @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 { createFromIconfontCN } from '@ant-design/icons';

import { ModalForm, ProFormText } from '@ant-design/pro-form';
import FormItem from 'antd/es/form/FormItem';
import {DatePicker,Input} from 'antd';
import { useEffect, useRef, useState } from 'react';

import { getData, downloadTemplateReq, importDataPost } from './service';

import './style.less';
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import KCIMUpload from '@/components/KCIMUpload';
import { ActionType } from '@ant-design/pro-components';


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

const currentData =  `${new Date().getFullYear()}-${(new Date().getMonth()+1).toString().padStart(2, '0')}`

export default function patientInfoImport() {
  const [computeDate,set_computeDate] = useState(currentData);
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<any>({computeDate:currentData});
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');
  const tableRef = useRef<ActionType>();

  const columns = [
    {
      title: '住院号/门诊号',
      dataIndex: 'visitNo',
    },
    {
      title: '病人ID',
      dataIndex: 'patientNo',
    },
    {
      title: '患者姓名',
      dataIndex: 'name',
    },
    {
      title: '就诊类别',
      dataIndex: 'type',
      renderText(type: number, record: any, index: any, action: any) {
        if(type==1)return '门诊';
        if(type==3)return '住院';
        if(type==2)return '急诊'
      },
    },
    {
      title: '科室代码',
      dataIndex: 'departmentCode',
    },
    {
      title: '科室名称',
      dataIndex: 'departmentName',
    },
    {
      title: '主诊断代码',
      dataIndex: 'primaryDiagCode',
    },
    {
      title: '主诊断名称',
      dataIndex: 'primaryDiagName',
    },
    {
      title: '次诊断代码',
      ellipsis: true,
      dataIndex: 'secondaryDiagCode',
    },
    {
      title: '次诊断名称',
      ellipsis: true,
      dataIndex: 'secondaryDiagName',
    },
    {
      title: '主手术/操作代码',
      dataIndex: 'primaryOperationCode',
    },
    {
      title: '主手术/操作名称',
      dataIndex: 'primaryOperationName',
    },
    {
      title: '次手术/操作代码',
      ellipsis: true,
      dataIndex: 'secondaryOperationCode',
    },
    {
      title: '次手术/操作名称',
      ellipsis: true,
      dataIndex: 'secondaryOperationName',
    },
    {
      title: 'DRG/DIP分组代码',
      dataIndex: 'groupCode',
    },
    {
      title: 'DRG/DIP分组名称',
      dataIndex: 'groupMame',
    },
    {
      title: '临床路径代码',
      dataIndex: 'clinicalPathwayCode',
    },
    {
      title: '临床路径名称',
      dataIndex: 'clinicalPathwayName',
    },
    {
      title: '入院日期',
      dataIndex: 'inHospitalTime',
    },
    {
      title: '出院日期',
      dataIndex: 'outHospitalTime',
    },
    {
      title: '住院天数',
      dataIndex: 'inHospitalDays',
    },
  ];

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

  const tableDataSearchHandle = (paramName:string) => {


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

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

  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 [
              // <Button
              //     key="ok"
              //     onClick={auditType == '0' ? () => downloadTemplate(index) : () => { }}
              // >
              //     下载模板
              // </Button>,
              ...needBtn,
            ];
          },
        }}
        onFinish={async (values) => {
          const {
            importFile: { fileList },
          } = values;

          let formData = new FormData();
          formData.append('file', fileList[0].originFileObj);
          formData.append('computeDate',computeDate);

          const resp = await importDataPost(formData);

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

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

  return (
    <KCIMPagecontainer className="patientInfoImport" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem">
            {
              <div className="search">
                <span>核算年月：</span>
                <DatePicker
                  onChange={(data, dateString) => {
                    set_computeDate(dateString);
                    set_tableDataFilterParams({
                      ...tableDataFilterParams,
                      computeDate: dateString,
                    });
                  }}
                  picker="month"
                  locale={locale}
                  defaultValue={moment(`${new Date().getFullYear()}-${(new Date().getMonth()+1).toString().padStart(2, '0')}`, 'YYYY-MM')}
                  format="YYYY-MM"
                  placeholder="选择年月"
                />
              </div>
            }
          </div>
          <div className='filterItem' style={{ marginLeft: 16, width: 205 }}>
              <span className='label' style={{ whiteSpace: 'nowrap' }}> 科室名称：</span>
              <Input placeholder={'请输入'} allowClear
                  suffix={
                      <IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle('departmentName')} />
                  }
                  onChange={(e) => {
                      set_tableDataSearchKeywords(e.target.value);
                      if (e.target.value.length == 0) {
                          set_tableDataFilterParams({
                              ...tableDataFilterParams,
                              departmentName: ''
                          });
                      }
                  }}
                  onPressEnter={(e) => {
                      set_tableDataFilterParams({
                          ...tableDataFilterParams,
                          departmentName: ((e.target) as HTMLInputElement).value 
                      });
                  }}

              />
          </div>
          <div className='filterItem' style={{ marginLeft: 16, width: 205 }}>
              <span className='label' style={{ whiteSpace: 'nowrap' }}> 患者名称：</span>
              <Input placeholder={'请输入'} allowClear
                  suffix={
                      <IconFont type="iconsousuo" style={{ color: '#99A6BF' }} onClick={() => tableDataSearchHandle('patientName')} />
                  }
                  onChange={(e) => {
                      set_tableDataSearchKeywords(e.target.value);
                      if (e.target.value.length == 0) {
                          set_tableDataFilterParams({
                              ...tableDataFilterParams,
                              patientName: ''
                          });
                      }
                  }}
                  onPressEnter={(e) => {
                      set_tableDataFilterParams({
                          ...tableDataFilterParams,
                          patientName: ((e.target) as HTMLInputElement).value 
                      });
                  }}

              />
          </div>
        </div>
        <div className="btnGroup">{importData()}</div>
      </div>
      <div style={{ marginTop: 16 }}>
        <KCIMTable
          columns={columns}
          actionRef={tableRef}
          rowKey="id"
          scroll={{x:2500}}
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
