import { queryBaseList } from '@/services/SmartOps';
import { useParams, useRequest } from '@umijs/max';
import { useEffect, useState } from 'react';
import Edit from './Edit';
import processList from './Mock';
import View from './View';

/**
 *
 * @param {number}
 * @returns
 */
const Work = (props) => {
  const { projectId } = useParams();
  const sectionId = 7;
  const [process, setProcess] = useState(processList[sectionId]);
  const [optimum, setOptimum] = useState({});
  // const [currentList, setCurrentList] = useState([]);
  const [edit, setEdit] = useState(false);

  const listRes = useRequest(queryBaseList, {
    defaultParams: [
      {
        project_id: Number(projectId),
        section_id: Number(sectionId),
      },
    ],
    formatResult(data) {
      let list = data.list || [];
      list.forEach((item) => {
        item.base = {};
        item.optimumList = [];
        try {
          item.base = JSON.parse(item.base_value || '{}');
          // 随机生成最优工况
          let bestIndex = item.optimum_list
            ? Math.floor(Math.random() * item.optimum_list.length)
            : 0;
          item.optimum_list?.forEach((optItem, index) => {
            optItem.control = JSON.parse(optItem.control_value || '{}');

            if (bestIndex == index) {
              optItem.is_best = 1;
              // 把best的数据复制给父级
              item.control = optItem.control;
              item.name = optItem.name;
            }
          });
        } catch (e) {
          console.error(e);
        }
      });
      // if (list.length > 0) setOptimum(list[0]);
      // setCurrentList(list);
      if (optimum) {
        let item = list.find((item) => item.id == optimum.id);
        item && setOptimum(item);
      }
      return list;
    },
  });

  const onEdit = (item) => {
    setOptimum(item);
    setEdit(true);
  };

  const onSave = () => {
    setEdit(false);
  };

  useEffect(() => {
    if (!optimum || Object.keys(optimum).length == 0) return;
    process.control.forEach((item) => {
      item.value = optimum.control?.[item.name] || '';
    });
    process.base.forEach((item) => {
      item.value = optimum.base?.[item.name] || '';
    });
    setProcess({ ...process });
  }, [optimum]);

  return (
    <div>
      {edit ? (
        <Edit
          projectId={projectId}
          optimum={optimum}
          process={process}
          onSave={onSave}
          setOptimum={setOptimum}
          setProcess={setProcess}
          refresh={listRes.refresh}
          loading={listRes.loading}
        />
      ) : (
        <View
          projectId={projectId}
          listRes={listRes}
          current={optimum}
          process={process}
          onEdit={onEdit}
          setCurrent={setOptimum}
          setProcess={setProcess}
          refresh={listRes.refresh}
        />
      )}
    </div>
  );
};

export default Work;
