import React from 'react';
import { connect } from 'dva';
import { Button, Tree, Checkbox, Row, Col, Form, Input, Select, Upload, Icon, Modal, Spin, message, Transfer } from 'antd';
import {
  extend,
  extendRule,
  initFilter,
  initQueryFilter,
  getOnlyPropertyData,
  extendInclude, guid, setDataFieldValue
} from "../../../utils/common";
import DropDownPagination from '../../common/DropDownPaginationEx';
import EditComponent from '../../../baseComponents/EditComponent/index.js'
import FormPage from '../../FormPage';
import config from "../../../config";
import moment from 'moment';

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
class OG059EditPage extends EditComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {
      },
      checkAll: false,
      treeData: [],
      uids: [],
      users: [],
    };
  };

  onBeforeSaveHandleRecord(params) {
    super.onBeforeSaveHandleRecord(params);
    const { editCode, record, srcRecord } = params ? params : {};
    if (!record.Nav_Users) {
      record.Nav_Users = [];
    }
    if (this.state.uids) {
      this.state.uids.forEach(uid => {
        if (!record.Nav_Users.find(it => it.USER_ID === uid)) {
          record.Nav_Users.push({
            ID: guid(),
            USER_ID: uid,
            ORG_ID: this.props.login.OrgId,
          });
        }
      });
    }

    record.Nav_Users.forEach(it => {
      if (!this.state.uids || !this.state.uids.find(uid => uid === it.USER_ID)) {
        it.IS_DELETED = true;
      }
    });
  }

  showTreeNode = (data) => {
    if (!data || data.length == 0)
      return;
    return data.map((item) => {
      if (item) {
        let title = item.Name;
        return (
          <Tree.TreeNode
            title={title}
            key={item.Id.toString()}
            data={item}
            disabled={item.IsDisabled}
            disableCheckbox={item.IsDisabled}
            isLeaf={!(item.Children && item.Children.length)}>
            {this.showTreeNode(item.Children)})
          </Tree.TreeNode>
        );
      };
    });
  };
  onBeforeEdit(params) {
    const { colConfig, record } = params;
    const { isNew, isCopy, copySrcData } = params ? params : {};
    const { dispatch } = this.props;
    this.getTreeData();
  }
  getTreeData = () => {
    const { form, dispatch, data, login } = this.props;
    const initJson = initFilter(login.orgId, login.userId)
    const createNodes = (data, parentNode, list, parentId) => {
      if (!data)
        return;
      data.map(it => {
        if (it.ParentId === parentId) {
          it.Children = [];
          createNodes(data, it, it.Children, it.Id);
          list.push(it);
        };
      });
    };
    dispatch({
      type: 'app/getDataByPost',
      url: 'OG/OGEmployeeOpinionCollection/GetDepartmentTree',
      payload: initJson,
      onComplete: (ret) => {
        if (ret) {
          const treeData = [];
          createNodes(ret, null, treeData, null);
          this.setState({
            treeData,
          }, () => {
          });
          if (this.state.data && this.state.data.Nav_Users) {
            this.setState({
              uids: this.state.data.Nav_Users.map(it => it.USER_ID.toLocaleUpperCase())
            })
          }
        }
      }
    });
  };


  refreshTransferSource = () => {
    let users = [];
    if (this.state.checkAll) {
      if (this.state.selNode) {
        let node = JSON.parse(JSON.stringify(this.state.selNode));
        users.push(...node.Users);
        const getChilds = (node, users) => {
          if (node.Children && node.Children.length > 0) {
            node.Children.forEach(it => {
              users.push(...it.Users);
              getChilds(it, users);
            })
          }
        }
        getChilds(node, users);
      }
    } else {
      if (this.state.selNode) {
        let node = JSON.parse(JSON.stringify(this.state.selNode));
        users.push(...node.Users);
      }
    }
    this.setState({
      users,
    })
  }
  onRenderHeadControl(params) {
    const { colConfig, record } = params;
    const spanCol = { xs: 20, sm: 20, md: 20 };



    switch (colConfig.field) {
      case 'Nav_Users.Nav_User.NAME': {
        return <>
          <Row style={{ width: 580 }}>
            <Col span={16} >
              <Tree
                onSelect={
                  (selectedKeys, e) => {
                    this.setState({
                      selNode: e.node.props.data,
                    }, () => {
                      this.refreshTransferSource()
                    })

                  }
                }
              >
                {this.showTreeNode(this.state.treeData)}
              </Tree>
              <Checkbox style={{ marginBottom: '8px', float: 'right' }} onChange={(e) => {
                this.setState({
                  checkAll: e.target.checked
                })
                this.refreshTransferSource();
              }
              }>
                全选
              </Checkbox>
            </Col>
            <Col {...spanCol}>
              <Transfer
                dataSource={this.state.users}
                titles={['部门人员', '已选择']}
                targetKeys={this.state.uids}
                onChange={(nextTargetKeys, direction, moveKeys) => {
                  let arr = nextTargetKeys.map(it => it);
                  this.setState({ uids: arr });
                }}
                render={item => item.title}
              />
            </Col>
          </Row>
        </>
        break;
      }
      default: {
        return super.onRenderHeadControl(params);
        break;
      }
    }
  }
}
export default connect(({ login, loading, custom, app }) => ({ login, loading, custom, app }))(Form.create()(OG059EditPage));