// 能耗监测
import ChartModule from '@/components/ManagementPage/chartModule';
import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import { getComparisonData } from '@/services/OperationManagement';
import { UnityAction } from '@/utils/utils';
import { useParams } from '@umijs/max';
import { message } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import styles from './manage.less';

const typeParams = [
  {
    // 计划吨水电耗
    type: '5',
    flag: '0',
  },
  {
    // 实际吨水电耗
    type: '5',
    flag: '1',
  },
  {
    // 计划用电量
    type: '6',
    flag: '0',
  },
  {
    // 实际用电量
    type: '6',
    flag: '1',
  },
];

const CostComparison = () => {
  const { projectId } = useParams();

  const [open, setOpen] = useState(false);
  const [chartData, setChartData] = useState([]);
  const [curElecPerCost, setElecPerCost] = useState(0); // 当前月实际吨水电耗
  const [curElecUsed, setCurElecUsed] = useState(0); // 当前月实际用电量

  const defaultTime = {
    s_time: `${dayjs().format('YYYY')}-${dayjs().startOf('year').format('MM')}`,
    e_time: `${dayjs().format('YYYY')}-${dayjs().endOf('year').format('MM')}`,
  };

  const defaultParams = {
    project_id: projectId,
    start: defaultTime.s_time,
    end: defaultTime.e_time,
  };

  const getChartData = () => {
    // 构建请求列表
    const queryList = [];
    for (let index = 0; index < 4; index++) {
      queryList.push(
        getComparisonData({ ...defaultParams, ...typeParams[index] }),
      );
    }
    // 获取四组数据
    return Promise.all(queryList).catch(() => {
      message.error('请求数据失败');
    });
  };

  const getFixed = (maxValue) => {
    // 如果小于1，则保留最后两位不为0的数字
    // 如果大于1小于10，则保留三位
    // 大于10，保留两位
    // 大于100，保留一位
    // 大于1000，不保留
    let fixed = 0;
    if (maxValue < 1) {
      const decimal = maxValue.toFixed(100).toString().split('.')[1];
      const decimalArr = decimal.split('');
      for (let index = 0; index < decimalArr.length; index++) {
        if (decimalArr[index] === '0') {
          fixed++;
        } else {
          break;
        }
      }
      fixed += 2;
    } else if (maxValue < 10) {
      fixed = 3;
    } else if (maxValue < 100) {
      fixed = 2;
    } else if (maxValue < 1000) {
      fixed = 1;
    }
    return fixed;
  };

  const createChartData = async () => {
    const result = await getChartData().catch(() => {
      message.error('获取数据失败');
    });
    if (result && result.length) {
      const [planElecPerCost, actualElecPerCost, planElecUsed, actualElecUsed] =
        result;
      const elecPerCost = { yName: 'kWh/t' };
      const elecUsed = { yName: 'kWh' };
      elecPerCost.xData = [
        ...new Set(
          [
            ...planElecPerCost.map((item) => item.month),
            ...actualElecPerCost.map((item) => item.month),
          ].map((item) => item),
        ),
      ].sort();

      let year = `${dayjs(elecPerCost.xData[0]).year()}`;
      elecPerCost.xData = [];
      for (let index = 0; index < 12; index++) {
        elecPerCost.xData.push(`${year}-${dayjs().month(index).format('MM')}`);
      }

      // 确定保留的小数点
      const elecPerCostValue = [...planElecPerCost, ...actualElecPerCost]
        .map((item) => item.value)
        .reduce((a, b) => Math.max(a, b));
      const elecPerCostFixed = getFixed(elecPerCostValue);
      elecPerCost.dataList = [
        {
          type: 0,
          yIndex: 1,
          name: '计划吨水电耗',
          data: elecPerCost.xData.map((month) => {
            const pItem = planElecPerCost.find((item) => item.month === month);
            if (pItem) {
              return pItem.value.toFixed(elecPerCostFixed);
            }
            return 0;
          }),
        },
        {
          type: 0,
          yIndex: 1,
          name: '实际吨水电耗',
          data: elecPerCost.xData.map((month) => {
            const aItem = actualElecPerCost.find(
              (item) => item.month === month,
            );
            if (aItem) {
              return aItem.value.toFixed(elecPerCostFixed);
            }
            return 0;
          }),
        },
      ];

      elecUsed.xData = [
        ...new Set(
          [
            ...planElecUsed.map((item) => item.month),
            ...actualElecUsed.map((item) => item.month),
          ].map((item) => item),
        ),
      ].sort();

      year = `${dayjs(elecUsed.xData[0]).year()}`;
      elecUsed.xData = [];
      for (let index = 0; index < 12; index++) {
        elecUsed.xData.push(`${year}-${dayjs().month(index).format('MM')}`);
      }

      // 确定保留的小数点
      const elecUsedMaxValue = [...planElecUsed, ...actualElecUsed]
        .map((item) => item.value)
        .reduce((a, b) => Math.max(a, b));
      const elecUsedFixed = getFixed(elecUsedMaxValue);
      elecUsed.dataList = [
        {
          type: 3,
          yIndex: 1,
          name: '计划用电量',
          data: elecUsed.xData.map((month) => {
            const pItem = planElecUsed.find((item) => item.month === month);
            if (pItem) {
              return pItem.value.toFixed(elecUsedFixed);
            }
            return 0;
          }),
        },
        {
          type: 3,
          yIndex: 1,
          name: '实际用电量',
          data: elecUsed.xData.map((month) => {
            const aItem = actualElecUsed.find((item) => item.month === month);
            if (aItem) {
              return aItem.value.toFixed(elecUsedFixed);
            }
            return 0;
          }),
        },
      ];
      elecUsed.chartType = 'bar';
      setChartData([elecPerCost, elecUsed]);

      var curElecPerCost = actualElecPerCost?.find((item) =>
        dayjs().isSame(item?.month, 'month'),
      );
      if (curElecPerCost)
        setElecPerCost(curElecPerCost?.value.toFixed(elecPerCostFixed));

      var curElecUsed = actualElecUsed?.find((item) =>
        dayjs().isSame(item?.month, 'month'),
      );
      if (curElecUsed)
        setCurElecUsed(curElecUsed?.value.toFixed(elecUsedFixed));
    } else {
      setChartData([]);
    }
  };

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

  return (
    <PageContent closeable={false}>
      <PageTitle onReturn={() => UnityAction.sendMsg('menuItem', '首页')}>
        能耗数据
        <div
          onClick={(e) => {
            e.stopPropagation();
            setOpen(!open);
          }}
          style={{ marginLeft: 10 }}
          className={`password-eye ${open ? 'open' : ''}`}
        ></div>
      </PageTitle>

      <div className="card-box" style={{ padding: 20, marginTop: 40 }}>
        <div className={styles.curEnergyCost}>
          <div className={styles.item}>
            <div className={styles.value}>
              {open ? curElecPerCost : '***'}
              <span className={styles.unit}>kWh/t</span>
            </div>
            <div className={styles.name}>当月吨水电耗</div>
          </div>
          <div className={styles.item}>
            <div className={styles.value}>
              {open ? curElecUsed : '***'}
              <span className={styles.unit}>kWh</span>
            </div>
            <div className={styles.name}>当月实际用电量</div>
          </div>
        </div>
        {chartData.length !== 0 && (
          <div
            style={{
              height: '920px',
              display: 'flex',
              flexDirection: 'column',
              justifyContent: 'space-between',
              padding: '60px 0 40px',
            }}
          >
            <div style={{ height: '350px' }}>
              <ChartModule {...chartData[0]} />
            </div>

            <div style={{ height: '350px' }}>
              <ChartModule {...chartData[1]} />
            </div>
          </div>
        )}
      </div>
    </PageContent>
  );
};

export default CostComparison;
