dictDetail.js 10.5 KB
import React from 'react'
import './dict.less'
import { Row, Col, Table, Form, Button, Input, Icon, message, Modal } 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 storage from '@src/utils/localStorage'
import { API_DICT_MANAGE } from '@src/Api'

const FormItem = Form.Item;

class DictDetail extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      btnAuth: null,
      name: '',
      code: '',
      list: [],
      loading: true,
      id: '',
      pid: '',
      backId: '',
      joinId: '',
      defaultExpandAllRows: false,
      expandStyle: { transform: 'rotate(-90deg)' },
      searchForm: {},
      searchArr: [],
      expandStatus: false,
      isShowOpt: true,
    };
   
  }
  
  routerArr = []  // 这个地方是用来记录路由变量  暂时只想到这个

  componentWillMount() {
    const btnAuth = storage.get('btnAuth')
    this.setState({btnAuth})
    if(
      btnAuth.indexOf('dict-edit') === -1 && 
      btnAuth.indexOf('dict-delete') === -1 && 
      btnAuth.indexOf('addNextDict') === -1 && 
      btnAuth.indexOf('dict-lookMore') === -1){
        this.setState({isShowOpt: false})
      }
  }

  async  componentDidMount() {
    await this.getRouterParams()
    this.getParamQuery()
  }

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

  //查询重置搜索条件
  reset = () => {
    this.props.form.resetFields();
    this.getParamQuery()
  }

  // 针对字典外部表格进行查询
  queryList = () => {
    const searchForm = this.props.form.getFieldsValue();
    this.setState({searchForm}, ()=> {
      this.getParamQuery()
    })
  }
  

  // 获取字典数据
  getParamQuery = (item) => {   
    let searchForm = Utils.trim(this.state.searchForm)
    this.setState({ loading: true })
    axios.ajax({
      url: API_DICT_MANAGE.getDictChild,
      data: {
        id: this.state.id,
        name: searchForm.name || '',
        pageSize: 99999999,
        pageNum: 1
      }
    }).then(res => {
      if (res && res.length > 0) {
        this.setState({ 
          list: res[0].childDicts, 
          loading: false, 
          name: res[0].name, 
          code: res[0].code, 
          pid: res[0].pid 
        })
      } else {
        this.setState({ list: [], loading: false });
      }
    })
  }

  onExpand = (expanded, record)=> {
    let _this = this
    let arr = [];
    this.setState({ loading: true })  
    if (expanded) {     
      axios.ajax({
        url: API_DICT_MANAGE.getChildsById,
        data: {
          id: record.id,
          pageSize: 99999999,
          pageNum: 1
        }
      }).then(res => {
        if (res && res.length > 0) {
         arr = _this.renderList(this.state.list, record, res)       
         console.log(arr) 
         this.setState({list: arr, loading: false})
        } else {
          this.setState({
            loading : false
          })  
          return
        }
        
      })   
    } else {
      arr = _this.renderList(this.state.list, record, [])         
      this.setState({list: arr, loading: false})
    }
  }

  renderList (data, record, res) {
    let _this = this  
    data.forEach((item,index) => {
      if(item.id === record.id){
        item.childDicts = res
      }else{
        if(item.childDicts && item.childDicts.length){
           _this.renderList(item.childDicts, record, res)
        }
      }
    }) 
    return data
  }

  // 字典列删除
  handleDelete = (text, record, index) => {
    if (text) {
      Modal.confirm({
        title: '删除',
        content: `您要删除的字典为 : ${text.name} ?`,
        onOk: () => {
          axios.ajax({
            url: API_DICT_MANAGE.deleteDictById,
            data: { id: text.id }
          }).then(res => {
            message.success('删除成功')
            this.getParamQuery();
          })
        }
      })
    } else {
      Modal.confirm({
        title: '警告',
        content: "请选择一条数据"
      })
    }
  }

  // 点击详情
  handleDetail = (item) => {    
    this.routerArr.push(item.id)
    this.setState({ id: item.id, list:[]}, () => {
      this.getParamQuery()
    })
  }
  // 点击返回 注意
  handleBack = (e) => {
    e && e.preventDefault()
    window.history.back()  
    const backuUrl = sessionStorage.getItem('backUrl')
    if (this.props.location.pathname === backuUrl) {
      return;
    }    
    this.routerArr.pop()   
    const backId = this.routerArr[this.routerArr.length -1] || sessionStorage.getItem('backId')
    this.setState({ id: backId || 0, list:[] }, () => {     
      this.getParamQuery()
    })
  }
  // 展开条件
  expandMenu = ()=> {
    this.setState({
      expandStatus: !this.state.expandStatus,
    })
  }

  render() {
    let loading = this.state.loading;

    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: '字典名称',
        key: 'name',
        dataIndex: 'name',
        width: '160px',
        align: 'left',
        className: 'leftCol tdWidth',
        render(name) {
          return Utils.formatTableColumn(name) 
        }
      },
      {
        title: '字典代码',
        key: 'code',
        dataIndex: 'code',
        width: '100px',
        className: 'tdWidth',
        render(code) {
          return Utils.formatTableColumn(code) 
        }
      },
      {
        title: '更新时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: '100px',
        render(updateTime) {
          return Utils.formateDateToYMD(updateTime)
        }
      }      
    ];

    if(this.state.isShowOpt) {
      columns.push(
        {
          title: '操作',
          key: 'opereate',
          width: '240px',
          align: 'right',
          className: 'tableOptCol',
          render: (text, item, index) => {
            return (
              <div  >
                {
                  this.state.btnAuth.indexOf('dict-edit') !== -1 ? 
                  
                    <NavLink to={'/home/system/dictChildAdd/updOpt/' + text.id} >
                      <Button size="small" >修改</Button>
                    </NavLink>
                    : ''
                }
                
                {
                  this.state.btnAuth.indexOf('dict-delete') !== -1 ? 
                  <Button size="small"  onClick={(e) => this.handleDelete(text, item, index)}  >
                    删除
                  </Button>
                  : ''
                }
  
                
  
                {
                   this.state.btnAuth.indexOf('dict-lookMore') !== -1 ?
                    text.childDicts ?
                      
                        <NavLink to={'/home/system/dictManage/detail/' + text.id} onClick={() => this.handleDetail(item)}> 
                          <Button size="small">查看 </Button>
                        </NavLink>:
                     ''
                    : ''
                  }
  
                {
                  this.state.btnAuth.indexOf('addNextDict') !== -1 ? 
                 
                  <NavLink to={'/home/system/dictChildAdd/addOpt/' + text.id} >
                    <Button size="small">新增下级字典 </Button>
                  </NavLink>: ''
                }
                              
              </div>
            )
          }
        },
      )
    }

    return (
      <div className='dictBg'>
        <div className="roleAdd">
          <div className="nav">
            <NavLink to='/home/system/dictManage/dict' > 字典管理 </NavLink> >  <span>字典数据 ( {this.state.name}: {this.state.code} )</span>
          </div>
        </div>
        <div className="system"> 
          <div className="searchWrap">
            <UserManageBar title="字典管理" />
            <div className='expandMenu iconfont icon-chazhaobiaodanliebiao' onClick={this.expandMenu} ></div>       
        { 
          this.state.expandStatus ?         
          <div className="systemSearch">
            <Form layout="inline">
              <Row gutter={12}>
                <Col span="4">
                  <FormItem  >
                    <label htmlFor="字典名称">字典名称</label>
                    {
                      getFieldDecorator('name', {
                      })(
                        <Input placeholder="字典名称" />
                        )
                    }
                  </FormItem>
                </Col>
                <Col span="4">
                  <FormItem style={{ marginTop: 38, }} >
                    <Button onClick={(item) => { this.queryList(item) }} style={{ background: '#00BB29', color: "#fff", marginRight: 4 }} >查询</Button>
                    <Button onClick={this.reset} style={{ background: '#ED1719', color: "#fff" }} type="danger">重置</Button>
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </div>
          : ''
        }    
        </div>   
         
          <div className="operate">
          {
            this.state.btnAuth.indexOf('addNextDict') !== -1 ? 
              <NavLink to={'/home/system/dictChildAdd/addOpt/'+ this.state.id} >
                <Button>新增</Button>
              </NavLink>
              : ''
          }
            
            <Button onClick={(e) => { this.handleBack(e) }}>
              返回
            </Button>
          </div>
          <UserManageBar title="详细数据" />

          <div className="detData reTable">
            <div style={{ backgroundColor: '#fff', minHeight:'500px' }}>
              <Table
              rowKey='id'
              key={`table-${this.state.list && this.state.list.length}`}
              bordered={false}
              columns={columns}
              onExpand = {this.onExpand}
              selections={false}
              defaultExpandAllRows = {this.state.defaultExpandAllRows}
              childrenColumnName='childDicts'
              loading={loading}
              dataSource={this.state.list}
              indentSize={12}
              pagination={false}
              />          
            </div>
          </div>

        </div>
      </div>
    )
  }
}

export default Form.create()(DictDetail);