import React, { useEffect, useRef, useMemo, useState } from 'react';
import { Button, Tabs } from 'antd';
import { connect } from 'umi';
import Flow from '@/components/Flow';
import AuditForm from '@/components/AuditForm';
import { useModel } from '@umijs/max';
import PageContent from '@/components/PageContent';

function Audit(props) {
  const {
    dispatch,
    formItems,
    formData,
    flowDetail,
    simpleFlowDteail,
    loading,
  } = props;
  const [tabActiveKey, setTabActiveKey] = useState('1');
  const ref = useRef();
  const { user } = useModel('userInfo');
  const permission = user?.Permission || {};

  const curItem = useMemo(() => {
    let item = {};
    try {
      item = JSON.parse(localStorage.getItem('currentAudit'));
    } catch (e) {}
    return item;
  }, [1]);

  const editMode = useMemo(() => {
    // 判断是否有权限
    if (permission['func-01-point-bom-flow']) {
      return 1;
    }
    // 判断是否为创建者
    if (user?.IsSuper) {
      return 1;
    }

    return 2;
  }, [permission, flowDetail]);

  useEffect(() => {
    dispatch({
      type: 'flow/queryProcessFlows',
      payload: { ids: Number(curItem.id) },
    });
    dispatch({
      type: 'user/getRoleList',
    });
    dispatch({
      type: 'user/fetchDepV2',
    });
  }, []);

  const onChange = (values) => {
    dispatch({
      type: 'xflow/save',
      payload: {
        formData: values,
      },
    });
  };

  const handleSaveClick = async () => {
    //只修改表单不渲染xflow getGraphData方法找不到，保存接口返回的flowDetail数据
    if (!ref.current?.getGraphData) {
      let param = {
        // name: curItem.name,
        id: Number(curItem.id),
        form_json: JSON.stringify(formItems),
        process_json: JSON.stringify(flowDetail),
        process_simple_json: simpleFlowDteail,
      };
      dispatch({ type: 'flow/saveAuditFlowInfo', payload: param });
      return;
    }
    await ref.current?.getGraphData?.((data, simpleNodes) => {
      let param = {
        // name: curItem.name,
        id: Number(curItem.id),
        form_json: JSON.stringify(formItems),
        process_json: data,
        process_simple_json: simpleNodes,
      };
      dispatch({ type: 'flow/saveAuditFlowInfo', payload: param });
    });
  };
  return (
    <PageContent
      extra={[
        <Button
          key={1}
          loading={loading['flow/saveAuditFlowInfo']}
          type="primary"
          onClick={handleSaveClick}
        >
          保存
        </Button>,
      ]}
      header={{
        title: curItem.name,
      }}
      tabActiveKey={tabActiveKey}
      onTabChange={setTabActiveKey}
      tabList={[
        {
          tab: '表单设计',
          key: '1',
        },
        {
          tab: '流程控制',
          key: '2',
        },
      ]}
    >
      {tabActiveKey == 1 && (
        <AuditForm value={formData} onChange={(values) => onChange(values)} />
      )}
      {tabActiveKey == 2 && (
        <Flow
          meta={{ type: 'edit', editMode, flowId: curItem.id }}
          flowDetail={flowDetail}
          ref={ref}
        />
      )}
    </PageContent>
  );
}
export default connect(({ flow, loading, user, xflow }) => ({
  roleList: flow.roleList,
  loading: loading.effects,
  formItems: xflow.formData,
  flowDetail: flow.flowDetail,
  formData: flow.formData,
  simpleFlowDteail: flow.simpleFlowDteail,
}))(Audit);
