/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-03-18 15:52:26
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-08-29 15:53:57
 * @FilePath: /CostAccountingSys/src/pages/monthlyInfoCollection/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { DatePicker, message, Tabs, Modal, Spin } from 'antd';
import { Key, useEffect, useState } from 'react';

import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import './style.less';
import IncomeCostDataImport from '../monthlyInfoSearch/incomeCostDataImport';
import { getDicDataBySysId } from '@/services/getDic';
import { LeftAndRighrStructure } from './components/leftAndRighrStructure';
import EmpCostDataImport from '../monthlyInfoSearch/empCostDataImport';
import WholeHospIncomeAndCost from '../monthlyInfoSearch/wholeHospIncomeAndCost';
import TableSelecter from './tableSelector';
import { cancelReq, getReq, oneKeyGetDataReq } from './service';
import { useModel } from '@umijs/max';

const MonthlyInfoCollection = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [computeDate, set_computeDate] = useState<string>(
    initialState ? initialState.computeDate : '',
  );
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >(undefined);
  const [tabs, set_tabs] = useState<any[]>([]);
  const [currentTabKey, set_currentTabKey] = useState('0');
  const [currentSelectedTab, set_currentSelectedTab] = useState<any>(undefined);
  const [tableSelecterVisible, set_tableSelecterVisible] = useState(false);
  const [reload, set_reload] = useState(false);
  const [isModalOpen, set_isModalOpen] = useState(false);

  const onTabChanged = (key: string) => {
    set_currentTabKey(key);
  };

  const getTabs = async () => {
    const { systemId } = JSON.parse(
      localStorage.getItem('currentSelectedTab') as string,
    );
    const resp = await getDicDataBySysId(systemId, 'DATA_COLLECT_TYPE');
    if (resp) {
      const { dataVoList } = resp;
      const tabs = dataVoList.map((a: any) => ({
        ...a,
        label: `${a.name}`,
        key: a.code,
      }));
      const showTabs = tabs.filter((a: any) => a.expandOne == '1');
      set_tabs([{ label: '月度数据导入', key: '0' }, ...showTabs]);
    }
  };

  const oneKeyGetHandle = async () => {
    return new Promise((resolve) => {
      Modal.confirm({
        title: '注意',
        content: '获取操作会覆盖上次获取的数据，确定要继续操作？',
        onOk: async () => {
          try {
            const resp = await oneKeyGetDataReq({ computeDate });
            if (resp) {
              message.success('获取成功！');
              set_reload(true);
              setTimeout(() => {
                set_reload(false);
              }, 1000);
              resolve(true);
            } else {
              resolve(false);
            }
          } catch (error) {
            // 请求失败，处理错误
            console.error(error);
            resolve(false);
          }
        },
        onCancel() {
          resolve(false);
        },
      });
    });
  };
  //撤销请求
  const cancelHandle = async () => {
    const resp = await cancelReq(computeDate, Number(currentTabKey));
    if (resp) {
      message.success('撤销成功！');
      set_reload(true);
      setTimeout(() => {
        set_reload(false);
      }, 1000);
      return Promise.resolve(true);
    }
    return Promise.resolve(false);
  };

  //获取请求
  const getHandle = (): Promise<boolean> => {
    return new Promise((resolve) => {
      Modal.confirm({
        title: '注意',
        content: '获取操作会覆盖上次获取的数据，确定要继续操作？',
        onOk: async () => {
          try {
            const resp = await getReq(computeDate, Number(currentTabKey));

            if (resp) {
              message.success('获取成功！');
              set_reload(true);
              setTimeout(() => {
                set_reload(false);
              }, 1000);
              resolve(true);
            } else {
              resolve(false);
            }
          } catch (error) {
            // 请求失败，处理错误
            console.error(error);
            resolve(false);
          }
        },
        onCancel() {
          resolve(false);
        },
      });
    });
  };

  useEffect(() => {
    const needTab = tabs.filter((a) => a.key == currentTabKey);
    set_currentSelectedTab(needTab[0]);

    if (currentTabKey == '2') {
    }
  }, [currentTabKey]);

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

  return (
    <KCIMPagecontainer className="MonthlyInfoCollection" title={false}>
      <Modal
        title={'拼力获取中...'}
        open={isModalOpen}
        footer={false}
        width={180}
        closable={false}
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          }}
        >
          <Spin />
        </div>
      </Modal>
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="异常详情"
        computeDate={computeDate}
        defaultSelectedKeys={[]}
        open={tableSelecterVisible}
        //onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
      />
      <div className="header">
        <div className="search">
          <span>核算年月：</span>
          <DatePicker
            onChange={(data, dateString) => {
              set_computeDate(dateString);
              setInitialState((s: any) => ({ ...s, computeDate: dateString }));
              set_tableDataFilterParams({
                ...tableDataFilterParams,
                computeDate: dateString,
              });
            }}
            picker="month"
            locale={locale}
            defaultValue={moment(computeDate, 'YYYY-MM')}
            format="YYYY-MM"
            autoComplete="off"
            placeholder="选择年月"
          />
        </div>
        <div className="btnGroup">
          <span
            className="check"
            onClick={() => set_tableSelecterVisible(true)}
          >
            检查
          </span>
          <span className="oneKeyGet" onClick={() => oneKeyGetHandle()}>
            一键获取
          </span>
        </div>
      </div>
      <div className="pageContent">
        <div className="tabWrapper">
          <Tabs
            className="tab"
            defaultActiveKey={tabs.length > 0 ? tabs[0].key : undefined}
            items={tabs}
            key={'key'}
            onChange={(key) => onTabChanged(key)}
          />
        </div>

        <div className="tabContent">
          {currentTabKey == '0' && (
            <IncomeCostDataImport
              date={computeDate}
              btnPerm={
                currentSelectedTab ? currentSelectedTab.expandTwo : '0|0'
              }
            />
          )}
          {(currentTabKey == '1' ||
            currentTabKey == '2' ||
            currentTabKey == '3' ||
            currentTabKey == '5' ||
            currentTabKey == '6') && (
            <LeftAndRighrStructure
              tabKey={currentTabKey}
              computeDate={computeDate}
              reload={reload}
              cancelHandle={cancelHandle}
              getHandle={getHandle}
              btnPerm={
                currentSelectedTab ? currentSelectedTab.expandTwo : '0|0'
              }
            />
          )}
          {currentTabKey == '4' && (
            <EmpCostDataImport
              cancelHandle={cancelHandle}
              getHandle={getHandle}
              date={computeDate}
              btnPerm={
                currentSelectedTab ? currentSelectedTab.expandTwo : '0|0'
              }
            />
          )}
          {currentTabKey == '7' && (
            <WholeHospIncomeAndCost
              cancelHandle={cancelHandle}
              getHandle={getHandle}
              date={computeDate}
              btnPerm={
                currentSelectedTab ? currentSelectedTab.expandTwo : '0|0'
              }
            />
          )}
        </div>
      </div>
    </KCIMPagecontainer>
  );
};

export default MonthlyInfoCollection;
