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 RoleGroupEditPage 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['roleGroupEditClick'+id] ) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          ['roleGroupEditClick'+id]:false
        },
      });
    }
  }
  loadDataSource=(orgId)=>{
    const {dispatch}=this.props;
    const roleJson = initFilter(orgId,'','CODE',1);
    extendRule(roleJson,'ENABLE_STATUS',1,0);
    roleJson.OrgType=1;
    dispatch({
      type: 'FMBase/getRoleDatasource',
      payload: roleJson,
    
    });
  };

  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');
      extendRule(userGroupJson, 'ID', 1, id);
      this.props.dispatch({
        type: 'FMRoleGroupEdit/getRoleGroup',
        payload: userGroupJson,
        onComplete: (ret) => {
          if(ret){
            let role=[];
            if(ret.Nav_BelongRoles){
              ret.Nav_BelongRoles.map(item=>{
                role.push(item.BELONG_ROLE_ID.toString().toUpperCase());
              })
            }

            this.setState({
              data: ret,
              roleTargetKeys:role,
            });
            this.loadDataSource(ret.ORG_ID);
          }
        }
      });
    }
    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 role=[];
      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});
          }
        });
      }
      updateData['Nav_BelongRoles']=role;
      dispatch({
        type: 'FMRoleGroupEdit/updateRoleGroup',
        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 handleRoleChange = (nextTargetKeys, direction, moveKeys) => {
      this.setState({roleTargetKeys: 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 rows={4} placeholder={'请输入备注'} />)}
                </Form.Item>
              </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>
              <Col style={{ textAlign: 'right',marginTop: '20px' }}>
                {
                  this.getBtns()
                }
              </Col>
            </Row>
          </Form>
      </div>
    );
  }

}

RoleGroupEditPage.propTypes = {
};

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