import React, {PureComponent} from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {Form, Input, Button, Menu, Icon, Tree, Select, message, Modal} from 'antd';
import {
  systemComDepartList,
  systemComDepartBatchInsertDepart,
  systemComDepartDelete,
  systemComDepartGetTreeDepart
} from "../../../services/api";
import bcx_utils from "../../../common/bcx_utils";

const TreeNode = Tree.TreeNode;
const Option = Select.Option;


//转换接口需要的字段
const reverseObj = data => {
  let newArr = JSON.parse(JSON.stringify(data));
  newArr.map(({key, title}, index) => {
    newArr[index] = {
      departId: key,
      departName: title,
    };
  });
  return JSON.stringify(newArr);
}

//迭代自身，删除多余的children
const deleteChild = arr => {
  let newArr = JSON.parse(JSON.stringify(arr));
  newArr.map(({title, key, children, departId}, index) => {
    newArr[index] = {
      title, key, children,
    };
    if (newArr[index].children.length) {
      newArr[index].children = deleteChild(children);
    } else {
      delete  newArr[index].children;
    }
  });
  return newArr;
}


//转换antd需要的字段
const changeObj = data => {
  let newArr = JSON.parse(JSON.stringify(data));
  newArr.map(({departId, departName, haveChild}, key) => {
    newArr[key] = {
      key: departId,
      title: departName,
      isLeaf: !haveChild,
    };
  });
  return newArr;
}

/**
 * 组建部门机构
 */
