import React, { useState, useEffect, useCallback } from 'react';
import {
  Table,
  Input,
  Select,
  Checkbox,
  Pagination,
  Button,
  Dialog,
  Form
} from '@alifd/next';
import IceContainer from '@icedesign/container';
import lodashFind from 'lodash.find';
import SortableTree from 'react-sortable-tree';
import PageHead from '@/components/page-head';
import getCustomHeader from '@/components/token-header';
import styles from './index.module.scss';

import { ajax } from '@/utils';
import newTreeTheme from './tree-theme';
const FormItem = Form.Item;
const formItemWidth = '500px';
const dialogDefaultItem = {
  id: '',
  parentId: ''
};
const departmentDialogDefaultItem = {
  dialogTitle: '添加子部门',
  name: '',
  parentId: '0',
  weight: 0,
  parentIdDisabled: false,
  leaders: ''
};
const DepartmentTree = ({ title }) => {
  const [isLoading, setLoading] = useState(false);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [departmentDialogVisible, setDepartmentDialogVisible] = useState(false);
  const [dialogData, setDialogData] = useState({ ...dialogDefaultItem });
  const [departmentDialogData, setDepartmentDialogData] = useState({
    ...departmentDialogDefaultItem
  });
  const [data, setData] = useState([]);
  const [currentDepartmentInfo, setCurrentDepartmentInfo] = useState({});
  const [currentDepartEmployees, setCurrentDepartEmployees] = useState([]);
  useEffect(() => {
    fetchData();
  }, []);
  const treeDataFormatter = data => {
    const looper = dataList => {
      dataList.forEach(item => {
        item.title = item.name;
        if (item.children && item.children[0]) {
          looper(item.children);
        } else {
          item.children = async ({ done }) => {
            const responseData = await ajax({
              api: 'getDepartment',
              method: 'get',
              type: 'json',
              data: { id: item.id },
              contentType: 'application/json'
            });
            done(treeDataFormatter(responseData.result));
          };
        }
      });
      return dataList;
    };
    return looper(data);
  };
  const fetchData = useCallback(async () => {
    await setLoading(true);
    try {
      const responseData = await ajax({
        api: 'getDepartment',
        method: 'get',
        type: 'json',
        data: { id: 0 },
        contentType: 'application/json'
      });

      await setLoading(false);
      if (responseData.success) {
        await setData(treeDataFormatter(responseData.result));
      } else {
      }
    } catch (e) {}
  });

  const addEmployeeForDepartment = async values => {
    const submitData = {};
    if (dialogData.parentId) {
      submitData.id = dialogData.parentId;
      submitData.addEmployeeIds = [values.id];
    }
    try {
      const responseData = await ajax({
        api: 'addEmployeeForDepartment',
        method: 'post',
        type: 'json',
        data: JSON.stringify(submitData),
        contentType: 'application/json',
        headers: getCustomHeader()
      });
      setDialogVisible(false);
      if (responseData.success) {
        location.reload();
      } else {
        Dialog.alert({
          title: '操作失败！',
          content: responseData.message || `系统错误请稍后再试~`
        });
      }
    } catch (e) {
      setDialogVisible(false);
      Dialog.alert({
        title: '操作失败！',
        content: `系统错误请稍后再试~`
      });
    }
    // async;
  };

  const addOrEditDepartment = async values => {
    // console.log('department-->', values);
    let submitData = { ...values };
    if (departmentDialogData.id) {
      submitData.id = departmentDialogData.id;
    }
    try {
      const apiUrl =
        departmentDialogData.id !== undefined
          ? 'editDepartment'
          : 'addDepartment';
      const responseData = await ajax({
        api: apiUrl,
        method: 'post',
        type: 'json',
        data: JSON.stringify(submitData),
        contentType: 'application/json',
        headers: getCustomHeader()
      });
      setDepartmentDialogVisible(false);
      if (responseData.success) {
        location.reload();
      } else {
        Dialog.alert({
          title: '操作失败！',
          content: responseData.message || `系统错误请稍后再试~`
        });
      }
    } catch (e) {
      setDepartmentDialogVisible(false);
      Dialog.alert({
        title: '操作失败！',
        content: `系统错误请稍后再试~`
      });
    }
    // async;
  };

  const confirmDepartmentDelete = currentDepartmentInfo => {
    Dialog.confirm({
      title: '确认删除吗？',
      content:
        '确认删除部门【' + currentDepartmentInfo.name + '】吗? 此操作不可逆',
      onOk: async () => {
        try {
          const responseData = await ajax({
            api: 'removeDepartment',
            method: 'post',
            type: 'json',
            data: JSON.stringify({ id: currentDepartmentInfo.id }),
            contentType: 'application/json',
            headers: getCustomHeader()
          });
          if (responseData.success) {
            location.reload();
          } else {
            Dialog.alert({
              title: '操作失败！',
              content: responseData.message || `系统错误请稍后再试~`
            });
          }
        } catch (e) {
          Dialog.alert({
            title: '操作失败！',
            content: `系统错误请稍后再试~`
          });
        }
      }
    });
  };
  const confirmEmployeeDelete = employee => {
    Dialog.confirm({
      title: '确认移除吗？',
      content:
        '确认从部门移除员工【' +
        employee.name +
        '】吗? 此操作不会删除员工，仅从该部门移除',
      onOk: async () => {
        const submitData = {};
        submitData.id = currentDepartmentInfo.id; //department id
        submitData.removeEmployeeIds = [employee.id];
        try {
          const responseData = await ajax({
            api: 'removeEmployeeForDepartment',
            method: 'post',
            type: 'json',
            data: JSON.stringify(submitData),
            contentType: 'application/json',
            headers: getCustomHeader()
          });
          if (responseData.success) {
            location.reload();
          } else {
            Dialog.alert({
              title: '操作失败！',
              content: responseData.message || `系统错误请稍后再试~`
            });
          }
        } catch (e) {
          Dialog.alert({
            title: '操作失败！',
            content: `系统错误请稍后再试~`
          });
        }
      }
    });
  };

  const renderDialogWithData = dialogItem => {
    return (
      <Dialog
        title={dialogItem.dialogTitle}
        visible={dialogVisible}
        footer={false}
        // style={{ width: '60%' }}
        onClose={() => setDialogVisible(false)}
      >
        <Form labelAlign="top">
          <FormItem label="员工ID:">
            <Input
              placeholder="员工ID"
              id="id"
              name="id"
              defaultValue={dialogItem.id}
              style={{ width: formItemWidth }}
            />
          </FormItem>

          <FormItem>
            <Form.Submit type="primary" onClick={addEmployeeForDepartment}>
              提交
            </Form.Submit>
          </FormItem>
        </Form>
      </Dialog>
    );
  };
  const renderDepartmentDialogWithData = dialogItem => {
    return (
      <Dialog
        title={dialogItem.dialogTitle}
        visible={departmentDialogVisible}
        footer={false}
        // style={{ width: '60%' }}
        onClose={() => setDepartmentDialogVisible(false)}
      >
        <Form labelAlign="top">
          <FormItem label="部门名称:">
            <Input
              placeholder="请输入部门名称"
              id="name"
              name="name"
              defaultValue={dialogItem.name}
              style={{ width: formItemWidth }}
            />
          </FormItem>

          <FormItem label="顺序:">
            <Input
              placeholder="请输入显示顺序"
              id="weight"
              name="weight"
              defaultValue={dialogItem.weight}
              style={{ width: formItemWidth }}
            />
          </FormItem>
          <FormItem label="父级部门:">
            <Input
              placeholder="请输入父级部门ID:"
              id="parentId"
              name="parentId"
              // disabled={dialogItem.parentIdDisabled}
              defaultValue={dialogItem.parentId}
              style={{ width: formItemWidth }}
            />
          </FormItem>
          <FormItem label="部门领导:">
            <Input
              placeholder="请输入部门领导"
              id="leaders"
              name="leaders"
              defaultValue={dialogItem.leaders}
              style={{ width: formItemWidth }}
            />
          </FormItem>

          <FormItem>
            <Form.Submit type="primary" onClick={addOrEditDepartment}>
              提交
            </Form.Submit>
          </FormItem>
        </Form>
      </Dialog>
    );
  };

  const viewDepartmentDetail = async ({ node, path, treeIndex }) => {
    // console.log(node, path);
    setCurrentDepartmentInfo(node);
    await setLoading(true);
    try {
      const responseData = await ajax({
        api: 'getDepartmentAndEmployees',
        method: 'get',
        data: { id: node.id }
      });

      await setLoading(false);
      if (responseData.success) {
        if (responseData.result.employeeResponseList) {
          await setCurrentDepartEmployees(
            responseData.result.employeeResponseList
          );
        } else {
          await setCurrentDepartEmployees([]);
        }
      } else {
      }
    } catch (e) {}
  };
  const onVisibilityToggle = ({ treeData, node, expanded, path }) => {
    console.log(node, path, expanded);
  };
  const renderAddSubDepartmentDialog = ({ node, path, treeIndex }) => {
    // console.log('edit', id);
    // const parentDepartment= nodel
    const dialogItem = {
      ...departmentDialogDefaultItem,
      dialogTitle: '添加子部门',
      parentId: node.id,
      parentIdDisabled: true
    };
    setDepartmentDialogData(dialogItem);
    setDepartmentDialogVisible(true);
  };
  const renderAddSiblingDepartmentDialog = () => {
    // console.log('edit', id);
    // const parentDepartment= nodel
    const dialogItem = {
      ...departmentDialogDefaultItem,
      dialogTitle: '添加平级部门',
      parentId: currentDepartmentInfo.parentId,
      parentIdDisabled: true
    };
    setDepartmentDialogData(dialogItem);
    setDepartmentDialogVisible(true);
  };
  const renderAddTopDepartmentDialog = () => {
    // console.log('edit', id);
    // const parentDepartment= nodel
    const dialogItem = {
      ...departmentDialogDefaultItem,
      dialogTitle: '添加一级部门',
      parentId: 0,
      parentIdDisabled: true
    };
    setDepartmentDialogData(dialogItem);
    setDepartmentDialogVisible(true);
  };
  const renderEditDepartmentDialog = node => {
    // console.log('edit', id);
    // const parentDepartment= nodel
    const dialogItem = {
      ...departmentDialogDefaultItem,
      dialogTitle: '编辑部门信息',
      id: node.id,
      name: node.name,
      parentIdDisabled: false,
      parentId: node.parentId,
      leaders: node.leaders
    };
    setDepartmentDialogData(dialogItem);
    setDepartmentDialogVisible(true);
  };
  const renderEditEmployeeDialog = record => {
    // console.log('edit', id);
    const dialogItem = {
      // ...dialogDefaultItem,
      dialogTitle: '编辑员工信息',
      ...record
    };
    setDialogData(dialogItem);
    setDialogVisible(true);
  };

  const renderAddEmployeeDialog = department => {
    setDialogData({ ...dialogDefaultItem, parentId: department.id });
    setDialogVisible(true);
  };
  const renderOpts = (value, index, record) => {
    return (
      <div>
        {/* <Button
          type="normal"
          className={styles.optBtn}
          onClick={() => switchMenuStatus(record.id, record.online)}
        >
          {record.online ? '禁用' : '启用'}
        </Button> */}

        {/* <Button
          type="normal"
          warning
          className={styles.optBtn}
          onClick={() => renderEditEmployeeDialog(record)}
        >
          编辑员工信息
        </Button> */}
        <Button
          type="normal"
          warning
          className={styles.optBtn}
          onClick={() => confirmEmployeeDelete(record)}
        >
          移除员工
        </Button>
      </div>
    );
  };
  const renderEmployee = (value, index, record) => {
    return (
      <div>
        <span>{record.name}</span>
        <p>{record.telephone}</p>
      </div>
    );
  };
  return (
    <div className={styles.departmentContainer}>
      {renderDialogWithData(dialogData)}
      {renderDepartmentDialogWithData(departmentDialogData)}
      <PageHead title="部门管理" />
      <div className={styles.departmentInner}>
        <div className={styles.treeWrapper}>
          <h3>部门树</h3>
          {data.length ? (
            <SortableTree
              treeData={data}
              theme={newTreeTheme}
              canDrag={() => {
                return false;
              }}
              generateNodeProps={rowInfo => ({
                buttons: [
                  <div>
                    <Button
                      type="normal"
                      className={styles.optBtn}
                      onClick={() => viewDepartmentDetail(rowInfo)}
                    >
                      查看
                    </Button>
                    <Button
                      type="normal"
                      className={styles.optBtn}
                      onClick={() => renderAddSubDepartmentDialog(rowInfo)}
                    >
                      添加子部门
                    </Button>
                  </div>
                ]
              })}
              onChange={treeData => setData(treeData)}
              onVisibilityToggle={onVisibilityToggle}
            />
          ) : (
            <div>
              <Button
                type="primary"
                onClick={() => renderAddTopDepartmentDialog()}
              >
                添加一级部门
              </Button>
            </div>
          )}
        </div>
        <div className={styles.contentWrapper}>
          {currentDepartmentInfo.id ? (
            <div className={styles.btnWrapper}>
              <Button
                type="primary"
                onClick={() => renderAddSiblingDepartmentDialog()}
              >
                添加同级部门
              </Button>
            </div>
          ) : null}
          <h3>部门简介</h3>
          {currentDepartmentInfo.id ? (
            <div className={styles.departmentDetailWrapper}>
              <p>
                部门ID：<span>{currentDepartmentInfo.id}</span>
              </p>
              <p>
                部门名称：<span>{currentDepartmentInfo.name}</span>
              </p>
              <p>
                部门leader:<span>{currentDepartmentInfo.leaders}</span>
              </p>
              <Button
                type="primary"
                onClick={() =>
                  renderEditDepartmentDialog(currentDepartmentInfo)
                }
              >
                编辑部门信息
              </Button>
              <Button
                warning
                onClick={() => confirmDepartmentDelete(currentDepartmentInfo)}
              >
                删除部门
              </Button>
            </div>
          ) : null}
          <h3>部门员工列表</h3>
          {currentDepartmentInfo.id ? (
            <Button
              type="primary"
              onClick={() => renderAddEmployeeDialog(currentDepartmentInfo)}
            >
              添加员工
            </Button>
          ) : null}
          <div className={styles.employeeWrapper}>
            <Table
              dataSource={currentDepartEmployees}
              hasBorder={false}
              onChange={employeeData => {}}
            >
              <Table.Column title="工号" dataIndex="workId" />
              <Table.Column
                title="姓名"
                dataIndex="name"
                cell={renderEmployee}
              />
              <Table.Column title="邮箱" dataIndex="email" />
              <Table.Column title="职位" dataIndex="title" />
              <Table.Column title="工位" dataIndex="workPlace" />

              <Table.Column title="操作" cell={renderOpts} />
            </Table>
          </div>
        </div>
      </div>
    </div>
  );
};
export default DepartmentTree;
