import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, Tree, Button,AmosAlert } from 'amos-framework';
import BizIcon from './../../../common/icon/BizIcon';
import {
  queryRiskSourceDetailAction,
  riskSourceDeleteAction,
  riskSourceSaveAction,
  queryRiskSourceTreeAction
 } from '../../../../services/bizService';
import RiskSourceModal from './modal/RiskSourceModal';

const TreeNode = Tree.TreeNode;

/**
 *
 * 风险层级树
 * @class RiskLevelTree
 * @extends {Component}
 */
class RiskLevelTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      riskSourceId: '',
      modelFlag: '',
      modal: false,
      treeData: [],
      searchParam: [],
      rightClickNodeTreeItem: null,
      btnType: '',
      riskType: '',
      autoExpandParent: true,
      expandedKeys: [],
      selectedKeys: [],
      node: {}
    };

  }

  componentWillMount() {

  }

  componentDidMount() {
    window.addEventListener('resize', this._resize);
    this.setOncontextmenu();//移除浏览器自带右键菜单
    this.queryRiskSourceTree();
  }

  componentWillReceiveProps(nextProps) {

  }

  componentWillUnmount() {
    window.addEventListener('resize', this._resize);
  }

  onRightClick = e => {// tree列表上右键事件
    this.setState({
      rightClickNodeTreeItem: {
        pageX: e.event.pageX,
        pageY: e.event.pageY
      }, node: e.node.props });
  }

  onButtonClick =(value)=>{//树按钮点击事件
    let { id } = this.state.node;
    let childrenLength = 0;
    let idsArry = [];
    idsArry.push(id);
    if (this.state.node.children){
      childrenLength = this.state.node.children.length;
      this.state.node.children.map(item =>{
        idsArry.push(item.props.id);
      });
    }
    if ( value === 'add' || value === 'edit'){
      this.setState({ modal: true,btnType: value });
    } else {
      const ids = idsArry.join(',');
      this.riskSourceDelete(ids, childrenLength);
    }
    this._handleClick();
  }

  onSelect =(selectedKeys,e)=>{//回调，刷新风险点信息、危险因素列表
    this.setState({ selectedKeys: (e.node.props.id + '').split(',') });
    const { callBack } = this.props;
    callBack && callBack(e.node.props.id);
  }

  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false
    });
  }

  onClick = (e,key)=>{

  }

  onscroll =(e)=>{
    const { rightClickNodeTreeItem }  = this.state;
    rightClickNodeTreeItem ? this.setState({ rightClickNodeTreeItem: null }) : '';
  }

  onOk = () =>{
    const { form } = this.model.state;
    this.model.form.validate((valid, dataValues) => {
      if (valid) {
        this.riskSourceEdit(form);
      } else {
        return false;
      }
    });
  }

  getNodeTreeRightClickMenu = () => {
    let { pageX, pageY } = { ...this.state.rightClickNodeTreeItem };
    const height = document.body.offsetHeight;
    let overHeight = height - (pageY + 120);
    overHeight > 0 ? '' : pageY = height - 120;
    const tmpStyle = {
      position: 'fixed',
      left: `${pageX}px`,
      top: `${pageY}px`,
      backgroundColor: '#ffffff',
      border: 'solid',
      height: '105px',
      borderWidth: '1px',
      borderColor: '#c9c9c9',
      zIndex: 1
    };
    const menu = (
      <div style={tmpStyle}>
        <Button icon={<BizIcon icon="tianjia" />}   onClick={()=>this.onButtonClick('add')}  className='risk-model-button' transparent>添加</Button>
        <Button icon={<BizIcon icon="xiugai" />}    onClick={()=>this.onButtonClick('edit')}  className='risk-model-button' transparent>编辑</Button>
        <Button icon={<BizIcon icon="shanchu" />}   onClick={()=>this.onButtonClick('delete')}  className='risk-model-button' transparent>删除</Button>
      </div>
    );
    return this.state.rightClickNodeTreeItem  ? menu : '';
  }

  setOncontextmenu =()=>{
    document.oncontextmenu = (e) =>{
      return false;
    };
  }

  getTreeIcon =(props)=>{
    let { pos } = props;
    let arry = pos ? pos.split('-') : [];
    let length = arry.length;
    if (length === 2){
      return <BizIcon icon="shu-changqu" />;
    } else if (length === 3){
      return <BizIcon icon="shu-zhukonglou" />;
    } else if (length === 4){
      return <BizIcon icon="shu-louceng" />;
    } else {
      return '';
    }
  }

  getDeteleConfirmByLength =(length)=>{
    if (length > 0){
      return '是否同步删除下层级所有节点';
    } else {
      return '确定要删除么';
    }
  }

  getContext = (btnType) => {
    let { id, riskType } = this.state.node;
    const { userData, methodData, riskLevelData } = this.props;
    let { riskTypeData } = this.props;
    if (btnType === 'add'){//新增
      riskTypeData = riskTypeData.filter(d => d.code > riskType);
      return (<RiskSourceModal
        userData={userData}
        methodData={methodData}
        riskLevelData={riskLevelData}
        riskTypeData={riskTypeData}
        parentId={id}
        ref={component =>this.model = component}
      />);
    } else if (btnType === 'edit') {
      riskTypeData = riskTypeData.filter(d => d.code >= riskType);
      return (<RiskSourceModal
        userData={userData}
        methodData={methodData}
        riskLevelData={riskLevelData}
        riskTypeData={riskTypeData}
        selectedRowId={id}
        ref={component => this.model = component}
      />);
    }
  }

  queryRiskSourceTree =(riskSourceId)=>{
    queryRiskSourceTreeAction().then(data =>{
      let obj = this.loopTreeNodes(data[0]);
      if (riskSourceId){//3d屏互动
        this.setState({ treeData: data, autoExpandParent: true }, ()=>this.queryRiskSourceDetail(riskSourceId));
      } else {//业务屏刷新
        if (obj) {
          this.setState({ treeData: data, autoExpandParent: true }, ()=>this.queryRiskSourceDetail(obj.id));
        } else {
          this.setState({ treeData: data, autoExpandParent: true });
        }
      }
    });
  }

  cancel = () => {
    this.setState({ modal: false });
  }

  queryRiskSourceDetail = (id) =>{
    queryRiskSourceDetailAction(id).then(data =>{
      this.setState({
        riskSourceId: data.id,
        expandedKeys: (data.parentId + '').split(','),
        selectedKeys: (data.id + '').split(',') }, ()=> this.props.callBack(data.id));
    });
  }

  riskSourceDelete =(id, length)=>{
    AmosAlert.confirm('提示',this.getDeteleConfirmByLength(length), {
      callback: flag => {
        if (flag) {
          // 确定
          riskSourceDeleteAction(id).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.reload();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  }
  reload =()=>{
    this.queryRiskSourceTree();
  }

  riskSourceEdit = (body) =>{
    riskSourceSaveAction(body).then(
      data => {
        AmosAlert.success('提示', '操作成功');
        this.setState({ modal: false });
        this.reload();
      },
      err => {
        AmosAlert.error('提示', err);
      }
    );
  }

  _handleClick = (event) => {
    this.setState({ rightClickNodeTreeItem: null });
  }

  _resize =()=>{
    this.onscroll();
  }

  loopTreeNodes = (data) => {
    if (data) {
      if (data.children && data.children.length > 0) {
        return this.loopTreeNodes(data.children[0]);
      }
    }
    return data;
  }

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode icon={e => this.getTreeIcon(e)} title={item.name} key={item.id + ''} {...item} >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode icon={e => this.getTreeIcon(e)} key={item.id + ''} title={item.name} {...item} />;
    });
  }

  render() {
    const { modal,btnType, treeData, expandedKeys, selectedKeys,autoExpandParent } = this.state;
    return (
      <div  className='risk-model-level'>
        <span className='risk-level-span'>风险层级</span>
        <div className='risk-model-tree' id='tree' onScroll={this.onscroll} onClick={this._handleClick}>
          <Tree
            expandedKeys={expandedKeys}
            onExpand={this.onExpand}
            selectedKeys={selectedKeys}
            autoExpandParent={autoExpandParent}
            showIcon
            onSelect={this.onSelect}
            onRightClick={this.onRightClick}
          >
            {this.renderTreeNodes(treeData)}
          </Tree>
        </div>
        <Modal
          header={btnType === 'edit' ? '编辑风险层级' : '添加风险层级'}
          visible={modal}
          className="risk-model-model"
          destroyContent
          width='40%'
          content={this.getContext(btnType)}
          onCancel={() => this.cancel()}
          onOk={() => this.onOk()}
          okText="确定"
          cancelText="取消"
          outterClosable={false}
          dragable
        />
        {this.getNodeTreeRightClickMenu()}
      </div>
    );
  }
}

RiskLevelTree.propTypes = {
  treeData: PropTypes.array,
  expandedKeys: PropTypes.array,
  selectedKeys: PropTypes.array,
  autoExpandParent: PropTypes.bool,
  callBack: PropTypes.func,
  userData: PropTypes.array,
  methodData: PropTypes.array,
  riskLevelData: PropTypes.array,
  riskTypeData: PropTypes.array
};

export default RiskLevelTree;
