import {
  Row,
  Col,
  Card,
  Tree,
  Form,
  Tabs,
  TreeSelect,
  Input,
  InputNumber,
  Modal,
  Button,
  message,
  Icon,
} from 'antd';
import React, { useState, useEffect } from 'react';
import request from '@/utils/request';
import apis from '@/services/apis';
import moment from 'moment';
import TreedataFrom from './form';
import TreedataAdd from './addForm';
import { connect } from 'dva';
import { add } from 'lodash';
import AuthButton from '@/components/AuthButton';

const { TreeNode, DirectoryTree } = Tree;
const FormItem = Form.Item;
const { Search } = Input;
const { TabPane } = Tabs;

const getTreeFrom = arr => {
  const copy = (arr || []).map(it => ({ ...it, children: undefined }));

  const tree = [];
  for (let inx in copy) {
    const it = copy[inx];
    const key = it.institutionCode;
    const node = {
      key,
      value: it.institutionId,
      title: it.institutionName,
      children: it.children,
      parent: it.parent,
    };
    const parent = key.length === 2 ? undefined : key.substring(0, key.length - 2);

    if (parent) {
      for (let cur of copy) {
        if ((cur.institutionCode || cur.key) === parent) {
          node.parent = cur;
          cur.children = [...(cur.children || []), node];
          break;
        }
      }
    }

    copy[inx] = node;
    tree.push(node);
  }
  return tree.filter(x => !x.parent);
};

const Organization = props => {
  const { user, ...leftProps } = props;

  const [value, setValue] = useState('');
  const [type, setType] = useState();
  const [visible, setVisible] = useState(false);
  const [institutionData, setInstitutionData] = useState({});
  const [confirmLoading, setConfirmLoading] = useState(false);

  const handleOk = () => {
    setConfirmLoading(true);
    try {
      if (value) {
        if (type == 'add') {
          request({
            ...apis.Institution.instSave,
            data: { parentInstitutionId: institutionData.value, institutionName: value },
          })
            .then(data => {
              props.dispatch({
                type: 'user/saveOrganization',
                payload: user.institutionList.concat(data),
              });
              setConfirmLoading(false);
              setVisible(false);

              message.info('操作成功');
            })
            .catch(err => {
              message.info(err.msg || err.message);
            });
        } else {
          request({
            ...apis.Institution.instiAlert,
            urlData: { id: institutionData.value },
            data: { institutionName: value },
          })
            .then(data => {
              props.dispatch({
                type: 'user/saveOrganization',
                payload: user.institutionList.map(x => {
                  if (x.institutionId == institutionData.value) {
                    return { ...x, institutionName: value };
                  }
                  return x;
                }),
              });
              setConfirmLoading(false);
              setVisible(false);
              message.info('操作成功');
            })
            .catch(err => {
              message.info(err.msg || err.message);
            });
        }
      }
    } catch (err) {
      console.error(err);
    }
  };

  const handleCancel = () => {
    setVisible(false);
  };

  const add = row => {
    setVisible(true);
    setType('add');
    setValue();
    setInstitutionData(row);
  };

  const edit = row => {
    setVisible(true);
    setType('edit');
    setValue(row.title);
    setInstitutionData(row);
  };

  const onDelete = row => {
    Modal.confirm({
      title: '确认要删除该组织吗？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        request({
          ...apis.Institution.instiDelete,
          urlData: { id: row.value },
        })
          .then(data => {
            props.dispatch({
              type: 'user/saveOrganization',
              payload: user.institutionList.filter(x => x.institutionId != row.value),
            });
            setConfirmLoading(false);
            setVisible(false);
            message.info('删除成功');
          })
          .catch(err => {
            console.log(err);
            message.info(err.msg || err.message);
          });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const getTitle = item => {
    return (
      <>
        {item.title}
        <AuthButton name="institution.add" noRight={null}>
          <Icon
            type="plus"
            onClick={e => {
              e.stopPropagation(), add(item);
            }}
            style={{marginLeft:'5px'}}
          />
        </AuthButton>
        <AuthButton name="institution.edit" noRight={null}>
          <Icon
            type="edit"
            onClick={e => {
              e.stopPropagation(), edit(item);
            }}
            style={{marginLeft:'5px'}}
          />
        </AuthButton>
        <AuthButton name="institution.delete" noRight={null}>
          <Icon
            type="delete"
            onClick={e => {
              e.stopPropagation(), onDelete(item);
            }}
            style={{marginLeft:'5px'}}
          />
        </AuthButton>
      </>
    );
  };
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={getTitle(item)} key={item.key} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} title={getTitle(item)} />;
    });

  return (
    <>
      <Card style={{ minHeight: '500px' }}>
        <Tree defaultExpandAll>{renderTreeNodes(getTreeFrom(user.institutionList) || [])}</Tree>
      </Card>
      <Modal
        title={type == 'add' ? '新增' : '编辑'}
        visible={visible}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        {type == 'add' && <p>上级公司:{institutionData.title}</p>}
        <Input value={value} onChange={e => setValue(e.target.value)}></Input>
      </Modal>
    </>
  );
};

export default connect(({ user }) => ({
  user: user.currentUser,
}))(Organization);

// import React, { useEffect, useMemo, useRef, useState } from 'react'
// import { TreeSelect } from 'antd'
// import { connect } from 'dva'

// const InstitutionSelect = React.forwardRef((props, ref) => {

//   const { user, ...leftProps } = props

//   const [expandedKeys, setExpandedKeys] = useState([])

//   const treeData = useMemo(() => {
//     return getTreeFrom(user.institutionList) || []
//   }, [user.institutionList])

//   useEffect(() => {
//     setExpandedKeys((user.institutionList || []).map((x) => x.institutionCode))
//   }, [user.institutionList])

//   return (
//     <TreeSelect allowClear treeExpandedKeys={expandedKeys} onTreeExpand={setExpandedKeys} {...leftProps} treeData={treeData} />
//   )
// })

// export default connect(({ user }) => ({
//   user: user.currentUser,
// }))(InstitutioSnelect)
