import React, { useState, useEffect } from 'react';
import { Popover, Radio, Avatar, Tooltip, Empty, Select } from 'antd';
import style from './index.less';
import moment from 'moment';
import { ChartBoxTitle } from './ChartBox';
import { useRequest } from '@umijs/max';
import {
  getProjectAlarm,
  getIssueList,
  getFaultAnalysis,
  getBreakdownRecord,
  getPatrolRecord,
  getProjectList,
} from '@/Project/services/DataMeter';

const { Option } = Select;

function AlarmCenter(props: DataMeter.IModelsProps) {
  const { child, setActive, layout, subModule, projectId } = props;
  // const [active, setActive] = useState();
  // const active = layout.active || child.find(item => item.show).key;
  const [active, setSelfActive] = useState(
    layout.active || child.find((item) => item.show)?.key,
  );
  const [showTabs, setShowTabs] = useState(false);
  const [title, setTitle] = useState('');
  const [faultActive, setFaultActive] = useState(1);
  const id = projectId || -1;
  const projectAlarmRequest = useRequest(getProjectAlarm, {
    defaultParams: [
      {
        pageSize: 50,
        currentPage: 1,
        msgType: '4,5,6',
        projectId: id,
      },
    ],
  });
  const IssueListRequest = useRequest(getIssueList, {
    defaultParams: [
      {
        projectId: id,
        pageSize: 50,
        currentPage: 1,
      },
    ],
  });
  const faultAnalysisRequest = useRequest(getFaultAnalysis, {
    defaultParams: [id],
  });
  const breakdownRecordRequest = useRequest(getBreakdownRecord, {
    defaultParams: [
      {
        pageSize: 50,
        currentPage: 1,
        projectId: id,
      },
    ],
  });
  const patrolRecordRequest = useRequest(getPatrolRecord, {
    defaultParams: [
      {
        pageSize: 50,
        currentPage: 1,
        projectId: id,
        status: 1,
      },
    ],
  });
  const projectRequest = useRequest(getProjectList, {
    cacheKey: 'projectList',
    staleTime: -1,
  });
  const projectAlarmList = projectAlarmRequest.data?.list || [];
  const issueList = IssueListRequest.data?.list || [];
  const faultAnalysis = faultAnalysisRequest.data?.list || [];
  const breakdownList = breakdownRecordRequest.data?.list || [];
  const patrolList = patrolRecordRequest.data?.list || [];
  const projectList = projectRequest.data?.list || [];

  const getTitle = (title: string) => {
    return (
      <Popover
        placement="topLeft"
        content={<div style={{ maxWidth: '2rem' }}>{title}</div>}
      >
        {title}
      </Popover>
    );
  };
  const onChange = (value: string) => {
    let id = projectId || -1;
    projectAlarmRequest.run({
      pageSize: 50,
      currentPage: 1,
      msgType: value,
      projectId: id,
    });
  };
  const onChangeFault = (value: number) => {
    setFaultActive(value);
  };

  const getBreakdownStatus = (status: number) => {
    switch (status) {
      case 0:
        return '已提交';
      case 1:
        return '已派遣';
      case 2:
        return '已处理';
      default:
        return '';
    }
  };

  const renderContent = () => {
    let content;
    switch (active) {
      case 1:
        if (faultActive == 1) {
          if (faultAnalysis.length > 0) {
            let col = faultAnalysis.map((item: any, index: number) => (
              <tr key={index}>
                <td
                  style={
                    subModule == 0
                      ? { width: '33%', paddingRight: '0.1rem' }
                      : { width: '50%', paddingRight: '0.1rem' }
                  }
                  className={style.alarmTitle}
                >
                  {getTitle(`${item.DeviceName}(${item.DeviceCode})`)}
                </td>
                <td
                  style={
                    subModule == 0
                      ? {
                          width: '33%',
                          paddingRight: '0.1rem',
                          whiteSpace: 'nowrap',
                        }
                      : {
                          width: '50%',
                          paddingRight: '0.1rem',
                          whiteSpace: 'nowrap',
                        }
                  }
                  className={style.alarmTitle}
                >
                  {getTitle(`${item.FaultDescription}`)}
                </td>
              </tr>
            ));
            content = (
              <div
                style={{
                  paddingTop: '0.12rem',
                  paddingLeft: '0.14rem',
                  flex: '1',
                  height: 0,
                }}
              >
                <table
                  className={style.alarmTable}
                  style={{
                    width: 'calc(100% - 12px)',
                    background:
                      'linear-gradient(270deg, rgba(153, 231, 255, 0.8) 0%, #60A8FF 100%)',
                  }}
                >
                  <thead>
                    <tr>
                      <th
                        style={
                          subModule == 0
                            ? { width: '33%', paddingRight: '0.1rem' }
                            : { width: '50%', paddingRight: '0.1rem' }
                        }
                      >
                        设备
                      </th>
                      <th
                        style={
                          subModule == 0
                            ? { width: '33%', paddingRight: '0.1rem' }
                            : { width: '50%', paddingRight: '0.1rem' }
                        }
                      >
                        故障类型
                      </th>
                    </tr>
                  </thead>
                </table>
                <div
                  style={{
                    overflowY: 'scroll',
                    height: 'calc(100% - 0.24rem)',
                  }}
                >
                  <table className={style.alarmTable}>
                    <tbody>{col}</tbody>
                  </table>
                </div>
              </div>
            );
          } else {
            content = <Empty />;
          }
        } else if (faultActive == 2) {
          if (breakdownList.length > 0) {
            let col = breakdownList.map((item: any, idx: number) => (
              <tr
                key={item.id}
                style={
                  idx % 2 == 0
                    ? {
                        background:
                          'linear-gradient(to right, rgba(153, 231, 255, 0.1), rgba(96, 168, 255, 0.1))',
                      }
                    : {
                        background:
                          'linear-gradient(to right, rgba(153, 231, 255, 0.2), rgba(96, 168, 255, 0.2))',
                      }
                }
              >
                <td
                  style={
                    subModule == 0
                      ? { width: '40%', paddingRight: '0.1rem' }
                      : { width: '50%', paddingRight: '0.1rem' }
                  }
                  className={style.alarmTitle}
                >
                  {getTitle(`${item.DeviceName}(${item.DeviceCode})`)}
                </td>
                <td
                  style={
                    subModule == 0
                      ? {
                          width: '20%',
                          paddingRight: '0.1rem',
                          whiteSpace: 'nowrap',
                        }
                      : {
                          width: '50%',
                          paddingRight: '0.1rem',
                          whiteSpace: 'nowrap',
                        }
                  }
                >
                  {moment(item.ReportTime).format('YYYY-MM-DD')}
                </td>
                {subModule == 0 && (
                  <td
                    style={{
                      width: '40%',
                      paddingRight: '0.1rem',
                      whiteSpace: 'nowrap',
                    }}
                    className={style.alarmTitle}
                  >
                    {getTitle(
                      projectList.find(
                        (project: any) => project.ID == item.ProjectId,
                      )?.Name || '无',
                    )}
                  </td>
                )}
              </tr>
            ));
            content = (
              <div
                style={{
                  paddingTop: '0.12rem',
                  paddingLeft: '0.14rem',
                  flex: '1',
                  height: 0,
                }}
              >
                <table
                  className={style.alarmTable}
                  style={{
                    width: 'calc(100% - 12px)',
                    background:
                      'linear-gradient(270deg, rgba(153, 231, 255, 0.8) 0%, #60A8FF 100%)',
                  }}
                >
                  <thead>
                    <tr>
                      <th
                        style={
                          subModule == 0
                            ? { width: '40%', paddingRight: '0.1rem' }
                            : { width: '50%', paddingRight: '0.1rem' }
                        }
                      >
                        设备
                      </th>
                      <th
                        style={
                          subModule == 0
                            ? { width: '20%', paddingRight: '0.1rem' }
                            : { width: '50%', paddingRight: '0.1rem' }
                        }
                      >
                        日期
                      </th>
                      {subModule == 0 && (
                        <th style={{ width: '40%', paddingRight: '0.1rem' }}>
                          项目名称
                        </th>
                      )}
                    </tr>
                  </thead>
                </table>
                <div
                  style={{
                    overflowY: 'scroll',
                    height: 'calc(100% - 0.24rem)',
                  }}
                >
                  <table className={style.alarmTable}>
                    <tbody>{col}</tbody>
                  </table>
                </div>
              </div>
            );
          } else {
            content = <Empty />;
          }
        } else {
          if (patrolList.length > 0) {
            let col = patrolList.map((item: any, idx: number) => (
              <tr
                key={item.id}
                style={
                  idx % 2 == 0
                    ? {
                        background:
                          'linear-gradient(to right, rgba(153, 231, 255, 0.1), rgba(96, 168, 255, 0.1))',
                      }
                    : {
                        background:
                          'linear-gradient(to right, rgba(153, 231, 255, 0.2), rgba(96, 168, 255, 0.2))',
                      }
                }
              >
                <td
                  style={
                    subModule == 0
                      ? { width: '40%', paddingRight: '0.1rem' }
                      : { width: '50%', paddingRight: '0.1rem' }
                  }
                  className={style.alarmTitle}
                >
                  {getTitle(`${item?.RouteInfo?.Name}`)}
                </td>
                <td
                  style={
                    subModule == 0
                      ? {
                          width: '20%',
                          paddingRight: '0.1rem',
                          whiteSpace: 'nowrap',
                        }
                      : {
                          width: '50%',
                          paddingRight: '0.1rem',
                          whiteSpace: 'nowrap',
                        }
                  }
                >
                  {' '}
                  {moment(item.CreatedTime).format('YYYY-MM-DD')}
                </td>
                {subModule == 0 && (
                  <td
                    style={{ width: '40%', paddingRight: '0.1rem' }}
                    className={style.alarmTitle}
                  >
                    {getTitle(
                      projectList.find(
                        (project: any) => project.ID == item.ProjectId,
                      )?.Name || '无',
                    )}
                  </td>
                )}
              </tr>
            ));
            content = (
              <div
                style={{
                  paddingTop: '0.12rem',
                  paddingLeft: '0.14rem',
                  flex: '1',
                  height: 0,
                }}
              >
                <table
                  className={style.alarmTable}
                  style={{
                    width: 'calc(100% - 12px)',
                    background:
                      'linear-gradient(270deg, rgba(153, 231, 255, 0.8) 0%, #60A8FF 100%)',
                  }}
                >
                  <thead>
                    <tr>
                      <th
                        style={
                          subModule == 0
                            ? { width: '40%', paddingRight: '0.1rem' }
                            : { width: '50%', paddingRight: '0.1rem' }
                        }
                      >
                        路线名称
                      </th>
                      <th
                        style={
                          subModule == 0
                            ? { width: '20%', paddingRight: '0.1rem' }
                            : { width: '50%', paddingRight: '0.1rem' }
                        }
                      >
                        日期
                      </th>
                      {subModule == 0 && (
                        <th style={{ width: '40%', paddingRight: '0.1rem' }}>
                          项目名称
                        </th>
                      )}
                    </tr>
                  </thead>
                </table>
                <div
                  style={{
                    overflowY: 'scroll',
                    height: 'calc(100% - 0.24rem)',
                  }}
                >
                  <table className={style.alarmTable}>
                    <tbody>{col}</tbody>
                  </table>
                </div>
              </div>
            );
          } else {
            content = <Empty />;
          }
        }
        break;
      case 2:
        if (projectAlarmList.length > 0) {
          let col = projectAlarmList.map((item: any, idx: number) => (
            <tr
              key={item.id}
              style={
                idx % 2 == 0
                  ? {
                      background:
                        'linear-gradient(to right, rgba(153, 231, 255, 0.1), rgba(96, 168, 255, 0.1))',
                    }
                  : {
                      background:
                        'linear-gradient(to right, rgba(153, 231, 255, 0.2), rgba(96, 168, 255, 0.2))',
                    }
              }
            >
              {/* <td>{item.MsgBody}</td> */}
              <td
                style={{ width: '40%', paddingRight: '0.1rem' }}
                className={style.alarmTitle}
              >
                {getTitle(item.MsgBody)}
              </td>
              {/* <td>{item.ReadStatus == 1 ? '已读' : '未读'}</td> */}
              <td
                style={
                  subModule == 0
                    ? {
                        width: '20%',
                        paddingRight: '0.1rem',
                        whiteSpace: 'nowrap',
                      }
                    : {
                        width: '50%',
                        paddingRight: '0.1rem',
                        whiteSpace: 'nowrap',
                      }
                }
              >
                {moment(item.CreatedOn).format('YYYY-MM-DD')}
              </td>
              {subModule == 0 && (
                <td
                  style={{ width: '40%', paddingRight: '0.1rem' }}
                  className={style.alarmTitle}
                >
                  {getTitle(
                    projectList.find(
                      (project: any) => project.ID == item?.Project?.ID,
                    )?.Name || '无',
                  )}
                </td>
              )}
            </tr>
          ));
          content = (
            <div
              style={{
                paddingTop: '0.12rem',
                paddingLeft: '0.14rem',
                flex: '1',
                height: 0,
              }}
            >
              <table
                className={style.alarmTable}
                style={{
                  width: 'calc(100% - 12px)',
                  background:
                    'linear-gradient(270deg, rgba(153, 231, 255, 0.8) 0%, #60A8FF 100%)',
                }}
              >
                <thead>
                  <tr>
                    <th
                      style={
                        subModule == 0
                          ? { width: '40%', paddingRight: '0.1rem' }
                          : { width: '50%', paddingRight: '0.1rem' }
                      }
                    >
                      预警内容
                    </th>
                    {/* <th>状态</th> */}
                    <th
                      style={
                        subModule == 0
                          ? { width: '20%', paddingRight: '0.1rem' }
                          : { width: '50%', paddingRight: '0.1rem' }
                      }
                    >
                      日期
                    </th>
                    {subModule == 0 && (
                      <th style={{ width: '40%', paddingRight: '0.1rem' }}>
                        项目名称
                      </th>
                    )}
                  </tr>
                </thead>
              </table>
              <div
                style={{
                  overflowY: 'scroll',
                  height: 'calc(100% - 0.24rem)',
                }}
              >
                <table className={style.alarmTable}>
                  <tbody>{col}</tbody>
                </table>
              </div>
            </div>
          );
        } else {
          content = <Empty />;
        }
        break;
      case 3:
        if (issueList.length > 0) {
          let col = issueList.map((item: any, idx: number) => (
            <tr
              key={item.id}
              style={
                idx % 2 == 0
                  ? {
                      background:
                        'linear-gradient(to right, rgba(153, 231, 255, 0.1), rgba(96, 168, 255, 0.1))',
                    }
                  : {
                      background:
                        'linear-gradient(to right, rgba(153, 231, 255, 0.2), rgba(96, 168, 255, 0.2))',
                    }
              }
            >
              {/* <td>{item.title}</td> */}
              <td
                style={
                  subModule == 0
                    ? { width: '25%', paddingRight: '0.1rem' }
                    : { width: '33%', paddingRight: '0.1rem' }
                }
                className={style.alarmTitle}
              >
                {getTitle(item.title)}
              </td>
              {/* <td>{STATUS[item.status]}</td> */}
              <td
                style={
                  subModule == 0
                    ? { width: '25%', paddingRight: '0.1rem' }
                    : { width: '33%', paddingRight: '0.1rem' }
                }
                className={style.alarmTitle}
              >
                {getTitle(STATUS[item.status as keyof typeof STATUS])}
              </td>
              <td
                style={
                  subModule == 0
                    ? {
                        width: '20%',
                        paddingRight: '0.1rem',
                        whiteSpace: 'nowrap',
                      }
                    : {
                        width: '33%',
                        paddingRight: '0.1rem',
                        whiteSpace: 'nowrap',
                      }
                }
              >
                {moment(item.c_time).format('YYYY-MM-DD')}
              </td>
              {subModule == 0 && (
                <td
                  style={{ width: '30%', paddingRight: '0.1rem' }}
                  className={style.alarmTitle}
                >
                  {getTitle(
                    projectList.find(
                      (project: any) => project.ID == item.project_id,
                    )?.Name || '无',
                  )}
                </td>
              )}
            </tr>
          ));
          content = (
            <div
              style={{
                paddingTop: '0.12rem',
                paddingLeft: '0.14rem',
                flex: '1',
                height: 0,
              }}
            >
              <table
                className={style.alarmTable}
                style={{
                  width: 'calc(100% - 12px)',
                  background:
                    'linear-gradient(270deg, rgba(153, 231, 255, 0.8) 0%, #60A8FF 100%)',
                }}
              >
                <thead>
                  <tr>
                    <th
                      style={
                        subModule == 0
                          ? { width: '25%', paddingRight: '0.1rem' }
                          : { width: '33%', paddingRight: '0.1rem' }
                      }
                    >
                      标题
                    </th>
                    <th
                      style={
                        subModule == 0
                          ? { width: '25%', paddingRight: '0.1rem' }
                          : { width: '33%', paddingRight: '0.1rem' }
                      }
                    >
                      状态
                    </th>
                    <th
                      style={
                        subModule == 0
                          ? { width: '20%', paddingRight: '0.1rem' }
                          : { width: '33%', paddingRight: '0.1rem' }
                      }
                    >
                      日期
                    </th>
                    {subModule == 0 && (
                      <th style={{ width: '30%', paddingRight: '0.1rem' }}>
                        项目名称
                      </th>
                    )}
                  </tr>
                </thead>
              </table>
              <div
                style={{
                  overflowY: 'scroll',
                  height: 'calc(100% - 0.24rem)',
                }}
              >
                <table className={style.alarmTable}>
                  <tbody>{col}</tbody>
                </table>
              </div>
            </div>
          );
        } else {
          content = <Empty />;
        }
        break;
      case 4:
        var total: any = [];
        var id = 1;
        issueList.forEach((item: any) => {
          id++;
          total.push({
            id,
            title: item.title,
            status: STATUS[item.status as keyof typeof STATUS],
            time: new Date(item.c_time),
            project_id: item.project_id,
          });
        });
        projectAlarmList.forEach((item: any) => {
          id++;
          total.push({
            id,
            title: item.MsgBody,
            status: item.ReadStatus == 1 ? '已读' : '未读',
            time: new Date(item.CreatedOn),
            project_id: item.Project?.ID,
          });
        });
        faultAnalysis.forEach((item: any) => {
          id++;
          total.push({
            id,
            title: item.FaultDescription,
            status: '-',
            time: new Date(item.AnalysisTime),
            project_id: item.ProjectId,
          });
        });
        patrolList.forEach((item: any) => {
          id++;
          total.push({
            id,
            title: item?.RouteInfo?.Name,
            status: '异常',
            time: new Date(item.CreatedTime),
            project_id: item.ProjectId,
          });
        });
        breakdownList.forEach((item: any) => {
          id++;
          total.push({
            id,
            title: `${item.DeviceName}(${item.DeviceCode})`,
            status: getBreakdownStatus(item.AcceptanceStatus),
            time: new Date(item.ReportTime),
            project_id: item.ProjectId,
          });
        });
        total.sort((a: any, b: any) => b.time - a.time);
        if (total.length > 0) {
          let col = total.map((item: any, idx: number) => (
            <tr
              key={item.id}
              style={
                idx % 2 == 0
                  ? {
                      background:
                        'linear-gradient(to right, rgba(153, 231, 255, 0.1), rgba(96, 168, 255, 0.1))',
                    }
                  : {
                      background:
                        'linear-gradient(to right, rgba(153, 231, 255, 0.2), rgba(96, 168, 255, 0.2))',
                    }
              }
            >
              <td
                style={
                  subModule == 0
                    ? { width: '25%', paddingRight: '0.1rem' }
                    : { width: '33%', paddingRight: '0.1rem' }
                }
                className={style.alarmTitle}
              >
                {getTitle(item.title)}
              </td>
              <td
                style={
                  subModule == 0
                    ? { width: '15%', paddingRight: '0.1rem' }
                    : { width: '33%', paddingRight: '0.1rem' }
                }
                className={style.alarmTitle}
              >
                {getTitle(item.status)}
              </td>
              <td
                style={
                  subModule == 0
                    ? {
                        width: '20%',
                        paddingRight: '0.1rem',
                        whiteSpace: 'nowrap',
                      }
                    : {
                        width: '33%',
                        paddingRight: '0.1rem',
                        whiteSpace: 'nowrap',
                      }
                }
              >
                {moment(item.time).format('YYYY-MM-DD')}
              </td>
              {subModule == 0 && (
                <td
                  style={{ width: '40%', paddingRight: '0.1rem' }}
                  className={style.alarmTitle}
                >
                  {getTitle(
                    projectList.find(
                      (project: any) => project.ID == item.project_id,
                    )?.Name || '无',
                  )}
                </td>
              )}
            </tr>
          ));
          content = (
            <div
              style={{
                paddingTop: '0.12rem',
                paddingLeft: '0.14rem',
                flex: '1',
                height: 0,
              }}
            >
              <table
                className={style.alarmTable}
                style={{
                  width: 'calc(100% - 12px)',
                  background:
                    'linear-gradient(270deg, rgba(153, 231, 255, 0.8) 0%, #60A8FF 100%)',
                }}
              >
                <thead>
                  <tr>
                    <th
                      style={
                        subModule == 0
                          ? { width: '25%', paddingRight: '0.1rem' }
                          : { width: '33%', paddingRight: '0.1rem' }
                      }
                    >
                      预警内容
                    </th>
                    <th
                      style={
                        subModule == 0
                          ? { width: '15%', paddingRight: '0.1rem' }
                          : { width: '33%', paddingRight: '0.1rem' }
                      }
                    >
                      状态
                    </th>
                    <th
                      style={
                        subModule == 0
                          ? { width: '20%', paddingRight: '0.1rem' }
                          : { width: '33%', paddingRight: '0.1rem' }
                      }
                    >
                      日期
                    </th>
                    {subModule == 0 && (
                      <th style={{ width: '40%', paddingRight: '0.1rem' }}>
                        项目名称
                      </th>
                    )}
                  </tr>
                </thead>
              </table>
              <div
                style={{
                  overflowY: 'scroll',
                  height: 'calc(100% - 0.24rem)',
                }}
              >
                <table className={style.alarmTable}>
                  <tbody>{col}</tbody>
                </table>
              </div>
            </div>
          );
        } else {
          content = <Empty />;
        }
        break;
    }
    return content;
  };

  useEffect(() => {
    let current = child.find((item) => item.key == active);
    if (current) {
      setTitle(current.title);
    }
  }, [active]);

  // useEffect(() => {
  //   if (child.active) {
  //     setActive(child.active);
  //   } else {
  //     let firstKey = child.find(item => item.show).key;
  //     setActive(firstKey);
  //   }
  // }, [child]);

  const STATUS = {
    0: '待处理',
    1: '现场经理协同处理中',
    2: '项目经理审核中',
    3: '项目经理协同处理中',
    4: '总监审核中',
    5: '总监协同处理中',
    6: 'coo协调处理中',
    7: '已完成',
  };

  return (
    <div className={style.modelBox}>
      {/* <ModelTitle type={2} active={showTabs} setActive={setShowTabs}>
        {title == '全部' ? '报警中心' : title}
      </ModelTitle> */}
      <ChartBoxTitle
        title={title == '全部' ? '报警中心' : title}
        showTabs={showTabs}
        setShowTabs={setShowTabs}
        width={layout.w}
      />
      {showTabs && (
        <ul className={style.tabsList}>
          {(child || [])
            .filter((item) => item.show)
            .map((item) => (
              <li
                key={item.key}
                className={`${active == item.key ? style.active : ''}`}
                onClick={() => {
                  setActive(item.key);
                  setSelfActive(item.key);
                }}
              >
                {item.title}
              </li>
            ))}
        </ul>
      )}
      {active == 2 && (
        <Select
          className={style.activeSelect}
          onChange={onChange}
          dropdownClassName="dataMeter"
          // style={{ width: 200, marginLeft: '0.16rem', marginTop: 10 }}
          defaultValue="4,5,6"
          options={[
            { value: '4,5,6', label: '全部' },
            { value: '4', label: '非关键节点预警' },
            { value: '5', label: '关键节点预警' },
            { value: '6', label: '问题工单逾期预警' },
          ]}
        ></Select>
      )}
      {active == 1 && (
        <Select
          className={style.activeSelect}
          onChange={onChangeFault}
          dropdownClassName="dataMeter"
          // style={{ width: 200, marginLeft: '0.16rem', marginTop: 10 }}
          defaultValue={faultActive}
        >
          <Option value={1}>工艺诊断异常</Option>
          <Option value={2}>设备故障</Option>
          <Option value={3}>巡检故障</Option>
        </Select>
      )}
      {renderContent()}
    </div>
  );
}

export default AlarmCenter;
