/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-11-20 16:29:50
 * @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 {
  ActionType,
  ProColumns,
  ProFormSelect,
} from '@ant-design/pro-components';
import { ModalForm } from '@ant-design/pro-form';
import FormItem from 'antd/es/form/FormItem';
import { Input } from 'antd';
import { useEffect, useRef, useState } from 'react';

import {
  getData,
  downloadTemplateReq,
  getTotalNumReq,
  importPatientChargeItemDataPost,
} 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 { getTargetDic } from '@/services/auth';
import { formatMoneyNumber } from '@/utils/format';

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

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

const columns: ProColumns[] = [
  {
    title: '收费项目',
    dataIndex: 'itemCode',
    width: 420,
    renderText(text, record, index, action) {
      const { itemCode, itemName } = record;
      return `[${itemCode}]${itemName}`;
    },
  },
  {
    title: '项目类别',
    dataIndex: 'itemType',
    width: 80,
    renderText(text, record, index, action) {
      let color = '',
        background = '';
      const { itemTypeCode } = record;
      if (itemTypeCode == '1') {
        color = '#009966';
        background = '#E8FCF6';
      }
      if (itemTypeCode == '2') {
        color = '#FF8000';
        background = '#FFF5EB';
      }
      if (itemTypeCode == '3') {
        color = '#0080FF';
        background = '#EBF5FF';
      }

      return (
        <span
          style={{
            display: 'inline-block',
            width: 40,
            height: 20,
            lineHeight: '20px',
            textAlign: 'center',
            borderRadius: 4,
            color: color,
            background: background,
            fontSize: 12,
          }}
        >
          {text}
        </span>
      );
    },
  },
  {
    title: '数量',
    dataIndex: 'num',
    width: 60,
    align: 'right',
  },
  {
    title: '单价',
    width: 120,
    dataIndex: 'price',
    align: 'right',
  },
  {
    title: '金额',
    width: 140,
    align: 'right',
    dataIndex: 'amount',
    renderText(num) {
      return formatMoneyNumber(num);
    },
  },
  {
    title: '开单科室',
    dataIndex: 'orderDepartmentCode',
    renderText(text, record, index, action) {
      const { orderDepartmentCode, orderDepartmentName } = record;
      return `[${orderDepartmentCode}]${orderDepartmentName}`;
    },
  },
  {
    title: '执行科室',
    dataIndex: 'executeDepartmentCode',
    renderText(text, record, index, action) {
      const { executeDepartmentCode, executeDepartmentName } = record;
      return `[${executeDepartmentCode}]${executeDepartmentName}`;
    },
  },
  {
    title: '开单人',
    dataIndex: 'orderUserCode',
    renderText(text, record, index, action) {
      const { orderUserCode, orderUserName } = record;
      return `[${orderUserCode}]${orderUserName}`;
    },
  },
  {
    title: '执行人',
    dataIndex: 'executeUserCode',
    renderText(text, record, index, action) {
      const { executeUserCode, executeUserName } = record;
      return `[${executeUserCode}]${executeUserName}`;
    },
  },
  {
    title: '医嘱项目',
    dataIndex: 'orderCode',
    renderText(text, record, index, action) {
      const { orderCode, orderName } = record;
      return `[${orderCode}]${orderName}`;
    },
  },
  {
    title: '住院号/门诊号',
    dataIndex: 'visitNo',
  },
  {
    title: '费用发生时间',
    width: 200,
    dataIndex: 'executeTime',
  },
];

export default function PatientChargeItemsImport({
  date,
  ifShowGetBtn,
  ifShowCancelBtn,
  currentSlectedPatientNo,
  cancelHandle,
  getHandle,
}: {
  date: string;
  ifShowGetBtn: boolean;
  ifShowCancelBtn: boolean;
  currentSlectedPatientNo: string;
  cancelHandle: () => Promise<boolean>;
  getHandle: () => Promise<boolean>;
}) {
  const [computeDate, set_computeDate] = useState(currentData);
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<any>({
    computeDate: currentData,
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');
  const tableRef = useRef<ActionType>();
  const [totalNum, set_totalNum] = useState(0);

  const getTableData = async (params: any) => {
    if (date && currentSlectedPatientNo) {
      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 getTotalNum = async () => {
    const resp = await getTotalNumReq({
      computeDate,
      itemType: tableDataFilterParams.itemType,
      departmentName: tableDataFilterParams.departmentName,
    });
    if (resp || resp == 0) {
      set_totalNum(resp);
    }
  };

  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 importPatientChargeItemDataPost(formData);

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

  useEffect(() => {
    // getTotalNum();
  }, [tableDataFilterParams]);

  useEffect(() => {
    if (date && currentSlectedPatientNo) {
      set_computeDate(date);
      set_tableDataFilterParams({
        ...tableDataFilterParams,
        computeDate: date,
        patientNo: currentSlectedPatientNo,
      });
    }
  }, [date, currentSlectedPatientNo]);

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

  return (
    <KCIMPagecontainer className="patientChargeItemsImport" title={false}>
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem" style={{ marginLeft: 16, width: 230 }}>
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              检索：
            </span>
            <Input
              placeholder={'收费项目代码/名称'}
              allowClear
              autoComplete="off"
              suffix={
                <IconFont
                  type="iconsousuo"
                  style={{ color: '#99A6BF' }}
                  onClick={() => tableDataSearchHandle('filter')}
                />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    filter: '',
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  filter: (e.target as HTMLInputElement).value,
                });
              }}
            />
          </div>
        </div>
        <div className="btnGroup">
          {ifShowCancelBtn && (
            <span
              onClick={() =>
                cancelHandle().then((isOk) => {
                  if (isOk) {
                    tableRef.current?.reload();
                  }
                })
              }
            >
              撤销
            </span>
          )}
          {ifShowGetBtn && (
            <span
              onClick={() =>
                getHandle().then((isOk) => {
                  if (isOk) {
                    tableRef.current?.reload();
                  }
                })
              }
            >
              获取
            </span>
          )}
          {/* {importData()} */}
        </div>
      </div>
      {/* <div className='total'>总金额：{formatMoneyNumber(totalNum)}</div> */}
      <div style={{ marginTop: 16 }}>
        <KCIMTable
          columns={columns}
          actionRef={tableRef}
          rowKey="id"
          scroll={{ x: 2500, y: `calc(100vh - 275px)` }}
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
