import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Form, Input,Select,Checkbox,Modal,Transfer,Spin,message } from 'antd';
import {
  extend,
  extendRule,
  initFilter,
  initQueryFilter,
  getOnlyPropertyData,
  extendInclude
} from "../../../utils/common";
import DropDownPagination from '../../common/DropDownPaginationEx';

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
class UserGroupEditPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      btns:[],
      userGroupTargetKeys:[],
      roleTargetKeys:[],
      roleGroupTargetKeys:[],
    };
  };

  componentDidMount() {
    this.props.form.resetFields();
    this.loadData();
  }

  componentWillReceiveProps(NextProps) {
    const {data}=this.props;
    let {id}=data?data:{};
    if(!id)
      id='';
    if (NextProps.custom['userGroupEditClick'+id] ) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          ['userGroupEditClick'+id]:false
        },
      });
    }
  }

  loadDataSource=(orgId)=>{
    const {data,dispatch}=this.props;
    const {id}=data?data:{};
    const userGroupJson = initFilter(orgId,'','CODE',1);
    if(id) {
      extendRule(userGroupJson, 'ID', 2, id);
    }
    extendRule(userGroupJson,'ENABLE_STATUS',1,0);
    userGroupJson.OrgType=1;
    dispatch({
      type: 'FMBase/getUserGroupDatasource',
      payload: userGroupJson,
    });
    const roleJson = initFilter(orgId,'','CODE',1);
    extendRule(roleJson,'ENABLE_STATUS',1,0);
    roleJson.OrgType=1;
    dispatch({
      type: 'FMBase/getRoleDatasource',
      payload: roleJson,
    
    });
    const roleGroupJson = initFilter(orgId,'','CODE',1);
    extendRule(roleGroupJson,'ENABLE_STATUS',1,0);
    roleGroupJson.OrgType=1;
    dispatch({
      type: 'FMBase/getRoleGroupDatasource',
      payload: roleGroupJson,
    });
  };
  
  loadData=()=> {
    const {data,formId,login,dispatch}=this.props;
    const {id}=data?data:{};
    if(id){
      const userGroupJson = initFilter(this.props.login.OrgId);
      extendInclude(userGroupJson,'Nav_BelongRoles');
      extendInclude(userGroupJson,'Nav_BelongRoleGroups');
      extendInclude(userGroupJson,'Nav_BelongUserGroups');
      extendRule(userGroupJson, 'ID', 1, id);
      this.props.dispatch({
        type: 'FMUserGroupEdit/getUserGroup',
        payload: userGroupJson,
        onComplete: (ret) => {
          if(ret){
            let userGroup=[];
            let role=[];
            let roleGroup=[];
            if(ret.Nav_BelongRoles){
              ret.Nav_BelongRoles.map(item=>{
                role.push(item.BELONG_ROLE_ID.toString().toUpperCase());
              })
            }
            if(ret.Nav_BelongRoleGroups){
              ret.Nav_BelongRoleGroups.map(item=>{
                roleGroup.push(item.BELONG_ROLE_GROUP_ID.toString().toUpperCase());
              })
            }

            if(ret.Nav_BelongUserGroups){
              ret.Nav_BelongUserGroups.map(item=>{
                userGroup.push(item.BELONG_USER_GROUP_ID.toString().toUpperCase());
              })
            }
            this.loadDataSource(ret.ORG_ID);
            this.setState({
              data: ret,
              userGroupTargetKeys:userGroup,
              roleTargetKeys:role,
              roleGroupTargetKeys:roleGroup
            });
          }
        }
      });
    }
    else{
      this.loadDataSource(login.OrgId);
      this.setState({
        data:{
          ...this.state.data,
          ORG_ID:this.props.login.OrgId,
        }
      })
      const {form,} = this.props;
      const { setFieldsValue} = form;
      if(this.props.login.OrgCode){
        setFieldsValue({
          CODE:(this.props.login.OrgCode),
        })
      }
    }
    if(formId){
      const btnJson = initFilter(this.props.login.OrgId,'','NUM',0);
      extendRule(btnJson, 'PAGE_CUSTOM_FORM_ID', 1, formId);
      this.props.dispatch({
        type: 'FMUserGroupEdit/getBtnList',
        payload: btnJson,
        onComplete: (ret) => {
          if(ret){
            this.setState({
              btns: ret,
            });
          }
        }
      });
    }
  };


  getBtns=()=>{
    if(this.state.btns){
      return this.state.btns.map(item=>{
        if (item.BTN_TYPE == 1) {
          return <Button type={item.CSS} icon={item.ICON} key={item.ID} onClick={() => this.handleOk()}>{item.LABEL}</Button>;
        }
      });
    }
  };

  handleOk = () => {
    const {form,dispatch,data} = this.props;
    const {getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue} = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      extend(this.state.data,values);
      let updateData=getOnlyPropertyData(this.state.data);
      const ret=this.state.data;
      let userGroup=[];
      let role=[];
      let roleGroup=[];
      if(this.state.roleTargetKeys){
        this.state.roleTargetKeys.map(item=>{
          let isGet=false;
          if(ret.Nav_BelongRoles){
            ret.Nav_BelongRoles.map(t=>{
              if(t.BELONG_ROLE_ID.toString().toUpperCase()==item) {
                role.push(t);
                isGet = true;
              }
            });
          }
          if(!isGet){
            role.push({BELONG_ROLE_ID:item,ORG_ID:updateData.ORG_ID});
          }
        });
      }

      if(this.state.userGroupTargetKeys){
        this.state.userGroupTargetKeys.map(item=>{
          let isGet=false;
          if(ret.Nav_BelongUserGroups){
            ret.Nav_BelongUserGroups.map(t=>{
              if(t.BELONG_USER_GROUP_ID.toString().toUpperCase()==item) {
                userGroup.push(t);
                isGet = true;
              }
            });
          }
          if(!isGet){
            userGroup.push({BELONG_USER_GROUP_ID:item,ORG_ID:updateData.ORG_ID});
          }
        });
      }


      if(this.state.roleGroupTargetKeys){
        this.state.roleGroupTargetKeys.map(item=>{
          let isGet=false;
          if(ret.Nav_BelongRoleGroups){
            ret.Nav_BelongRoleGroups.map(t=>{
              if(t.BELONG_ROLE_GROUP_ID.toString().toUpperCase()==item) {
                roleGroup.push(t);
                isGet = true;
              }
            });
          }
          if(!isGet){
            roleGroup.push({BELONG_ROLE_GROUP_ID:item,ORG_ID:updateData.ORG_ID});
          }
        });
      }

      updateData['Nav_BelongRoles']=role;
      updateData['Nav_BelongUserGroups']=userGroup;
      updateData['Nav_BelongRoleGroups']=roleGroup;
      dispatch({
        type: 'FMUserGroupEdit/updateUserGroup',
        payload: updateData,
        onComplete: (ret) => {
          if(ret) {
            if(data.close){
              data.close();
            }
            message.success('执行成功');
          }
        }
      });
    })
  };

  render() {
    const {form, location, dispatch, match,loading} = this.props;
    const {getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue} = form;

    const handleUserGroupChange = (nextTargetKeys, direction, moveKeys) => {
      this.setState({userGroupTargetKeys: nextTargetKeys});
    }
    const handleRoleChange = (nextTargetKeys, direction, moveKeys) => {
      this.setState({roleTargetKeys: nextTargetKeys});
    }
    const handleRoleGroupChange = (nextTargetKeys, direction, moveKeys) => {
      this.setState({roleGroupTargetKeys: nextTargetKeys});
    }
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14},
    };


    return (
      <div>
          <Form>

            <Row>
              <Col span={12}>
                <Form.Item
                  label={'用户组名称'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('NAME', {
                    validateTrigger: 'onBlur',
                    initialValue: this.state.data.NAME,
                    rules: [{required: true, message: '请输入用户组名称'}],
                  })(<Input maxLength={30} placeholder={'请输入用户组名称'}/>)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={'用户组编码'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('CODE', {
                    validateTrigger: 'onBlur',
                    initialValue: this.state.data.CODE,
                    rules: [{required: true, message: '请输入用户组编码'}],
                  })(<Input maxLength={30} placeholder={'请输入用户组编码'}/>)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <FormItem label={'启用标志'} {...formItemLayout}>
                  {getFieldDecorator('ENABLE_STATUS', {
                    validateTrigger: 'onBlur',
                    initialValue: this.state.data.ENABLE_STATUS?this.state.data.ENABLE_STATUS.toString():"0",
                    rules: [],

                  })(<Select placeholder="数据类型" >
                    <Option value="0">启用</Option>
                    <Option value="1">不启用</Option>
                  </Select>)}

                </FormItem>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={'备注'}
                  {...formItemLayout}
                >
                  {getFieldDecorator('REMARK', {
                    initialValue: this.state.data.REMARK,
                  })(<TextArea maxLength={300} rows={4} placeholder={'请输入备注'} />)}
                </Form.Item>
              </Col>
            </Row>

            <Row style={{'display': 'flex','flexDirection': 'column'}}>
              <Col  style={{ 'margin': '15px auto' }}>
                <Transfer
                  dataSource={this.props.FMBase.userGroupDatasource}
                  titles={['用户组', '已选择']}
                  targetKeys={this.state.userGroupTargetKeys}
                  onChange={handleUserGroupChange}
                  render={item => item.title}
                />
              </Col>
            </Row>
            <Row style={{'display': 'flex','flexDirection': 'column'}}>
              <Col  style={{ 'margin': '15px auto' }}>
                <Transfer
                  dataSource={this.props.FMBase.roleDatasource}
                  titles={['角色', '已选择']}
                  targetKeys={this.state.roleTargetKeys}
                  onChange={handleRoleChange}
                  render={item => item.title}
                />
              </Col>
            </Row>

            <Row style={{'display': 'flex','flexDirection': 'column'}}>
              <Col  style={{ 'margin': '15px auto' }}>
                <Transfer
                  dataSource={this.props.FMBase.roleGroupDatasource}
                  titles={['角色组', '已选择']}
                  targetKeys={this.state.roleGroupTargetKeys}
                  onChange={handleRoleGroupChange}
                  render={item => item.title}
                />
              </Col>
            </Row>

            <Row>
              <Col style={{ textAlign: 'right',marginTop: '20px' }}>
                {
                  this.getBtns()
                }
              </Col>
            </Row>
          </Form>
      </div>
    );
  }

}

UserGroupEditPage.propTypes = {
};

export default connect(({ login, loading, FMBase,FMUserGroupEdit,custom }) => ({ login, loading, FMBase,FMUserGroupEdit,custom }))(Form.create()(UserGroupEditPage));
