import React, { useEffect, useState } from 'react';
import { connect, useModel} from 'umi';
import { Row, Col, Form, Input, Button, Select, Switch, TreeSelect, message, Modal } from 'antd';
import { dispatchHandle } from '@/utils/publicHandle';
import useUpdateEffect from '@/useHooks/useUpdateEffect';

const NodeModal = (props) => {
  const [form] = Form.useForm();
  const { dispatch, addType, addVisible, nodeDetail, isChildLevel, refreshTree, treeType } = props;
  const { nodeInfo } = nodeDetail || {};
  const [currentDetail, setCurrentDetail] = useState({});
  const { initialState, setInitialState } = useModel('@@initialState');

  console.log(`nodeDetail is:`, nodeDetail, `nodeInfo is:`, nodeInfo);
  console.log(`addVisible is:`, addVisible);

  useUpdateEffect(() => {
    // form.resetFields();
  }, [nodeDetail && nodeDetail.id]);
  useEffect(() => {
    form.resetFields();
    //打开的时候
    if (addVisible) {
      if (addType === 'add') {
        setCurrentDetail({});
      } else if (addType === 'edit') {
        console.log(`nodeInfo is:`, nodeInfo);
        setCurrentDetail(nodeInfo);
      }
    } else {
      setCurrentDetail({});
    }
  }, [addVisible, nodeInfo && nodeInfo.id]);

  const handleClose = () => {
    setCurrentDetail({});
    form.resetFields();
    props.handleClose();
  };
  const calcNodeOperate = (payload = {}) => {};
  const handleSubmit = (e) => {
    e && e.preventDefault();
    const {
      handleClose,
      addType,
      isChildLevel,
      treeType,
      projectCurrentNode,
      partCurrentNode,
      user: {
        currentUser
      }
    } = props;
    const nodeDetail = props.nodeDetail;
    const projectId = currentUser && currentUser.currentProjectId;//如果是项目级,部门树无根节点,则projectId为最顶层的parentId
    //const platformType = currentUser && currentUser.currentPlatformType;
    // const platformType = Number(window.localStorage.getItem("platformType"));
    // console.log(`platformType is:`,platformType);
    const { currentPlatformType } = initialState?.currentUser;//从token接口拿
    const platformType = Number(currentPlatformType);
     
    //取当前选中的节点
    let nodeInfo = nodeDetail && nodeDetail.nodeInfo;
    let urlType;
    if (treeType === 'area') {
      urlType = 1; //集团
    } else if (treeType === 'project') {
      urlType = 2; //项目
    } else if (treeType === 'part') {
      urlType = 3; //部门
    }

    form
      .validateFields()
      .then((values) => {
        const payload = values;
        let params = {
          name: payload.name,
          type: urlType, //1,2,3
        };
        //这里比较特殊=======,部门添加如果没有选中节点,则以项目节点为参照点
        if (treeType === 'part' && partCurrentNode === null) {
          nodeInfo = projectCurrentNode && projectCurrentNode.nodeInfo;
        }
        if (isChildLevel) {
          //添加下级,自已的id
          params = {
            ...params,
            parentId: nodeInfo && nodeInfo.id,
          };
        } else {
          //添加平级,找父级
            if (platformType === 2 && partCurrentNode === null) {
              //项目级ID
              params = {
                ...params,
                parentId:projectId,//拿项目信息的projectId,部门树添加的时候
              }
            } else {
                params = {
                  ...params,
                  parentId:
                    treeType === 'part' && partCurrentNode === null
                      ? nodeInfo && nodeInfo.id
                      : nodeInfo && nodeInfo.parentId, //部门树未选中,则以项目树选中的为父级节点
                };
            }
        }
        //编辑状态
        if (addType === 'edit') {
          params = {
            ...params,
            id: nodeInfo && nodeInfo.id,
          };
          delete params.parentId;
        }
        //节点树更新
        dispatchHandle(dispatch, 'universal/account_service_organization_patch', params, () => {
          handleClose();
          //刷新上级节点
          message.success(addType === 'edit' ? '修改节点成功' : '添加节点成功', 2, () => {
            refreshTree({
              treeType,
              urlType,
            });
          });
        });
      })
      .catch((e) => {});
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };
  const formTailLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 12 },
  };

  return (
    <Modal
      width={600}
      title={
        addType === 'edit'
          ? `编辑${nodeDetail?.titleName}节点`
          : `创建${nodeDetail?.titleName || ''}节点`
      }
      visible={addVisible}
      onCancel={handleClose}
      closable={false}
      footer={null}
      centered
    >
      <Form
        form={form}
        initialValues={{ ...currentDetail }}
        key={currentDetail && currentDetail.id}
      >
        <Row>
          <Col md={24}>
            <Form.Item
              name="name"
              {...formItemLayout}
              label="节点名称"
              rules={[{ required: true, message: `请输入节点名称` }]}
            >
              <Input placeholder="请输入" />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col offset={4} span={12}>
            <Button
              loading={props.loading}
              type="primary"
              style={{ marginRight: 30 }}
              onClick={handleSubmit}
            >
              提交
            </Button>
            <Button onClick={handleClose}>取消</Button>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default connect(({ universal, loading,user }) => ({
  universal,user,
  loading: loading.models.universal,
}))(NodeModal);