/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-03-19 10:55:39
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-08-29 16:49:38
 * @FilePath: /CostAccountingSys/src/pages/monthlyInfoCollection/components/leftAndRighrStructure.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { KCIMLeftList } from '@/components/KCIMLeftList';
import { KCIMTable } from '@/components/KCIMTable';
import {
  beforeCollectionSearch,
  beforeCostShareSearch,
} from '@/pages/costAccounting/calcPageTemplate/columns';
import { getCalcPageTableData } from '@/pages/costAccounting/calcPageTemplate/service';
import { ActionType, ProColumns } from '@ant-design/pro-components';
import { useEffect, useRef, useState } from 'react';
import { Input, Modal } from 'antd';

import './style.less';
import { createFromIconfontCN } from '@ant-design/icons';
import CostAllocationParamsDeal from '@/pages/baseSetting/costAllocationSet/costAllocationParamsDeal';
import PatientInfoImport from '@/pages/monthlyInfoSearch/patientInfoImport';
import PatientChargeItemsImport from '@/pages/monthlyInfoSearch/patientChargeItemsImport';
import {
  calcIdleCostReq,
  getCostDepartmentList,
  getCostShareDepartmentList,
  getIncomeDepartmentList,
  getPatientChargeItemList,
  getPatientInfoDepartmentList,
} from '../service';
import { formatMoneyNumber } from '@/utils/format';

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

export interface LeftAndRighrStructure {
  tabKey: string;
  computeDate: string;
  btnPerm: string;
  cancelHandle: () => Promise<boolean>;
  getHandle: () => Promise<boolean>;
  reload: boolean;
}

