/*
 * @Author: your name
 * @Date: 2021-11-10 09:33:30
 * @LastEditTime: 2023-10-08 14:43:17
 * @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, Divider } from 'antd';
import { useState, useEffect } from 'react';
import avatar from '../../../public/images/avatar.png';
import TopBar from '@/components/topBar';
import { FastEntry, FastEntryTabType } from './components/FastEntry';
import { RecentlyVisited, RecentlyVisitedItemsType } from './components/RecentlyVisited';
import { todoItem, TodoList } from './components/TodoList';
import { getAllParams, getUserIndexData, todoListAct, UserInfo } from '@/service';
import { MsgRecord } from './components/MsgRecord';
import { getParamsManaTableData } from '../platform/setting/paramsMana/service';


export interface IndexPageType {
  location: Location;
}

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

  const [loading, setLoading] = useState(false);
  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 [iframeLoading, set_iframeLoading] = useState(false);


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

  const getIndexPageDataFunc = async () => {
    const resp = await getUserIndexData();
    if (resp) {

      set_userInfo(resp.userInfo);

      const fastEntryList = resp.fastEntrance.map((item: any) => ({
        name: item.name,
        path: item.path,
        menuId: item.menuId,
        systemId: item.systemId
      }));

      set_fastEntry(fastEntryList);

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

      })));

      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) => {
    const resp = await todoListAct([id]);
    if (resp) {
      getIndexPageDataFunc();
    }
  }

  const setIframeUrl = async () => {

    const resp = await getAllParams();

    if (resp) {
      const needItem = resp.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}&toolbar=[]&hideTitle=true&hideScaleBar=false&&scale=screen&hidePageBar=false&token=${token}`);
      }
    }

  }



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

    setIframeUrl();

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

  }, [])


  return (
    <div className="indexPage">
      <Helmet>
        <title>欢迎进入医管平台</title>
      </Helmet>
      <div className='pageContainer'>
        <div className="profileCard">
          <Skeleton loading={loading} active avatar>
            <div className='wraper'>
              <div className="avatar">
                <img src={avatar} alt="头像" />
              </div>
              <div className="description">
                <div className="rowOne">
                  <div className="info">
                    <div className="name">{userInfo?.name}</div>
                    <div className="baseInfo">
                      {`${userInfo?.gender} | ${userInfo?.title ? userInfo?.title : '-'} | ${userInfo?.major ? userInfo?.major : '-'}`}
                    </div>
                  </div>
                  <div className='staffBaseInfo'>
                    <div className='staffBaseInfoSpan'>
                      <span className='spanName'>人员工号</span>
                      <span className='spanValue'>{userInfo?.account ? userInfo?.account : '-'}</span>
                    </div>
                    <Divider type="vertical" className='Divider' />
                    <div className='staffBaseInfoSpan'>
                      <span className='spanName'>人员类别</span>
                      <span className='spanValue'>{userInfo?.jobTitle ? userInfo?.jobTitle : '-'}</span>
                    </div>
                    <Divider type="vertical" className='Divider' />
                    <div className='staffBaseInfoSpan'>
                      <span className='spanName'>所属科室</span>
                      <span className='spanValue'>{userInfo?.departmentName ? userInfo?.departmentName : '-'}</span>
                    </div>
                    <Divider type="vertical" className='Divider' />
                    <div className='staffBaseInfoSpan'>
                      <span className='spanName'>进院日期</span>
                      <span className='spanValue'>{userInfo?.entryTime ? `${new Date(userInfo?.entryTime).getFullYear()}-${(new Date(userInfo?.entryTime).getMonth() + 1) > 10 ? (new Date(userInfo?.entryTime).getMonth() + 1) : '0' + (new Date(userInfo?.entryTime).getMonth() + 1)}-${(new Date(userInfo?.entryTime).getDate()) > 10 ? (new Date(userInfo?.entryTime).getDate()) : '0' + (new Date(userInfo?.entryTime).getDate())}` : '-'}</span>
                    </div>
                  </div>
                </div>
                <div className="rowTwo">

                  <div className='medicalInfoSpan'>
                    <div className='span'>资格证号：<span>{userInfo?.qualificationCertificateNo ? userInfo?.qualificationCertificateNo : '-'}</span></div>
                    <div className='span'>执业证号：<span>{userInfo?.practiceCertificateNo ? userInfo?.practiceCertificateNo : '-'}</span></div>
                  </div>
                  <div className='medicalInfoSpan'>
                    <div className='span'>医师级别：<span>{userInfo?.doctorLevel ? userInfo?.doctorLevel : '-'}</span></div>
                    <div className='span'>执业状态：<span>{userInfo?.practiceStatus ? userInfo?.practiceStatus : '-'}</span></div>
                  </div>
                  <div className='medicalInfoSpan'>
                    <div className='span'>执业科目：<span>{userInfo?.practiceSubject ? userInfo?.practiceSubject : '-'}</span></div>
                    <div className='span'>备注：<span>{userInfo?.remark ? userInfo?.remark : '-'}</span></div>
                  </div>
                  <div className='medicalInfoSpan'>
                    <div className='span'>执业类别：<span>{userInfo?.practiceCate ? userInfo?.practiceCate : '-'}</span></div>
                  </div>

                </div>
              </div>
            </div>
          </Skeleton>
        </div>
        <div className='cardTwo '>
          <FastEntry data={fastEntry} />
          <RecentlyVisited data={recentlyVisitedList} />
        </div>
        <div className='cardThree'>
          <TodoList todoList={todoList} todoListClickHandle={todoListClickHandle} />
          <MsgRecord list={msgRecord} />
        </div>
        {
          specialPageUrl&&(
            <div className='iframe'>
            <Skeleton loading={iframeLoading} paragraph={{ rows: 50 }} active />
            <iframe
              onLoad={() => onLoadhandle()}
              style={{ width: '100%', height: 'calc(100vh - 40px)', border: 'none' }}
              src={specialPageUrl}
            ></iframe>
          </div>
          )
        }
       
      </div>

    </div>
  );
};

export default IndexPage;
