import { addBaseParams, addOptimum, editOptimum } from '@/services/SmartOps';
import {useRequest } from '@umijs/max';
import { message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import BasicParamsForm from './components/BasicParamsForm';
import ControlParamsForm from './components/ControlParamsForm';
import TargetOperatingConditions from './components/TargetOperatingConditions';
import WorkConditionAssessment from './components/WorkConditionAssessment';
import styles from './index.less';

/**
 *
 * @param {number}
 * @returns
 */
const Edit = (props) => {
  const {
    optimum,
    process,
    setProcess,
    onSave,
    setOptimum,
    projectId,
    refresh,
    loading: listLoading,
  } = props;
  const sectionId = 7;
  const [current, setCurrent] = useState();
  // const [currentList, setCurrentList] = useState([]);
  const [edit, setEdit] = useState(false);
  const baseForm = useRef();
  const controlForm = useRef();

  const addBaseRes = useRequest(
    (value) =>
      addBaseParams({
        base_value: JSON.stringify(value),
        project_id: Number(projectId),
        section_id: Number(sectionId),
      }),
    {
      manual: true,
      onSuccess(data) {
        message.success('保存基础参数成功');
        console.log(data);
        setOptimum({ ...optimum, id: data.id });
      },
    },
  );

  const addRes = useRequest(addOptimum, {
    manual: true,
    onSuccess() {
      setEdit(false);
      refresh();
      message.success('新增成功');
    },
  });

  const updateRes = useRequest(editOptimum, {
    manual: true,
    onSuccess() {
      setEdit(false);
      refresh();
      message.success('编辑成功');
    },
  });

  // 新增工况
  const onAddConditions = () => {
    let newPorcess = JSON.parse(JSON.stringify(process));
    newPorcess.base.forEach((item) => {
      item.value = '';
    });
    setProcess(newPorcess);
  };

  const onEdit = (item) => {
    setCurrent(item);
    // setCurrentList(item.optimum_list)
    setEdit(true);
  };

  const onSaveOptmium = (name) => {
    let controlData = controlForm.current.getFieldsValue();

    if (current) {
      // 保存
      updateRes.run({
        name,
        id: current.id,
        control_value: JSON.stringify(controlData),
      });
    } else {
      // 新增
      addRes.run({
        name,
        bid: optimum.id,
        project_id: Number(projectId),
        section_id: Number(sectionId),
        control_value: JSON.stringify(controlData),
      });
    }
  };

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

  const loading =
    listLoading || addBaseRes.loading || updateRes.loading || addRes.loading;

  return (
    <>
      <div className={styles.Row} style={{ marginBottom: 20 }}>
        <div className={styles.Col}>
          <WorkConditionAssessment process={process} projectId={projectId} />
        </div>
        <div className={styles.Col}>
          <TargetOperatingConditions
            list={optimum?.optimum_list || []}
            current={current}
            optimum={optimum}
            onEdit={onEdit}
            onCancel={onSave}
            setCurrent={setCurrent}
            loading={loading}
            onDelete={(id) => updateRes.run({ id, is_delete: 1 })}
          />
        </div>
      </div>
      <div className={styles.Row}>
        <div className={styles.Col}>
          <BasicParamsForm
            ref={baseForm}
            process={process}
            edit={true}
            current={optimum}
            loading={loading}
            onSaveBase={addBaseRes.run}
            changeProcess={(process) => setProcess(process)}
          />
        </div>
        <div className={styles.Col}>
          <ControlParamsForm
            ref={controlForm}
            process={process}
            edit={true}
            current={optimum}
            onSave={onSaveOptmium}
            loading={loading}
            changeProcess={(process) => setProcess(process)}
          />
        </div>
      </div>
    </>
  );
};

export default Edit;
