import ModuleTitle from '@/components/ManagementPage/moduleTitle';
import PageContent from '@/components/PageContent';
import { queryWorkReport } from '@/services/smartReport';
import { LeftOutlined } from '@ant-design/icons';
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 defaultData = {
  //   electricity: '1111',
  //   in_water: '22222',
  //   maintain_record: '333',
  //   medicine: '444',
  //   out_water: '666',
  //   push_complete_task: '777',
  //   push_complete_task_per: '888',
  //   push_task: '555',
  //   repair_record: '999',
  //   self_inspection_abnormal_task: '1212',
  //   self_inspection_normal_task: '13123',
  //   self_inspection_task: '1414',
  //   water_electricity: '1515',
  //   water_medicine: '1616',
  //   work_order_complete_task: '1717',
  //   work_order_complete_task_per: '80',
  //   work_order_task: '123',
  //   patrol_safe: 2,
  //   patrol_section: 3,
  //   push_optimize_task: 6,
  //   push_complete_task: 4,
  //   eqData: [
  //     { name: '安全隐患', value: 2 },
  //     { name: '工艺异常', value: 3 },
  //     { name: '设备异常', value: 4 },
  //   ],
  //   mandate_type_con: 1,
  //   mandate_type_group: 2,
  //   mandate_type_pat: 3,
  //   mandate_type_pro: 4,
  //   taskData: [
  //     { name: '工况任务', value: 2 },
  //     { name: '集团任务', value: 3 },
  //     { name: '系统自检', value: 4 },
  //     { name: '生产任务', value: 5 },
  //   ],
  //   chart_check: 1,
  //   chart_part: 2,
  //   chart_section: 3,
  //   repair_record: 4,
  //   maintain_record: 5,
  //   patrol_mandate_record: 6,
  //   reagent_record: 7,
  //   workOrderData: [
  //     { name: '盘点', value: 2 },
  //     { name: '备品备件', value: 3 },
  //     { name: '工艺工单', value: 4 },
  //     { name: '维修工单', value: 5 },
  //     { name: '保养工单', value: 5 },
  //     { name: '巡检工单', value: 5 },
  //     { name: '加药工单', value: 5 },
  //   ],
  //   con_level_five: 6, //较差
  //   con_level_four: 1, //一般
  //   con_level_one: 2, //优秀
  //   con_level_three: 3, //较好
  //   con_level_two: 4, //良好
  //   workScoreData: [
  //     { name: '较差', value: 2 },
  //     { name: '一般', value: 3 },
  //     { name: '优秀', value: 4 },
  //     { name: '较好', value: 5 },
  //     { name: '良好', value: 4 },
  //   ],
  // };

  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, '异常类型统计');
    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, '工况评估统计');
    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();
  };

  return (
    <PageContent closeable={false}>
      <ConfigProvider locale={zhCN}>
        <div className={styles.head}>
          <div className={styles.nameContainer}>
            <LeftOutlined
              onClick={handleOnClick}
              style={{ fontSize: 36, cursor: 'pointer', marginRight: '20px' }}
            />
            <div>
              <div className={styles.name}>智慧运营报告</div>
              <div className={styles.photo}>
                {dayjs(date.stime).format('MM月DD日')}-
                {dayjs(date.etime).format('MM月DD日')}
              </div>
            </div>
          </div>
          <div className={styles.headRight}>
            <div>
              时间：
              <Select
                className={styles.headRightSelect}
                defaultValue="1"
                style={{ width: 180 }}
                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>
        <Spin spinning={loading}>
          <div className={styles.box}>
            <div className={styles.left}>概览</div>
            <div className={styles.title}>无锡锡山水厂</div>
            <div className={styles.content}>
              {/* <div className={styles.item}>智慧运营天数：{}天</div>
          <div className={styles.item}>智慧运营节省金额：{}元</div> */}
              <div className={styles.item}>累计进水：{in_water}</div>
              <div className={styles.item}>累计出水：{out_water}</div>
              <div className={styles.item}>吨水能耗：{water_electricity}</div>
              <div className={styles.item}>吨水药耗：{water_medicine}kg/m³</div>
              <div className={styles.item}>
                系统自检次数：{self_inspection_task}次
              </div>
              <div className={styles.item}>
                优化建议： {push_optimize_task}条
              </div>
              <div className={styles.item}>
                任务完成：{push_complete_task}个
              </div>
              <div className={styles.item}>
                工单完成：{work_order_complete_task}个
              </div>
              <div className={styles.item}>设备维修：{repair_record}个</div>
              <div className={styles.item}>设备保养：{maintain_record}个</div>
            </div>
          </div>
          <div className={styles.box}>
            <ModuleTitle title="水量" />
            <div className={styles.content}>
              <div className={styles.item}>累计进水：{in_water}</div>
              <div className={styles.item}>累计出水：{out_water}</div>
            </div>
          </div>
          <div className={styles.box}>
            <ModuleTitle title="能耗" />
            <div className={styles.content}>
              <div className={styles.item}>吨水能耗：{water_electricity}</div>
              <div className={styles.item}>累计耗电量：{electricity}kwh</div>
            </div>
          </div>
          <div className={styles.box}>
            <ModuleTitle title="药耗" />
            <div className={styles.content}>
              <div className={styles.item}>吨水药耗：{water_medicine}kg/m³</div>
              <div className={styles.item}>累计用药量：{medicine}</div>
            </div>
          </div>
          <div className={styles.box}>
            <ModuleTitle title="系统自检" />
            <div className={styles.threeContent}>
              <div className={styles.numItem}>
                <div>{self_inspection_task}</div>
                <div>自检次数</div>
              </div>
              <div className={styles.numItem}>
                <div>{self_inspection_abnormal_task}</div>
                <div>异常次数</div>
              </div>
              <div className={styles.numItem}>
                <div>{self_inspection_normal_task}</div>
                <div>正常次数</div>
              </div>
            </div>
            <div
              ref={eqDomRef}
              style={{ height: '340px', margin: '10px 0 10px 0' }}
            ></div>
            {/* <div>异常类型统计（设备异常、工艺异常、安全隐患异常）</div> */}
          </div>
          <div className={styles.box}>
            <ModuleTitle title="智慧运营" />
            <div style={{ padding: '20px 20px 0 20px' }}>
              <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: '340px', margin: '10px 0 10px 0' }}
            ></div>
          </div>
          <div className={styles.box}>
            <ModuleTitle title="任务工单" />
            <div className={styles.content}>
              <div className={styles.item}>任务数量：{push_task}</div>
              <div className={styles.item}>工单数量：{work_order_task}</div>
              <div className={styles.item}>
                任务完成数量：{push_complete_task}
              </div>
              <div className={styles.item}>
                工单完成数量：{work_order_complete_task}
              </div>
              <div className={styles.item}>
                任务完成率：{Number(push_complete_task_per)}%
              </div>
              <div className={styles.item}>
                工单完成率：{Number(work_order_complete_task_per)}%
              </div>
              <div className={styles.item}>
                <div ref={taskDomRef} style={{ height: '400px' }}></div>
              </div>
              <div className={styles.item}>
                <div ref={workDomRef} style={{ height: '400px' }}></div>
              </div>
            </div>
          </div>
          <div className={styles.box}>
            <ModuleTitle title="设备维修保养" />
            <div className={styles.content}>
              <div className={styles.item}>维修数量：{repair_record}</div>
              <div className={styles.item}>保养数量：{maintain_record}</div>
            </div>
          </div>
        </Spin>
      </ConfigProvider>
    </PageContent>
  );
};
export default SmartReport;
const getPieOption = (chartData, name) => {
  const option = {
    title: {
      text: name,
      top: '92%',
      left: '50%',
      textAlign: 'center',
      textStyle: {
        color: '#000000',
        fontWeight: 'normal',
        fontSize: 18,
      },
    },
    color: [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc',
    ],
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'horizontal',
      // left: 'left',
      textStyle: {
        color: '#000000',
        fontSize: 18,
      },
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };
  return option;
};
