/*
 * @Author: your name
 * @Date: 2021-11-10 09:33:30
 * @LastEditTime: 2025-05-20 10:53:28
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/pages/index.tsx
 */

import { useModel, history, Location, Helmet } from 'umi';
import './index.less';
import { Skeleton, Drawer, Tooltip } from 'antd';
import { useState, useEffect } from 'react';

import { FastEntry, FastEntryTabType } from './components/FastEntry';
import { RecentlyVisitedItemsType } from './components/RecentlyVisited';
import { todoItem, TodoList } from './components/TodoList';
import { getSysParamsByCode, getUserIndexData, UserInfo } from '@/service';

import { KcimCenterSysId } from '@/constant';
import { createFromIconfontCN } from '@ant-design/icons';

import '../../../public/zhongtaiB.js';
const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

export interface IndexPageType {
  location: Location;
}

const IndexPage: React.FC<IndexPageType> = ({ location }) => {
  const {
    systemLists, //当前医院可选子系统列表
    setInitialState,
    userData,
    customerType,
  } = useModel('@@initialState', (model) => {
    return {
      systemLists: model.initialState?.systemLists,
      setInitialState: model.setInitialState,
      userData: model.initialState?.userData,
      customerType: model.initialState?.customerType,
    };
  });

  const [userInfo, set_userInfo] = useState<UserInfo>();

  const [fastEntry, set_fastEntry] = useState<FastEntryTabType[]>([]);
  const [recentlyVisitedList, set_recentlyVisitedList] = useState<RecentlyVisitedItemsType[]>([]);
  const [todoList, set_todoList] = useState<todoItem[]>([]);
  const [msgRecord, set_msgRecord] = useState([]);

  const [specialPageUrl, setspecialPageUrl] = useState<string | undefined>(undefined);

  const [leftImgUrl, set_leftImgUrl] = useState<string | undefined>(undefined);
  const [leftBgImgUrl, set_leftBgImgUrl] = useState<string | undefined>(undefined);

  const [iframeLoading, set_iframeLoading] = useState(false);

  const [allParams, set_allParams] = useState<any[]>([]);
  const [title, set_title] = useState<string | undefined>(undefined);
  const [welcomTitle, set_welcomTitle] = useState('欢迎进入医管平台');
  const [drawerOpen, set_drawerOpen] = useState(false);

  const onLoadhandle = () => {
    set_iframeLoading(false);
  };

  const getIndexPageDataFunc = async () => {
    const resp = await getUserIndexData();
    if (resp) {
      set_userInfo(resp.userInfo);
      set_leftImgUrl(resp.indexUrl ? resp.indexUrl.split('|')[0] : undefined);
      set_leftBgImgUrl(resp.indexUrl ? resp.indexUrl.split('|')[1] : undefined);
      localStorage.setItem('userInfo', JSON.stringify(resp.userInfo));
      setInitialState((s: any) => ({ ...s, userInfo: resp.userInfo }));
      const fastEntryList = resp.fastEntrance.map((item: any) => ({
        id: item.id,
        name: item.name,
        path: item.path,
        menuId: item.menuId,
        systemId: item.systemId,
        type: item.type,
        contentType: item.contentType,
        url: item.url,
      }));

      set_fastEntry(fastEntryList);

      set_todoList(
        resp.todoList.map((t: any) => ({
          id: t.id,
          status: 1,
          content: t.content,
          createDate: t.createDate,
          taskLevel: t.taskLevel,
          recordTitle: t.recordTitle,
        })),
      );

      set_msgRecord(
        resp.messageRecords.map((t: any) => ({
          title: t.recordTitle,
          date: t.createDate,
          resolveTime: t.resolveTime,
          isProcess: t.isProcess,
          content: t.content,
        })),
      );
    }
  };

  const todoListClickHandle = async (id: number) => {
    set_drawerOpen(true);
    // const resp = await todoListAct([id]);
    // if (resp) {
    //   getIndexPageDataFunc();
    // }
  };

  const setIframeUrl = async (allParams: any[]) => {
    const needItem = allParams.filter((a: any) => a.code == '1644270043527254016');
    const userData = localStorage.getItem('userData');
    let token = '';

    if (userData) {
      const { youshuToken } = JSON.parse(userData);
      token = youshuToken;
    }

    if (needItem.length > 0) {
      setspecialPageUrl(`http://eastern1.kcim-bi.163yun.com/dash/integration/56?rid=${needItem[0].value}&token=${token}`);
    }
  };

  const getAllParamsHanle = async () => {
    const resp = await getSysParamsByCode(KcimCenterSysId);
    if (resp) {
      set_allParams(resp);
    }
  };

  const onClose = () => {
    set_drawerOpen(false);
  };

  const fastEntryOnChangeHandle = () => {
    getIndexPageDataFunc();
  };

  useEffect(() => {
    if (allParams) {
      setIframeUrl(allParams);
      allParams.forEach((item) => {
        if (item.code == '1739124039835848704') {
          set_title(item.value);
        }
        if (item.code == '1739123252502073344') {
          set_welcomTitle(item.value);
        }
      });
    }
  }, [allParams]);

  useEffect(() => {
    getIndexPageDataFunc();
    const t = localStorage.getItem('visitedTabs');
    if (t) {
      const visitedPaths = JSON.parse(t);
      set_recentlyVisitedList(visitedPaths);
    }

    getAllParamsHanle();

    // const url = `${spacialPage[0].url}&token=${youshuToken}`;
  }, []);

  return (
    <div className="indexPage">
      {/* <iframe width={1000} height={800} src="http://localhost:8088/superset/dashboard/5b12b583-8204-08e9-392c-422209c29787/?native_filters_key=q3H6TKjSa58" ></iframe> */}
      <Drawer
        className="MsgProcessDrawer"
        title={null}
        onClose={onClose}
        open={drawerOpen}
        mask={false}
        headerStyle={{ display: 'none' }}
        bodyStyle={{ background: '#F5F7FA' }}
        width={600}
        style={{
          position: 'absolute', // 确保 Drawer 可以被定位
          top: 48,
          bottom: 0, // 距离底部 10%
          height: 'calc(100vh - 50px)', // 设置 Drawer 的高度
        }}
      >
        <div className="drawerHeader">
          <div className="title">
            <span onClick={() => set_drawerOpen(false)}>
              <img src={require('../../../public/images/cancel_black.png')} alt="" />
            </span>
            待办事项
          </div>
        </div>
        <div className="msgInfo">
          <div className="left">
            <img src={require('../../../public/images/todojindo.png')} alt="" />
            <div className="detail">
              <div className="msgtitle">任立群发起了请假申请</div>
              <div className="date">2023-12-26 11:24</div>
            </div>
          </div>
          <div className="right">后勤管理 / 报事报修</div>
        </div>
        <div className="content">
          <div style={{ padding: 8 }}>
            <Skeleton active paragraph={{ rows: 12 }} />
          </div>
        </div>
      </Drawer>
      <Helmet>
        <title>{welcomTitle}</title>
      </Helmet>
      <div className="pageContainer">
        <div className="left">
          <div style={{ padding: 8 }}>
            <div className="leftTitle">{title ? title.split('|')[0] : '默认标题'}</div>
            <div className="leftTitleSub">{title ? title.split('|')[1] : '默认标题'}</div>
          </div>

          <div className="leftContent">
            {specialPageUrl && (
              <div className="iframe" style={{ width: '100%' }}>
                <Skeleton loading={iframeLoading} paragraph={{ rows: 50 }} active />
                <iframe onLoad={() => onLoadhandle()} style={{ width: '100%', height: 'calc(100vh - 180px)', border: 'none' }} src={specialPageUrl}></iframe>
              </div>
            )}
            {!specialPageUrl && (
              <div className="imgWrap" style={{ width: '100%', background: `url(${leftBgImgUrl})` }}>
                <img src={leftImgUrl} alt="" />
              </div>
            )}
          </div>
        </div>
        <div className="right">
          <div className="cardOne">
            <img className="welcomBg" src={'/images/welcom_bg.png'} alt="" />
            <div className="inner">
              <span className="userId">{userInfo?.account}</span>
              <div className="cardOneTitle">{`欢迎回来，${userInfo?.name}`}</div>
              <div className="content">
                <div className="row">
                  <div className="label">
                    <img src={require('../../../public/images/icon-keshi.png')} alt="" />
                    <span>{customerType == '2' ? '组织' : '科室'}</span>
                    <Tooltip title={userInfo?.departmentName}>
                      <span className="departmentName">
                        {userInfo?.departmentName ? userInfo?.departmentName : '-'}
                      </span>
                    </Tooltip>
                  </div>
                  <div className="label">
                    <img src={require('../../../public/images/icon-zhicheng.png')} alt="" />
                    <span>{customerType == '2' ? '职务' : '职称'}</span>
                    <Tooltip title={customerType == '2' ? userInfo?.jobTitle : userInfo?.title}>
                      <span className="departmentName">
                        {customerType == '2' ? (userInfo?.jobTitle ?? '-') : (userInfo?.title ?? '-')}
                      </span>
                    </Tooltip>
                  </div>
                </div>
                <div className="row">
                  <div className="label">
                    <img src={require('../../../public/images/icon-leibie.png')} alt="" />
                    <span>类别</span>
                    <Tooltip title={userInfo?.userCate}>
                      <span className="departmentName">
                        {userInfo?.userCate ? userInfo?.userCate : '-'}
                      </span>
                    </Tooltip>
                  </div>
                  <div className="label">
                    <img src={require('../../../public/images/icon-gangwei.png')} alt="" />
                    <span>岗位</span>
                    <Tooltip title={userInfo?.position}>
                      <span className="departmentName">
                        {userInfo?.position ? userInfo?.position : '-'}
                      </span>
                    </Tooltip>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className="cardTwo">
            <FastEntry data={fastEntry} onChange={() => fastEntryOnChangeHandle()} />
          </div>
          <div className="cardThree">
            <TodoList todoList={todoList} todoListClickHandle={todoListClickHandle} />
          </div>
        </div>
      </div>
    </div>
  );
};

export default IndexPage;
