import { getPendingList } from '@/services/message';
import { getComparisonData } from '@/services/OperationManagement';
import { queryConditionSnapshot } from '@/services/SmartOps';
import { getToken, UnityAction } from '@/utils/utils';
import { LoadingOutlined } from '@ant-design/icons';
import { connect, useParams, useRequest } from '@umijs/max';
import dayjs from 'dayjs';
import { useEffect } from 'react';
import { getScadaPage } from '../../services/OperationManagement';
import styles from './index.less';

const HomePage = (props) => {
  const { projectId } = useParams();
  const { data } = useRequest(queryConditionSnapshot, {
    defaultParams: [{ project_id: projectId }],
  });
  return (
    <div className={styles.content}>
      <LeftContent data={data} />
      <CenterContent />
      <RightContent data={data} />
    </div>
  );
};

const LeftContent = (props) => {
  const { data } = props;
  return (
    <div className={styles.left}>
      <SmartWork data={data} />
      <WaterAmt data={data} />
      <WaterQuality data={data} />
      {/* <Backlog /> */}
    </div>
  );
};
const CenterContent = () => {
  return (
    <div className={styles.centerBox}>
      <Backlog />
      <Scada />
    </div>
  );
};
const RightContent = (props) => {
  const { data } = props;
  return (
    <div className={styles.right}>
      <SelfInspection />
      <Electric data={data} />
      <Medicine />
      {/* <Scada /> */}
    </div>
  );
};

// 水厂工况
const SmartWork = (props) => {
  const { data } = props;
  return (
    <Box
      title="水厂工况"
      onClick={() => UnityAction.sendMsg('menuItem', '工况管理')}
    >
      <div className={styles.scoreBox}>
        <div className={styles.circle}>
          <div className={styles.score}>{data?.score}</div>
          <div className={styles.grade}>{data?.grade}</div>
        </div>
        <div className={styles.scoreTitle}>
          当前运行{data?.grade}，可继续优化
        </div>
      </div>

      <div className={styles.time}>
        {dayjs(data?.clac_time).format('YYYY-MM-DD HH:mm')}
      </div>
    </Box>
  );
};

// 水量监测
const WaterAmt = (props) => {
  const { data } = props;
  const { projectId } = useParams();
  return (
    <Box
      title="水量监测"
      onClick={() => UnityAction.sendMsg('menuItem', '水量监测')}
    >
      <ul>
        <li>
          <div className={styles.value}>{data?.fwa}</div>
          <div className={styles.btn1}>进水量</div>
        </li>
        <li>
          <div className={styles.value}>{data?.dwa}</div>
          <div className={styles.btn2}>产水量</div>
        </li>
      </ul>
    </Box>
  );
};

// 水质监测
const WaterQuality = (props) => {
  const { data } = props;
  const { projectId } = useParams();
  return (
    <Box
      title="水质监测"
      onClick={() => UnityAction.sendMsg('menuItem', '水质监测')}
    >
      <ul>
        <li>
          <div className={styles.value}>{data?.dsan}</div>
          <div className={styles.btn1}>出水余氯</div>
        </li>
        <li>
          <div className={styles.value}>{data?.dtur}</div>
          <div className={styles.btn2}>出水浊度</div>
        </li>
      </ul>
    </Box>
  );
};

// 系统自检
const SelfInspection = connect(({ eqSelfInspection, loading }) => ({
  autoReport: eqSelfInspection.autoReport,
  loading: loading.models['eqSelfInspection'],
}))((props) => {
  const { autoReport, dispatch, loading } = props;
  const { projectId } = useParams();

  const renderStatus = () => {
    if (loading) return <LoadingOutlined />;
    if (autoReport.Status > 0) {
      return (
        <span className={styles.text} style={{ color: '#FE5850' }}>
          异常
        </span>
      );
    }
    return (
      <span className={styles.text} style={{ color: '' }}>
        正常
      </span>
    );
  };

  useEffect(() => {
    dispatch({
      type: 'eqSelfInspection/getAutoPatrol',
      payload: {
        projectId,
      },
    });
  }, []);

  return (
    <Box
      title="系统自检"
      onClick={() => UnityAction.sendMsg('menuItem', '系统自检')}
    >
      <div className={styles.selfCon}>
        <div className={styles.circle}>{renderStatus()}</div>
        <div className={styles.texting}>自检中</div>
      </div>
      <div className={styles.time}>
        {dayjs(autoReport.CreatedTime).format('YYYY-MM-DD HH:mm')}
      </div>
      {/* <div className={styles.insTag}>自检中</div> */}

      {/* <div className={styles.insStatus}>{renderStatus()}</div>
      <div className={styles.time} style={{ marginBottom: 30 }}>
        {dayjs(autoReport.CreatedTime).format('YYYY-MM-DD HH:mm')}
      </div> */}
    </Box>
  );
});

