dictAdd.js 13.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
import React from 'react'
import './dict.less'
import { Form, Button, Input, Select, message, Tree, Radio, Row, Col, Spin } from 'antd'
import { NavLink } from 'react-router-dom'
import UserManageBar from '@components/Common/WhiteBar/index'
import axios from '@src/axios/index'
import Utils from '@src/utils/utils'

import { API_DICT_MANAGE } from '@src/Api'
import { reduce } from 'zrender/lib/core/util';

const FormItem = Form.Item;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;

class DictAdd extends React.Component {
  state = {
    form:{
      status: 1,
      name: '',
      type: 1,
      version: null,
      code: '',
      value: '',
      pid: '',
      remark: '',
      id: '',
    },
    childDicts: false, //判断如果有子级,需要加载数据
    routerParams: '新增字典',

    dictTree: [],
    isLoad: true,
    isLoadTree: false, // 为true 的情况下 并且 isLoad为false 的情况下 加载树
    disabled: true,
    checkedKeys: [],
    checked: {
      key: '',
      val: ''
    },
    spinStatus: false, // 是否显示加载中

  };

  componentWillMount() {
    document.getElementById('root').scrollIntoView(true);//为ture返回顶部,false为底部
  }
  componentDidMount() {
    //获取字典信息
    this.getDictByid()

    // 获取路由信息
    this.getRouterParams()

    // 获取非跟节点下的树形结构
    this.getDictLevel()
  }

  // 根据路由判断进来的是修改还是新增
  getRouterParams = () => {
    const params = this.props.match.params
    if (!params || !params.params) {
      message.warn('请重新选择,或者刷新页面')
      this.props.history.push({
        pathname: '/home/system/dict',
      });
      return
    }

    if (params.params === 'addOpt') {
      this.setState({
        routerParams: '新增字典',
        disabled: true,
        isLoadTree: true
      })
    } else if (params.params === 'updOpt') {
      this.setState({
        routerParams: '修改字典',
        disabled: false,
        isLoadTree: false,
        spinStatus: true,
      })
    }
  }

  // 如果是修改 那么就要获取修改某条数据的信息并填充表单
  getDictByid= () => {
    let _this = this
    return new Promise((resolve, reject) => {
      const { params } = this.props.match
      if (params.sid) {
        axios.ajax({
          url: API_DICT_MANAGE.getDictById,
          data: {
            id: params.sid
          }
        }).then(res => {
          if (res && Object.keys(res).length > 0) {
            //let data = Object.assign({}, res, {version: '' + res.version})
            resolve(this.setState({form: res}));
            if (res.type ===1) {
              this.setState({isLoad: true, spinStatus: false})
            } else {
              this.setState({isLoad: false, spinStatus: false})
            }
          }
        })
      }
    })
  }

  // 节点选择 根据isLoad来加载不同的表单 true 显示 跟节点的
  nodeChange = ()=> {
    const data = this.props.form.getFieldsValue();
    if (data.type === 1) {
      this.setState({isLoad: false});
    } else {
      this.setState({isLoad: true});
    }
  };

  // 获取非跟节点下的树形结构
  getDictLevel () {
    this.setState({ loading: true })
    axios.ajax({
     url: API_DICT_MANAGE.getDict,
     data: {
       pageSize: 99999999999,
       pageNum: 1
     }
    }).then(res => {
     if (res.records && res.records.length > 0) {
      this.setState({ dictTree: res.records, loading: false })
     } else {
      this.setState({ dictTree: [], loading: false });
     }

    })
  }