let _currentSelectedLeftObj: any = undefined;
export const LeftAndRighrStructure = (props: LeftAndRighrStructure) => {
  const {
    tabKey,
    computeDate,
    btnPerm = '1|1',
    cancelHandle,
    getHandle,
    reload,
  } = props;

  const tableRef = useRef<ActionType>();
  const [currentSelectedLeftObj, set_currentSelectedLeftObj] = useState<
    undefined | any
  >(undefined);
  const [tableColumn, set_tableColumn] = useState<ProColumns[]>([]);
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >(undefined);
  const [scrollX, set_scrollX] = useState<number | undefined>(1000);
  const [scrollY, set_scrollY] = useState<string>(`calc(100vh - 324px)`);
  const [tabSearchKey, set_tabSearchKey] = useState('');
  const [currentLeftTab, set_currentLeftTab] = useState(1);
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState('');
  const [tableSearchKey, set_tableSearchKey] = useState('');

  const [leftListData, set_leftListData] = useState<any[]>([]);
  const [leftListPage, set_leftListPage] = useState<number>(1);
  const [leftListPageSize, set_leftListPageSize] = useState<number>(200);
  const [leftListHasMore, set_leftListHasMore] = useState<boolean>(true);
  const [leftListLoading, set_leftListLoading] = useState<boolean>(false);
  const [ifShowGetBtn, set_ifShowGetBtn] = useState(false);
  const [ifShowCancelBtn, set_ifShowCancelBtn] = useState(false);

  const [leftListSearchPlaceHolder, set_leftListSearchPlaceHolder] =
    useState('请输入');
  const [leftListSearchKeyword, set_leftListSearchKeyword] = useState('');

  const [leftContentH, set_leftContentH] = useState<string | undefined>(
    undefined,
  );
  const [currentResp, set_currentResp] = useState<any>(undefined);

  const getTableData = async (params: any) => {
    if (tabKey == '1') {
      const resp = await getCalcPageTableData({
        calcPageKey: 'beforeCollectionSearch',
        ...params,
        ...tableDataFilterParams,
        computeDate,
        type: currentLeftTab,
        departmentCode: _currentSelectedLeftObj.subText,
      });
      if (resp) {
        // set_totalAmount(resp.totalAmount);
        set_currentResp(resp);
        return {
          data: resp.list,
          success: true,
          total: resp.totalCount,
          pageSize: resp.pageSize,
          totalPage: resp.totalPage,
        };
      }
    }
    if (tabKey == '2' && _currentSelectedLeftObj) {
      const resp = await getCalcPageTableData({
        ...params,
        calcPageKey: 'beforeCostShareSearch',
        ...tableDataFilterParams,
        computeDate,
        departmentCode: _currentSelectedLeftObj.subText,
      });
      if (resp) {
        set_currentResp(resp);
        return {
          data: resp.list,
          success: true,
          total: resp.totalCount,
          pageSize: resp.pageSize,
          totalPage: resp.totalPage,
        };
      }
    }
    return {
      data: [],
      success: true,
    };
  };

  const onLeftChange = (item: any) => {
    set_currentSelectedLeftObj(item);
    _currentSelectedLeftObj = item;
  };

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      [`${paramName}`]: tableDataSearchKeywords,
    });
  };

  const inComeLeftData = async () => {
    const resp = await getIncomeDepartmentList({
      computeDate,
      type: currentLeftTab,
    });
    if (resp) {
      const arr = resp.map((a: any) => ({
        name: a.departmentName,
        subText: a.departmentCode,
      }));
      set_leftListData([...arr]);
    }
  };
  const costLeftData = async () => {
    const resp = await getCostDepartmentList({
      computeDate,
      type: currentLeftTab,
    });
    if (resp) {
      const arr = resp.map((a: any) => ({
        name: a.departmentName,
        subText: a.departmentCode,
      }));
      set_leftListData([...arr]);
    }
  };
  const costShareLeftData = async () => {
    const resp = await getCostShareDepartmentList();
    if (resp) {
      set_leftListData([...resp]);
    }
  };

  const getPatientInfoDepartments = async () => {
    const resp = await getPatientInfoDepartmentList(
      computeDate,
      Number(currentLeftTab),
    );
    if (resp) {
      const arr = resp.map((a: any) => ({
        name: a.departmentName,
        subText: a.departmentCode,
      }));
      set_leftListData([...arr]);
    }
  };

  const getPatientChargeItemReq = async (
    page: number,
    pageSize: number,
    append: boolean = false,
    filter?: string,
  ) => {
    set_leftListLoading(true);
    try {
      const resp: any = await getPatientChargeItemList(
        computeDate,
        page,
        pageSize,
        filter ?? leftListSearchKeyword,
      );
      const rawList = Array.isArray(resp) ? resp : resp?.list || [];
      const arr = rawList.map((a: any) => ({
        name: a.name,
        subText: a.patientNo,
      }));
      if (append) {
        set_leftListData((prev) => [...prev, ...arr]);
      } else {
        set_leftListData([...arr]);
      }
      const prevCount = append ? leftListData.length : 0;
      const totalCount =
        resp && typeof resp === 'object'
          ? resp.totalCount ?? resp.total ?? undefined
          : undefined;
      if (typeof totalCount === 'number') {
        set_leftListHasMore(prevCount + arr.length < totalCount);
      } else {
        set_leftListHasMore(arr.length === pageSize);
      }
      set_leftListPage(page);
    } finally {
      set_leftListLoading(false);
    }
  };

  const onReachBottomLoadMore = () => {
    if (tabKey !== '6') return;
    if (leftListLoading) return;
    if (!leftListHasMore) return;
    const nextPage = leftListPage + 1;
    getPatientChargeItemReq(nextPage, leftListPageSize, true);
  };

  const onLeftSearchChange = (keyword: string) => {
    if (tabKey !== '6') return;
    set_leftListSearchKeyword(keyword);
    set_leftListPage(1);
    set_leftListHasMore(true);
    getPatientChargeItemReq(1, leftListPageSize, false, keyword);
  };

  const getLeftDatas = () => {
    if (tabKey == '1') {
      inComeLeftData();
    }
    if (tabKey == '3') {
      costShareLeftData();
    }
    if (tabKey == '2') {
      costLeftData();
    }
    if (tabKey == '5') {
      getPatientInfoDepartments();
    }
    if (tabKey == '6') {
      getPatientChargeItemReq(
        1,
        leftListPageSize,
        false,
        leftListSearchKeyword,
      );
    }
  };

  useEffect(() => {
    set_currentSelectedLeftObj(undefined);
    _currentSelectedLeftObj = undefined;
    set_currentResp(undefined);

    if (tabKey == '1') {
      set_tableColumn([...beforeCollectionSearch]);
      set_scrollX(1300);
      set_scrollY(`calc(100vh - 395px)`);
      set_tabSearchKey('name');
      set_tableSearchKey('filter');
      set_leftContentH(`calc(100vh - 380px)`);
    }
    if (tabKey == '3') {
      set_tabSearchKey('responsibilityName');
      set_scrollX(undefined);
      set_leftContentH('calc(100vh - 294px)');
    }

    if (tabKey == '2') {
      set_tableColumn([...beforeCostShareSearch]);
      set_scrollX(undefined);
      set_scrollY(`calc(100vh - 396px)`);
      set_tabSearchKey('name');
      set_tableSearchKey('filter');
      set_leftContentH('calc(100vh - 351px)');
    }

    if (tabKey == '5') {
      set_scrollX(1300);
      set_scrollY(`calc(100vh - 345px)`);
      set_tabSearchKey('name');
      set_tableSearchKey('');
      set_leftContentH(`calc(100vh - 324px)`);
    }
    if (tabKey == '6') {
      set_scrollX(1300);
      set_tabSearchKey('name');
      set_tableSearchKey('filter');
      set_leftListSearchPlaceHolder('患者ID/姓名');
      set_leftContentH(`calc(100vh - 292px)`);
      set_leftListSearchKeyword('');
    }
  }, [tabKey]);

  const calcIdleCost = async () => {
    Modal.confirm({
      title: '注意',
      content: '计算操作会覆盖已有的闲置成本数据，确定要继续操作？',
      okText: '确定',
      cancelText: '取消',
      onOk: async (...args) => {
        const resp = await calcIdleCostReq(computeDate);
        if (resp) {
          costLeftData();
        }
        return true;
      },
    });
  };

  useEffect(() => {
    // 合并为一次驱动：当 computeDate 或 tabKey 变化时，按分支加载一次左侧数据
    if (tabKey == '1') {
      inComeLeftData();
    }
    if (tabKey == '2') {
      costLeftData();
    }
    if (tabKey == '3') {
      costShareLeftData();
    }
    if (tabKey == '5') {
      getPatientInfoDepartments();
    }
    if (tabKey == '6') {
      set_leftListPage(1);
      set_leftListHasMore(true);
      getPatientChargeItemReq(
        1,
        leftListPageSize,
        false,
        leftListSearchKeyword,
      );
    }
    tableRef.current?.reload();
  }, [computeDate, tabKey]);

  useEffect(() => {
    if (btnPerm) {
      const [a, b] = btnPerm.split('|');
      set_ifShowCancelBtn(b == '1');
      set_ifShowGetBtn(a == '1');
    }
  }, [btnPerm]);

  useEffect(() => {
    if (currentSelectedLeftObj) {
      tableRef.current?.reload();
    }
  }, [currentSelectedLeftObj]);

  useEffect(() => {
    if (reload) {
      getLeftDatas();
      tableRef.current?.reload();
    }
  }, [reload]);

  useEffect(() => {
    // console.log({tabKey,currentLeftTab});
    if (tabKey == '1') {
      inComeLeftData();
    }
    if (tabKey == '5') {
      getPatientInfoDepartments();
    }
  }, [currentLeftTab]);

  return (
    <div className="LeftAndRighrStructure">
      {tabKey != '3' && tabKey != '5' && tabKey != '6' && (
        <div className="line">
          <div className="info">
            <img src={require('../../../../static/multiblock.png')} alt="" />
            全部科室合计：
            <span>
              {currentResp
                ? formatMoneyNumber(currentResp.totalAmount)
                : '0.00'}
              元
            </span>
          </div>
          <div className="lineBtnGroup">
            {tabKey == '2' && (
              <span onClick={() => calcIdleCost()}>计算闲置成本</span>
            )}
            {ifShowCancelBtn && (
              <span
                onClick={() =>
                  cancelHandle().then((isOk) => {
                    if (isOk) {
                      set_currentResp(undefined);
                      // getLeftDatas();
                      // tableRef.current?.reload();
                    }
                  })
                }
              >
                撤销
              </span>
            )}
            {ifShowGetBtn && (
              <span
                onClick={() =>
                  getHandle().then((isOk) => {
                    if (isOk) {
                      // getLeftDatas();
                      // tableRef.current?.reload();
                    }
                  })
                }
              >
                获取
              </span>
            )}
          </div>
        </div>
      )}

      <div className="contentWrapper">
        <div className="left">
          {tabKey == '1' && (
            <div className="leftTab">
              <div
                onClick={() => set_currentLeftTab(1)}
                className={currentLeftTab == 1 ? 'tab on' : 'tab'}
              >
                按开单
              </div>
              <div
                onClick={() => set_currentLeftTab(2)}
                className={currentLeftTab == 2 ? 'tab on' : 'tab'}
              >
                按执行
              </div>
            </div>
          )}
          {tabKey == '5' && (
            <div className="leftTab">
              <div
                onClick={() => set_currentLeftTab(1)}
                className={currentLeftTab == 1 ? 'tab on' : 'tab'}
              >
                门诊
              </div>
              <div
                onClick={() => set_currentLeftTab(2)}
                className={currentLeftTab == 2 ? 'tab on' : 'tab'}
              >
                急诊
              </div>
              <div
                onClick={() => set_currentLeftTab(3)}
                className={currentLeftTab == 3 ? 'tab on' : 'tab'}
              >
                住院
              </div>
            </div>
          )}

          <KCIMLeftList
            contentH={leftContentH}
            fieldNames={{
              title: 'responsibilityName',
              key: 'responsibilityCode',
              children: 'child',
            }}
            rowKey={
              tabKey == '1' || tabKey == '2' || tabKey == '5' || tabKey == '6'
                ? 'subText'
                : ''
            }
            dataSource={leftListData}
            searchKey={tabSearchKey}
            onChange={onLeftChange}
            placeholder={leftListSearchPlaceHolder}
            listType={tabKey == '3' ? 'tree' : 'list'}
            icon={
              tabKey == '6'
                ? require('../../../../static/empInfo.png')
                : undefined
            }
            onReachBottom={tabKey == '6' ? onReachBottomLoadMore : undefined}
            loading={leftListLoading}
            useRemoteSearch={tabKey == '6'}
            onSearchChange={onLeftSearchChange}
          />
        </div>
        <div className="right">
          <div
            className="toolBar"
            style={{
              display: tabKey == '1' || tabKey == '2' ? 'flex' : 'none',
            }}
          >
            <div className="leftTool">
              当前科室合计：
              <span>
                {currentResp
                  ? formatMoneyNumber(currentResp.departmentAmount)
                    ? currentResp.departmentAmount
                    : '0.00'
                  : '0.00'}
                元
              </span>
            </div>
            <div className="rightTool">
              <div
                className="filterItem"
                style={{ marginLeft: 16, width: 233 }}
              >
                <span className="label" style={{ whiteSpace: 'nowrap' }}>
                  {' '}
                  检索：
                </span>
                <Input
                  placeholder={'收入项目代码/名称'}
                  allowClear
                  autoComplete="off"
                  suffix={
                    <IconFont
                      type="iconsousuo"
                      style={{ color: '#99A6BF' }}
                      onClick={() => tableDataSearchHandle(`${tableSearchKey}`)}
                    />
                  }
                  onChange={(e) => {
                    set_tableDataSearchKeywords(e.target.value);
                    if (e.target.value.length == 0) {
                      set_tableDataFilterParams({
                        ...tableDataFilterParams,
                        [`${tableSearchKey}`]: '',
                      });
                    }
                  }}
                  onPressEnter={(e) => {
                    set_tableDataFilterParams({
                      ...tableDataFilterParams,
                      [`${tableSearchKey}`]: (e.target as HTMLInputElement)
                        .value,
                    });
                  }}
                />
              </div>
            </div>
          </div>
          {tabKey != '3' &&
            tabKey != '5' &&
            tabKey != '6' &&
            currentSelectedLeftObj && (
              <KCIMTable
                actionRef={tableRef}
                columns={tableColumn}
                rowKey="id"
                request={(params) => getTableData(params)}
                tableAlertRender={false}
                scroll={{ x: scrollX, y: scrollY }}
                params={tableDataFilterParams}
              />
            )}

          {tabKey == '3' && (
            <CostAllocationParamsDeal
              date={computeDate}
              ifShowGetBtn
              ifShowCancelBtn
              responsibilityCode={currentSelectedLeftObj?.responsibilityCode}
              cancelHandle={cancelHandle}
              getHandle={getHandle}
            />
          )}
          {tabKey == '5' && (
            <PatientInfoImport
              date={computeDate}
              ifShowGetBtn
              ifShowCancelBtn
              currentSlectedDepCode={currentSelectedLeftObj?.subText}
              type={currentLeftTab}
              cancelHandle={cancelHandle}
              getHandle={getHandle}
            />
          )}
          {tabKey == '6' && (
            <PatientChargeItemsImport
              date={computeDate}
              cancelHandle={cancelHandle}
              getHandle={getHandle}
              ifShowGetBtn
              ifShowCancelBtn
              currentSlectedPatientNo={currentSelectedLeftObj?.subText}
            />
          )}
        </div>
      </div>
    </div>
  );
};