// 能耗监测
const Electric = (props) => {
  const { data } = props;
  const { projectId } = useParams();
  return (
    <Box
      title="能耗监测"
      onClick={() => UnityAction.sendMsg('menuItem', '能耗监测')}
    >
      <ul>
        <li>
          <div className={styles.value}>{data?.elec}</div>
          <div className={styles.btn1}>用电量</div>
        </li>
      </ul>
    </Box>
  );
};
// 药耗监测
const Medicine = () => {
  const { projectId } = useParams();
  const time = dayjs().format('YYYY-MM');

  const { data } = useRequest(getComparisonData, {
    defaultParams: [
      {
        project_id: projectId,
        start: time,
        end: time,
        type: 1,
        flag: 1,
      },
    ],
    formatResult(res) {
      return res[0];
    },
  });
  return (
    <Box
      title="药耗监测"
      onClick={() => UnityAction.sendMsg('menuItem', '药耗监测')}
    >
      <ul>
        <li>
          <div className={styles.value}>{data?.value?.toFixed(2) || '-'}元</div>
          <div className={styles.btn1}>当月吨水药成本</div>
        </li>
      </ul>
    </Box>
  );
};

// 工艺监控
const Scada = () => {
  const { projectId } = useParams();

  const { data } = useRequest(getScadaPage, {
    defaultParams: [{ project_id: projectId }],
    formatResult: (res) => {
      let domain = location.host.includes('pad.greentech.com.cn')
        ? 'https://metawant.greentech.com.cn/'
        : 'http://47.96.12.136:8788/';
      const token = getToken();
      const pageList = res?.filter((item) => item.hide);
      const urls = pageList.map(
        (item) =>
          `${domain}smart-water/scada/index.html#/3dview/${projectId}/${item.id}?JWT-TOKEN=${token}&hideTitle=true`,
      );
      return urls.splice(0, 1);
    },
  });
  return (
    <Box
      title="工艺监控"
      onClick={() => UnityAction.sendMsg('menuItem', '工艺监控')}
    >
      <div className={styles.scada}>
        {data?.map((url) => (
          <iframe style={{ width: '5.7rem', height: '2.64rem' }} src={url} />
        ))}
        <div className={styles.mask}></div>
      </div>
    </Box>
  );
};

// 待办事项
const Backlog = (props) => {
  const { projectId } = useParams();

  const { data, loading } = useRequest(getPendingList, {
    defaultParams: [{ project_id: projectId }],
  });
  const handleClick = (item) => {
    if (item.type === 0) {
      // task
      UnityAction.sendMsg('OpenTaskModal', `mandate_id=${item.origin_id}`);
    } else {
      // order
      UnityAction.sendMsg(
        'OpenWorkOrderModal',
        `order_id=${item.origin_id}&order_type=${item.origin_type}`,
      );
    }
  };
  return (
    <Box
      title={
        <div style={{ display: 'flex' }}>
          待办事项
          {/* <div className={styles.count}>{data?.length || 0}</div> */}
        </div>
      }
      onClick={() => UnityAction.sendMsg('menuItem', '待办事项')}
    >
      <div className={styles.backlog}>
        <div>
          {data?.map((item) => (
            <div
              className={styles.item}
              onClick={(e) => {
                e.stopPropagation();
                handleClick(item);
              }}
            >
              <div className={styles.createTime}>{item.time}</div>
              <div className={styles.titleCon}>
                <div className={styles.point} />
                <div className={styles.titleText}>{item.title}</div>
              </div>

              <div className={styles.bottomCon}>{item.content}</div>
            </div>
          ))}
        </div>
      </div>
    </Box>
  );
};

const Box = ({ title, children, onClick, big }) => {
  return (
    <div
      className={`${styles.box} ${big ? styles.boxBig : ''}`}
      onClick={onClick}
    >
      <div className={styles.titleContent}>
        <div className={styles.line} />
        <div className={styles.boxTitle}>{title}</div>
      </div>
      {/* <span className={styles.boxTitle}>
        <div className={styles.line}></div>
        {title}
      </span> */}
      {children}
    </div>
  );
};

export default HomePage;
