import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import { queryWorkReport } from '@/services/smartReport';
import { useNavigate, useParams, useRequest } from '@umijs/max';
import { ConfigProvider, DatePicker, Select, Spin } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import dayjs from 'dayjs';
import * as echarts from 'echarts';
import { useEffect, useRef, useState } from 'react';
import styles from './index.less';

const { RangePicker } = DatePicker;

const SmartReport = () => {
  const navigate = useNavigate();
  const { projectId } = useParams();
  const FORMAT = 'YYYY-MM-DD';

  const [showRange, setShowRange] = useState(false);
  const [date, setDate] = useState({
    stime: dayjs().subtract(7, 'day').format(FORMAT),
    etime: dayjs().subtract(1, 'day').format(FORMAT),
  });

  const eqDomRef = useRef(null);
  const eqChartRef = useRef(null);

  const taskDomRef = useRef(null);
  const taskChartRef = useRef(null);

  const workDomRef = useRef(null);
  const workChartRef = useRef(null);

  const workScoreDomRef = useRef(null);
  const workScoreChartRef = useRef(null);

  const {
    data = {},
    run,
    loading,
  } = useRequest(
    (date) =>
      queryWorkReport({
        project_id: projectId,
        ...date,
      }),
    {
      defaultParams: [{ project_id: projectId, ...date }],
      formatResult: (res) => {
        const data = res.data;
        return {
          ...data,
          eqData: [
            { name: '安全隐患', value: data.patrol_safe },
            { name: '工艺异常', value: data.patrol_section },
            { name: '设备异常', value: data.push_complete_task },
          ],
          taskData: [
            { name: '工况任务', value: data.mandate_type_con },
            { name: '集团任务', value: data.mandate_type_group },
            { name: '系统自检', value: data.mandate_type_pat },
            { name: '生产任务', value: data.mandate_type_pro },
          ],
          workOrderData: [
            { name: '盘点', value: data.chart_check },
            { name: '备品备件', value: data.chart_part },
            { name: '工艺工单', value: data.chart_section },
            { name: '维修工单', value: data.repair_record },
            { name: '保养工单', value: data.maintain_record },
            { name: '巡检工单', value: data.patrol_mandate_record },
            { name: '加药工单', value: data.reagent_record },
          ],
          workScoreData: [
            { name: '较差', value: data.con_level_five },
            { name: '一般', value: data.con_level_four },
            { name: '优秀', value: data.con_level_one },
            { name: '较好', value: data.con_level_three },
            { name: '良好', value: data.con_level_two },
          ],
        };
      },
    },
  );

  const handleChange = (value) => {
    const date = { ...date };
    switch (value) {
      case '1':
        date.stime = dayjs().subtract(7, 'day').format(FORMAT);
        date.etime = dayjs().subtract(1, 'day').format(FORMAT);
        setDate(date);
        setShowRange(false);
        run(date);
        break;
      case '2':
        date.stime = dayjs().subtract(1, 'month').format(FORMAT);
        date.etime = dayjs().subtract(1, 'day').format(FORMAT);
        setDate(date);
        setShowRange(false);
        run(date);
        break;
      case '3':
        setShowRange(true);
        break;
    }
  };

  const {
    ele_65,
    ele_66,
    electricity,
    in_water,
    maintain_record,
    medicine,
    out_water,
    push_optimize_task,
    push_complete_task,
    push_complete_task_per,
    push_task,
    repair_record,
    self_inspection_abnormal_task,
    self_inspection_normal_task,
    self_inspection_task,
    water_electricity,
    water_medicine,
    work_order_complete_task,
    work_order_complete_task_per,
    work_order_task,
  } = data;

  useEffect(() => {
    initData();
  }, [data]);

  useEffect(() => {
    eqChartRef.current = echarts.init(eqDomRef.current);
    taskChartRef.current = echarts.init(taskDomRef.current);
    workChartRef.current = echarts.init(workDomRef.current);
    workScoreChartRef.current = echarts.init(workScoreDomRef.current);

    return () => {
      eqChartRef.current.dispose();
      taskChartRef.current.dispose();
      workChartRef.current.dispose();
      workScoreChartRef.current.dispose();
    };
  }, []);

  const initData = () => {
    const eqOption = getPieOption(data.eqData, true);
    if (eqChartRef.current) eqChartRef.current.setOption(eqOption);

    const taskOption = getPieOption(data.taskData);
    if (taskChartRef.current) taskChartRef.current.setOption(taskOption);

    const workOption = getPieOption(data.workOrderData);
    if (workChartRef.current) workChartRef.current.setOption(workOption);

    const workScoreOption = getPieOption(data.workScoreData, true);
    if (workScoreChartRef.current)
      workScoreChartRef.current.setOption(workScoreOption);
  };

  const onChange = (value) => {
    if (!value) return;
    const date = { ...date };
    date.stime = value[0].format(FORMAT);
    date.etime = value[1].format(FORMAT);
    run(date);
    setDate(date);
  };

  const handleOnClick = () => {
    history.back();
  };

  const Box = ({ title, children }) => {
    return (
      <div className={styles.box}>
        <div className={styles.main_in}>
          <div className={styles.titleContent}>{title}</div>
          {children}
        </div>
      </div>
    );
  };

  const TwoBoxItem = ({ label, value, unit }) => {
    return (
      <div className={styles.longWhiteBox}>
        <div className={styles.longWhiteBoxIn}>
          {label}
          <span className={styles.value}>
            {value}
            {unit && <span className={styles.unit}>{unit}</span>}
          </span>
        </div>
      </div>
    );
  };
  const ThreeBoxContent = ({ data }) => {
    return (
      <div className={styles.threeContent}>
        {data?.map((item) => (
          <div className={styles.threeItem}>
            <div className={styles.value}>
              {item.value}
              <span className={styles.unit}>{item.unit}</span>
            </div>
            {item.label}
          </div>
        ))}
      </div>
    );
  };

  const CircleContent = ({ data }) => {
    return (
      <div className={styles.circleContent}>
        {data?.map((item) => (
          <div className={styles.circle}>
            <div className={styles.threeItem}>
              <div className={styles.value}>
                {item.value}
                <span className={styles.unit}>{item.unit}</span>
              </div>
              {item.label}
            </div>
          </div>
        ))}
      </div>
    );
  };

  const CircleThreeContent = ({ data }) => {
    return (
      <div className={styles.circleContent}>
        {data?.map((item) => (
          <div>
            <div
              className={`${styles.circleValue} ${
                Number(item.value) > 999 ? styles.circleValueSmall : ''
              }`}
            >
              {item.value}
            </div>
            <div style={{ textAlign: 'center' }} className={styles.unit}>
              {item.label}
            </div>
          </div>
        ))}
      </div>
    );
  };
  const ThreeContent = ({ data }) => {
    return (
      <div className={styles.circleContent}>
        {data?.map((item) => (
          <div>
            <div className={styles.ValueSmall}>{item.value}</div>
            <div style={{ textAlign: 'center' }} className={styles.unit}>
              {item.label}
            </div>
          </div>
        ))}
      </div>
    );
  };

  return (
    <PageContent closeable={false}>
      <ConfigProvider locale={zhCN}>
        <PageTitle children="智慧运营报告" returnable />
        <div className={styles.head}>
          {/* <div className={styles.name}>智慧运营报告</div> */}
          <div className={styles.photo}>
            {dayjs(date.stime).format('MM月DD日')}-
            {dayjs(date.etime).format('MM月DD日')}
          </div>
          <div className={styles.headRight}>
            <div>
              时间：
              <Select
                className={styles.headRightSelect}
                defaultValue="1"
                style={{ width: '2rem' }}
                onChange={handleChange}
                popupClassName={styles.headRightSelect}
                options={[
                  {
                    value: '1',
                    label: '近7天',
                  },
                  {
                    value: '2',
                    label: '近30天',
                  },
                  {
                    value: '3',
                    label: '自定义时间',
                  },
                ]}
              />
            </div>
            <div>
              {showRange && <RangePicker inputReadOnly onChange={onChange} />}
            </div>
          </div>
        </div>

        <div className={styles.title}>无锡锡山水厂</div>

        <Spin spinning={loading}>
          <div className={styles.scrollContent}>
            <Box title="概览">
              <div className={styles.content}>
                <TwoBoxItem label="累计进水：" value={in_water} />
                <TwoBoxItem label="累计出水：" value={out_water} />

                <ThreeBoxContent
                  data={[
                    {
                      label: '吨水能耗',
                      value: water_electricity,
                      unit: 'kwh',
                    },
                    { label: '吨水药耗', value: water_medicine, unit: 'kg/m³' },
                    {
                      label: '系统自检次数',
                      value: self_inspection_task,
                      unit: '次',
                    },
                  ]}
                />

                <TwoBoxItem
                  label="优化建议："
                  value={push_optimize_task}
                  unit="条"
                />
                <TwoBoxItem
                  label="任务完成："
                  value={push_complete_task}
                  unit="个"
                />

                <ThreeBoxContent
                  data={[
                    {
                      label: '工单完成',
                      value: work_order_complete_task,
                      unit: '个',
                    },
                    { label: '设备维修', value: repair_record, unit: '个' },
                    {
                      label: '设备保养',
                      value: maintain_record,
                      unit: '个',
                    },
                  ]}
                />
              </div>
            </Box>
            <Box title="水量">
              <CircleContent
                data={[
                  { label: '累计进水', value: in_water },
                  { label: '累计出水', value: out_water },
                ]}
              />
            </Box>

            <Box title="能耗">
              <CircleContent
                data={[
                  { label: '吨水能耗', value: water_electricity, unit: '' },
                  { label: '累计耗电量', value: electricity, unit: 'kwh' },
                ]}
              />
            </Box>

            <Box title="药耗">
              <CircleContent
                data={[
                  { label: '吨水药耗', value: water_medicine, unit: 'kg/m³' },
                  { label: '累计用药量', value: medicine },
                ]}
              />
            </Box>

            <div className={styles.box}>
              <div className={styles.main_in}>
                <div className={styles.titleContent}>系统自检</div>
                <ThreeContent
                  data={[
                    { label: '自检次数', value: self_inspection_task },
                    { label: '异常次数', value: self_inspection_abnormal_task },
                    { label: '正常次数', value: self_inspection_normal_task },
                  ]}
                />
                <div className={styles.paddingContent}>
                  <div className={styles.cutLine}></div>
                </div>
                <div style={{ padding: '0.43rem 0.4rem 0' }}>
                  <div className={styles.unit}>异常类型统计：</div>
                  <div
                    ref={eqDomRef}
                    style={{
                      height: '6rem',
                      margin: '0 0 0 0.8rem',
                    }}
                  />
                </div>
              </div>
            </div>

            <div className={styles.box}>
              <div className={styles.main_in}>
                <div className={styles.titleContent}>智慧运营</div>
                <CircleThreeContent
                  data={[
                    {
                      label: '优化条数',
                      value: push_optimize_task,
                      unit: '条',
                    },
                    { label: '超滤能耗(kwh)', value: ele_65 },
                    { label: '反渗透能耗(kwh)', value: ele_66 },
                  ]}
                />
                <div className={styles.paddingContent}>
                  <div className={styles.cutLine}></div>
                </div>
                <div style={{ padding: '0.43rem 0.4rem 0' }}>
                  <div className={styles.unit}>工况评估统计：</div>
                  <div
                    ref={workScoreDomRef}
                    style={{
                      height: '6rem',
                      width: 'calc(100% - 1.2rem)',
                      margin: '0 0 0 0.8rem',
                    }}
                  />
                </div>
                {/* <div style={{ padding: '0.2rem 0.2rem 0 0.2rem' }}>
                <div className={styles.smartText}>
                  优化条数:{push_optimize_task}条
                </div>
                <div className={styles.smartText}>超滤能耗：{ele_65}</div>
                <div className={styles.smartText}>反渗透能耗：{ele_66}</div>
              </div> */}
                {/* <div
                ref={workScoreDomRef}
                style={{ height: '3.4rem', margin: '0.1rem 0 0.1rem 0' }}
              ></div> */}
              </div>
            </div>
            <div className={styles.box}>
              <div className={styles.main_in}>
                <div className={styles.titleContent}>任务工单</div>
                <CircleContent
                  data={[
                    { label: '任务数量', value: push_task },
                    { label: '工单数量', value: work_order_task },
                  ]}
                />
                <CircleContent
                  data={[
                    { label: '任务完成数量', value: push_complete_task },
                    { label: '工单完成数量', value: work_order_complete_task },
                  ]}
                />
                <CircleContent
                  data={[
                    {
                      label: '任务完成率',
                      value: push_complete_task_per,
                      unit: '%',
                    },
                    {
                      label: '工单完成率',
                      value: work_order_complete_task_per,
                      unit: '%',
                    },
                  ]}
                />
                <div style={{ display: 'flex', padding: '0 0.4rem' }}>
                  <div className={styles.item}>
                    <div className={styles.unit}>任务类型统计：</div>
                    <div
                      ref={taskDomRef}
                      style={{
                        height: '6rem',
                        width: '100%',
                        marginTop: '0.2rem',
                      }}
                    ></div>
                  </div>
                  <div className={styles.item}>
                    <div className={styles.unit}>工单类型统计：</div>
                    <div
                      ref={workDomRef}
                      style={{
                        height: '6rem',
                        width: '100%',
                        marginTop: '0.2rem',
                      }}
                    ></div>
                  </div>
                </div>
              </div>
            </div>
            <Box title="设备维修保养">
              <CircleContent
                data={[
                  {
                    label: '维修数量',
                    value: repair_record,
                  },
                  {
                    label: '保养数量',
                    value: maintain_record,
                  },
                ]}
              />
            </Box>
          </div>
        </Spin>
      </ConfigProvider>
    </PageContent>
  );
};
export default SmartReport;
const getPieOption = (chartData, isLeft = false) => {
  const option = {
    color: [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc',
    ],
    tooltip: {
      trigger: 'item',
      textStyle: {
        fontSize: '0.3rem',
      },
    },
    legend: isLeft
      ? {
          orient: 'vertical',
          left: 'left',
          top: 'center',
          textStyle: {
            color: '#000000',
            fontSize: '0.3rem',
          },
        }
      : {
          orient: 'horizontal',
          // itemWidth: 10,
          // itemHeight: 8,
          textStyle: {
            color: '#000000',
            fontSize: '0.3rem',
          },
        },
    series: [
      {
        type: 'pie',
        top: isLeft ? 0 : '20%',
        radius: isLeft ? '60%' : '40%',
        left: isLeft ? '20%' : 0,
        label: { fontSize: '0.3rem' },
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  return option;
};