  // 保存操作
  handleOperator = (e) => {
    e && e.preventDefault();
    let formData = this.props.form.getFieldsValue();
    const { params } = this.props.match.params
    const { userInfo } = this.state
    var pid = ''
    if (params && params === 'addOpt' && formData.type === 2 ) {
      if (this.state.checkedKeys.length > 0){
        pid = this.state.checkedKeys[0]
      }else {
        message.warn('请选择所属上级字典!')
        return false
      }
    }

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({
          spinStatus: true,
        })

        let url = params && params === 'addOpt' ? API_DICT_MANAGE.addDict : API_DICT_MANAGE.editDict
        // 这个地方需要控制一下,如果是修改进来表单需要隐藏上级字典以及字典树
        var obj = {};
        if(params && params === 'updOpt'){
          obj = this.state.form.type === 1 ? {type:1, id:this.state.form.id,} : {type:2, id:this.state.form.id, pid: Number(this.state.form.pid)}
        } else {
          obj = formData.type === 1 ? {} : {pid: Number(pid)}
        }
        let data = Utils.trim(Object.assign({}, formData, obj))
        axios.optAjax({
          url: url,
          data: {
            ...data
          }
        }).then(res => {
          if(res && res.code && res.code !== 0){
            this.setState({
              spinStatus: false,
            })
            return
          }
          message.success('操作成功')
          this.props.history.push('/home/system/dictManage/dict')
        })
      }
    });
  };

  // 树选择事件
  onSelect = (checkedKeys, e) => {
    this.setState({
      checkedKeys,
      checked: {
        key: checkedKeys[0],
        val: e.node.props.name
      }
    });
  }

  // 渲染字典树结构
  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.childDicts && item.childDicts.length > 0) {
        return <TreeNode icon={<Radio ref={item.name} checked={this.state.checkedKeys == item.id} value={item.id} />} title={item.name} key={item.id} name={item.name}>
          {this.renderTreeNodes(item.childDicts)}
        </TreeNode>
      } else {
        return <TreeNode icon={<Radio ref={item.name} checked={this.state.checkedKeys == item.id} value={item.id} />} title={item.name} key={item.id} name={item.name}>
        </TreeNode>
      }

      return <TreeNode {...item} />;
    });
  }

  render () {
    let _this = this;
    const { getFieldDecorator } = this.props.form;
    const state = this.state;

    const formItemLayout = {
      labelCol: {
        md: { span: 12 },
        lg: { span: 6 },
      },
      wrapperCol: {
        md: { span: 24 },
        lg: { span: 18 },
      },
    }


    return (
      <div className='dictBg'>
        <Spin tip="加载中..." spinning = {this.state.spinStatus}>
        <div className="roleAdd">
          <div className="nav">
            <NavLink to='/home/system/dictManage/dict' > 字典管理  </NavLink> >
            <span>{this.state.routerParams}</span>
          </div>

          <UserManageBar title="基本信息" />

          <div className="dictDetail">
            <Form  layout="horizontal" className = "publicForm">
              {
                this.state.disabled ?
                <Row gutter={24}>
                  <Col span="8">
                    <FormItem label="上级字典"  { ...formItemLayout}>
                      {
                        getFieldDecorator( 'type' , {
                          initialValue: state.form.type,
                          onChange:  this.nodeChange,

                          rules: [
                            {required: true, message:'上级字典为必选'}],
                        })(
                          <Select>
                            <Option value={1}>根节点</Option>
                            <Option value={2}>非根节点</Option>
                          </Select>
                        )
                      }
                    </FormItem>
                </Col>
              </Row>
                : ''
              }
              <div>
              <Row gutter={24}>
                <Col span="8">
                  <FormItem label="字典名称"  { ...formItemLayout}>
                    {
                      getFieldDecorator('name', {
                        initialValue: state.form.name,
                        rules: [
                          {required: true, message: '请输入字典名称'},
                          {max: 16, whitespace: true, message: '字典名称最长为16位字符'},
                        ],
                      })(
                        <Input placeholder="字典名称"/>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem label="字典代码"  { ...formItemLayout}>
                    {
                      getFieldDecorator('code', {
                        initialValue: state.form.code,
                        validateFirst: true,
                        rules: [
                          {required: true, message: '请输入字典代码'},
                          {pattern: Utils.getFormRules('version').regular, message: '字典代码必须是字母和数字,最长为16位字符'},
                          {max: 16, message: '字典代码必须是字母和数字,最长为16位字符'},
                        ],
                      })(
                        <Input disabled = {!this.state.disabled} placeholder="字典代码"/>
                      )
                    }
                  </FormItem>
                </Col>
              </Row>

              </div>
             {
              this.state.isLoad ?
              <Row gutter={24}>
                <Col span="8">
                  <FormItem label="字典版本"  { ...formItemLayout}>
                    {
                      getFieldDecorator('version', {
                        initialValue: state.form.version,
                        validateFirst: true,
                        rules: [
                          {required: true, message: '请输入字典版本'},
                          { max: 10,message: '请根据提示输入字典版本,最长为10位字符'},
                          {pattern: Utils.getFormRules('version').regular, message: '请根据提示输入字典版本,最长为10位字符'}
                        ],
                      })(
                        <Input placeholder="格式(v1.1.1/1.1.1)"/>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem label="状&emsp;&emsp;态" value={state.form.status} { ...formItemLayout}>
                    {
                      getFieldDecorator('status', {
                        initialValue: state.form.status,
                        rules: [{
                          required: true, message: '状态不能为空',
                        }],
                      })(
                        <Select >
                          <Option value={1}>正常</Option>
                          <Option value={2}>禁用</Option>
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
              :
              <Row gutter={24}>
                <Col span="8">
                  <FormItem label="&nbsp;&nbsp;&nbsp;&emsp;字典值" { ...formItemLayout}>
                    {
                      getFieldDecorator('value', {
                        initialValue: state.form.value,
                        rules: [
                          {max: 16, message: '字典值最长为16位字符'},
                        ],
                      })(
                        <Input placeholder="字典值"/>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem label="&nbsp;&nbsp;&nbsp;字典描述"  { ...formItemLayout}>
                    {
                      getFieldDecorator('remark', {
                        initialValue: state.form.remark,
                        rules: [
                          {max: 512, message: '字典描述最长为512位字符'},
                        ],
                      })(
                        <Input placeholder="字典描述" />
                      )
                    }
                  </FormItem>
                </Col>
              </Row>
             }
            </Form>
          </div>

          {
            !this.state.isLoad && this.state.isLoadTree ?
            <div>
              <UserManageBar title="字典树" />
              <div className="dictDetail">
                <div className="dictSubtitle">
                  <i className="anticon anticon-book"></i>
                  &nbsp;选择所属上级字典
                </div>
                {
                  this.state.dictTree.length > 0 ?
                  <Tree
                    showIcon
                    defaultExpandAll
                    className="orgTree"
                    onSelect={(checkedKeys, e) => { this.onSelect(checkedKeys, e) }}
                  >
                    {this.renderTreeNodes(this.state.dictTree)}
                  </Tree>
                  :
                  <div className ="noData" >NO Data</div>
                }

              </div>
            </div>
            : ''
          }

          <div className="submitBtn" >
            <Button type="primary"  disabled = {this.state.spinStatus} onClick={this.handleOperator} >保存</Button>
            <NavLink to='/home/system/dictManage/dict' ><Button>  返回 </Button></NavLink>
          </div>

        </div>
        </Spin>
      </div>
    )
  }
}

export default Form.create()(DictAdd);