export default class InitialDepartmentalInstitutions extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // count: 0,
      uuid: 1,
      placeholder: '请输入内容',
      header: '百川信（厦门）网络服务信息有限公司',
      caption: '经营管理中心',
      treeData: [],
      currentInfos: {     //当前树节点完整信息,右侧数据依赖这个
        selectedKeys: "-1",
        dataRef: {
          children: []
        }
      },//当前记录
      currentNode: {
        props:
          {
            pos: "0-0",
            dataRef: {
              key: "-1"
            }
          }
      },//保存当前节点信息
      expandedKeys: ["-1"],
    };

  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.systemComDepartGetTreeDepart(-1);
  }
  /******************************ajax请求******************************/
    // 初始化  查询下级部门功能
  systemComDepartGetTreeDepart = (parentDepartId) => {
    systemComDepartGetTreeDepart({parentDepartId}).then(
      ({data}) => {
        const treeData = deleteChild(data);
        this.setState({treeData});
        this.initRightCurrentNode(data);
        this.initRightCurrentInfos(data);
      },
      (err) => {
        console.log(err);
      }
    );
  }

  //批量新增部门
  systemComDepartBatchInsertDepart = (ajaxData) => {
    systemComDepartBatchInsertDepart(ajaxData).then(
      ({msg}) => {
        message.success(msg);
        //操作成功，本地更新节点
        this.upDateNode();
      },
      (err) => {
        console.log(err);
      }
    );
  }
  /******************************相关事件******************************/

  initRightCurrentNode = (data) => {
    let currentInfos = {...this.state.currentInfos};
    const {children, title} = data[0];
    currentInfos.dataRef.children = bcx_utils.jsoncopy(children);
    this.setState({currentInfos});

  }
  initRightCurrentInfos = (data) => {
    let currentInfos = {...this.state.currentInfos};
    const {children, title} = data[0];
    currentInfos.dataRef.title = title;
    currentInfos.dataRef.children = bcx_utils.jsoncopy(children);
    this.setState({currentInfos});

  }

  //找到节点 更新节点  (提交确认按钮)
  upDateNode = () => {
    const treeData = JSON.parse(JSON.stringify(this.state.treeData));
    const {props: {pos, dataRef: {key}}} = this.state.currentNode;//当前节点的id（key）,还有位置信息
    const [, ...posDetail] = pos.split("-");
    const length = posDetail.length;
    //请求新节点信息，更新旧节点
    systemComDepartList({parentDepartId: key}).then(
      ({data}) => {
        this.systemComDepartGetTreeDepart(-1);
      },
      (err) => {
        console.log(err);
      }
    );

  }
  //删除
  remove = (index, item) => {
    const currentInfos = {...this.state.currentInfos};
    if (item.key !== "") {
      Modal.confirm({
        title: '确认删除该记录?',
        content: '',
        onOk: () => {
          systemComDepartDelete({departId: item.key}).then(
            (data) => {
              message.success(data.msg);
              this.upDateNode()
            },
            (err) => {
              console.log(err);
            }
          );
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    } else {
      const newArr = currentInfos.dataRef.children.filter((val, key) => key !== index);
      currentInfos.dataRef.children = newArr;
      this.setState({currentInfos});
    }
  }

  //添加部门输入框
  inputChange = (index, e) => {
    const currentInfos = {...this.state.currentInfos};
    currentInfos.dataRef.children[index].title = e.target.value.trim();
    this.setState({currentInfos});
  }


  //添加部门
  addItem = () => {
    const currentInfos = {...this.state.currentInfos};
    if (!currentInfos.dataRef.children) {
      currentInfos.dataRef.children = [];
    }
    currentInfos.dataRef.children.push(
      {
        key: "",
        title: "",
      }
    );
    this.setState({currentInfos});
  }


  //提交 添加部门
  handleSubmit = (e) => {
    e.preventDefault();
    const {dataRef: {children}, selectedKeys} = this.state.currentInfos;
    if (!selectedKeys || !children) {
      message.error("请选择添加的部门");
      return;
    }
    let newArr = children.filter(val => val.title.length !== 0);
    bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
      if (newArr.length === 0) {
        message.error("请填写部门名称", 1.5, () => {
          setTimeout(() => {
            resolve();
          }, 500);
        });
      } else {
        //移除标题为空的选项
        const submitArr = reverseObj(newArr);
        const submitData = {
          parentDepartId: selectedKeys,
          comDeparts: submitArr,
        };
        this.systemComDepartBatchInsertDepart(submitData);
        resolve();
      }

    }))


  }


  onSelect = (selectedKeys, info) => {
    //选中时候，传入当前节点数据
    this.setState({
      currentInfos: {selectedKeys, dataRef: bcx_utils.jsoncopy(info.node.props.dataRef)},
      currentNode: info.node
    });
  }
  //下一步，刷新
  nextStep = () => {
    let _this = this;
    this.nextStep = false;//防止重复显示

    function nextStep() {
      return new Promise((resolve) => {
        _this.nextStep = true;
        _this.props.nextStep(resolve);
      });
    }

    async function ajaxStep() {
      let result = await nextStep();
      if (result === "4") {
        message.error("请创建至少一种部门", 1.5, () => {
          setTimeout(() => {
            _this.nextStep = false;
          }, 500)
        });
      }
    }

    if (this.nextStep === false) {
      ajaxStep();
    }
  }
  /******************************render******************************/


  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} dataRef={item}/>;
    });
  }

  renderFormItems = () => {
    if (!this.state.currentInfos.dataRef.children) {
      return;
    }
    const formItems = this.state.currentInfos.dataRef.children.map((val, key) => {
      return (
        <div key={key}>
          <div className="item">
            <div className="l">
              <span className="ant-form-item-required">类型：</span>
            </div>
            <Select disabled={true} defaultValue="1" className="select">
              <Option value="1">部门</Option>
            </Select>
            <Icon
              className="dynamic-delete-button"
              type="minus-circle-o"
              onClick={() => this.remove(key, val)}/>
          </div>
          <div className="item">
            <div className="l">
              <span className="ant-form-item-required">部门名称：</span>
            </div>
            <Input placeholder="请输入"
                   className="r"
                   maxLength={20}
                   minLength='1'
                   defaultValue={val.title}
                   value={val.title}
                   onChange={this.inputChange.bind(this, key)}/>
          </div>

        </div>
      )
        ;
    });


    return formItems;
  }

  render() {
    const {currentInfos} = this.state;
    //自身迭代节点
    const loop = data => data.map((item) => {
      const title = <span>{item.key}</span>;
      if (item.children) {
        return (
          <TreeNode key={item.key} title={title}>
            {loop(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} title={title}/>;
    });

    return (
      <Container>
        <div className="nextstep" onClick={this.nextStep}>下一步</div>
        <header className="password-header">组建部门机构</header>
        <div className="department-content">
          <div className="department-inquiry">
            {this.state.treeData.length !== 0 && (
              <Tree
                defaultExpandAll={true}
                onSelect={this.onSelect}
              >
                {this.renderTreeNodes(this.state.treeData)}
              </Tree>
            )}
          </div>
          <div className="department-right">
            <p className="department-title" style={{marginBottom: 24}}>{currentInfos.dataRef.title}</p>
            {this.renderFormItems()}
            <div style={{paddingLeft: 102}}>
              <Button type="dashed" onClick={this.addItem} style={{width: 337, margin: "0 0 24px 0"}}>
                <Icon type="plus"/> 添加
              </Button>
            </div>
            <div style={{paddingLeft: 102}}>
              {/*<Button style={{marginRight: "8px"}}>取消</Button>*/}
              <Button className="submit" type="primary" onClick={this.handleSubmit}>保存</Button>
            </div>
          </div>
        </div>
      </Container>
    );
  }
}

/*********************样式*************************** */
const
  Container = style.div`{
    .nextstep{
          font-size: 14px;
          color: #0F71FF;
          line-height: 14px;
          border: 1px solid #0F71FF;
          border-radius: 4px;
          float: right;
          padding: 8px 14px;
          margin-top: 3px;
          cursor: pointer;
    }
    .password-header{
        font-size: 20px;
        color: #333333;
        padding-bottom:16px;
        border-bottom:1px solid #e9e9e9;
    }
    .ant-btn-primary{
        background-color: #0F71FF;
    }
    .ant-menu-submenu > .ant-menu{
        background:#fff;
    }
    .department-content{
        height: 850px;
        background: #fff;
        border-radius: 5px;
        padding-left: 220px;
        position: relative;
        >div{
          height: 850px;
          overflow: auto;        
        }
        .department-inquiry{
          width: 220px;
          padding: 16px 8px;
          position: absolute;
          top: 0;
          left: 0;
          input{
            color: #333;
          }
          .depart-menu{
            span{
              color: #333;
              font-size: 14px;
            }
            ul li{
              color: #333;
              font-size: 14px;
            }
          }
          .ant-tree-node-content-wrapper {
            width: 120px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;            
          }         
        }
        .department-right{
            margin-left:1px;
            padding:24px;
            border-left:1px solid #eee;
            min-height:600px;
            .department-title{
                font-size: 16px;
                color: #333333;
            }
        }
      }
    .item{
      width:440px;
      margin-bottom:24px;
      position:relative;
      .dynamic-delete-button {
        cursor: pointer;
        position: absolute;
        font-size: 24px;
        color: #d9d9d9;
        transition: all .3s;
        margin:5px 0 0 10px;
     }
     .dynamic-delete-button:hover {
        color: #777;
     }
     .dynamic-delete-button[disabled] {
        cursor: not-allowed;
        opacity: 0.5;
     }
      >div{
       display:inline-block;
      }
      .l{
        width:94px;
        text-align: right;
        margin-right: 8.3px;
      }
      .r{
        width:337px;
      }
      .select{
       width:304px;
      }
    }  
}`;
