AdminList.js 12.5 KB
Newer Older
sin's avatar
sin committed
1 2 3 4
/* eslint-disable */

import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
5
import {Card, Form, Input, Button, Modal, message, Table, Divider, Tree, Spin, Row, Col, Select, Icon} from 'antd';
6
import { checkTypeWithEnglishAndNumbers } from '../../../helpers/validator'
sin's avatar
sin committed
7 8 9
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from './AdminList.less';
10
import moment from "moment";
11
import PaginationHelper from "../../../helpers/PaginationHelper";
sin's avatar
sin committed
12 13

const FormItem = Form.Item;
14
const { TreeNode } = Tree;
sin's avatar
sin committed
15 16
const status = ['未知', '正常', '禁用'];

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
function List ({ dataSource, loading, pagination, searchParams, dispatch,
                 handleModalVisible, handleRoleAssignModalVisible}) {

  function handleRoleAssign(record) {
    // 显示 Modal
    handleRoleAssignModalVisible(true, record);
    // 查询角色列表
    dispatch({
      type: 'adminList/queryRoleList',
      payload: {
        id: record.id,
      },
    });
  }

  function handleStatus(record) {
    Modal.confirm({
      title: record.status === 1 ? '确认禁用' : '取消禁用',
      content: `${record.username}`,
      onOk() {
        dispatch({
          type: 'adminList/updateStatus',
          payload: {
            id: record.id,
            status: record.status === 1 ? 2 : 1,
          },
        });
      },
      onCancel() {},
    });
  }

  function handleDelete(record) {
    Modal.confirm({
      title: `确认删除?`,
      content: `${record.username}`,
      onOk() {
        dispatch({
          type: 'adminList/delete',
          payload: {
            id: record.id,
          },
        });
      },
      onCancel() {},
    });
  }

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
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username'
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        return <span>{status[val]}</span>; // TODO 芋艿,此处要改
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '操作',
      width: 360,
      render: (text, record) => {
91
        const statusText = record.status === 1 ? '禁用' : '开启'; // TODO 芋艿,此处要改
92 93
        return (
          <Fragment>
94
            <a onClick={() => handleModalVisible(true, 'update', record)}>编辑</a>
95
            <Divider type="vertical" />
96
            <a onClick={() => handleRoleAssign(record)}>角色分配</a>
97
            <Divider type="vertical" />
98
            <a className={styles.tableDelete} onClick={() => handleStatus(record)}>
99 100
              {statusText}
            </a>
101 102 103 104 105 106 107
            {
              record.status === 2 ?
                <span>
                  <Divider type="vertical" />
                  <a className={styles.tableDelete} onClick={() => handleDelete(record)}>
                    删除
                  </a>
108
                </span> : null
109
            }
110 111 112 113 114 115
          </Fragment>
        );
      },
    },
  ];

116
  function onPageChange(page) { // 翻页
117 118 119 120 121 122 123 124
    dispatch({
      type: 'adminList/query',
      payload: {
        pageNo: page.current,
        pageSize: page.pageSize,
        ...searchParams
      }
    })
125
  }
126 127 128 129 130

  return (
    <Table
      columns={columns}
      dataSource={dataSource}
131
      loading={loading}
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
      rowKey="id"
      pagination={pagination}
      onChange={onPageChange}
    />
  )
}

// 搜索表单
const SearchForm = Form.create()(props => {
  const {
    form,
    form: { getFieldDecorator },
    dispatch
  } = props;

  function search() {
    dispatch({
      type: 'adminList/query',
      payload: {
        ...PaginationHelper.defaultPayload,
        ...form.getFieldsValue()
      }
    })
  }

  // 提交搜索
  function handleSubmit(e) {
    // 阻止默认事件
    e.preventDefault();
    // 提交搜索
    search();
  }

  // 重置搜索
  function handleReset() {
    // 重置表单
    form.resetFields();
    // 执行搜索
    search();
  }

  return (
    <Form onSubmit={handleSubmit} layout="inline">
      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        <Col md={8} sm={24}>
          <FormItem label="昵称">
            {getFieldDecorator('nickname')(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>
        <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={handleReset}>
                重置
              </Button>
            </span>
        </Col>
      </Row>
    </Form>
  );
});

196
// 添加 or 修改 Form 表单
197
const AddOrUpdateForm = Form.create()(props => {
198
  const { dispatch, modalVisible, form, handleModalVisible, modalType, formVals } = props;
sin's avatar
sin committed
199 200

  const okHandle = () => {
201
    form.validateFields((err, fields) => {
sin's avatar
sin committed
202
      if (err) return;
203 204 205 206 207 208 209 210 211 212 213 214
      // 添加表单
      if (modalType === 'add') {
        dispatch({
          type: 'adminList/add',
          payload: {
            body: {
              ...fields,
            },
            callback: () => {
              // 清空表单
              form.resetFields();
              // 提示
215
              message.success('新建成功');
216 217 218 219 220 221 222 223 224 225 226
              // 关闭弹窗
              handleModalVisible();
            },
          },
        });
        // 修改表单
      } else {
        dispatch({
          type: 'adminList/update',
          payload: {
            body: {
227
              id: formVals.id,
228 229 230 231 232 233
              ...fields,
            },
            callback: () => {
              // 清空表单
              form.resetFields();
              // 提示
234
              message.success('编辑成功');
235 236 237 238 239 240
              // 关闭弹窗
              handleModalVisible();
            },
          },
        });
      }
sin's avatar
sin committed
241 242 243
    });
  };

244
  const title = modalType === 'add' ? '新建员工' : '更新员工';
sin's avatar
sin committed
245 246 247 248 249 250
  return (
    <Modal
      destroyOnClose
      title={title}
      visible={modalVisible}
      onOk={okHandle}
251
      okText='保存'
sin's avatar
sin committed
252 253
      onCancel={() => handleModalVisible()}
    >
254
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="用户名">
sin's avatar
sin committed
255
        {form.getFieldDecorator('username', {
256
          rules: [{ required: true, message: '请输入用户名!'},
257
            {max: 16, min:6, message: '长度为 6-16 位'},
258 259
            { validator: (rule, value, callback) => checkTypeWithEnglishAndNumbers(rule, value, callback, '数字以及字母')}
          ],
260
          initialValue: formVals.username,
sin's avatar
sin committed
261 262 263 264
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="昵称">
        {form.getFieldDecorator('nickname', {
265
          rules: [{ required: true, message: '请输入昵称!'},
266 267
            {max: 10, message: '姓名最大长度为 10'}],
          initialValue: formVals.nickname,
sin's avatar
sin committed
268 269 270 271
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="密码">
        {form.getFieldDecorator('password', {
272
          rules: [{ required: modalType === 'add', message: '请填写密码'}, // 添加时,必须输入密码
273 274
            {max: 16, min: 6, message: '长度为 6-18 位'}],
          initialValue: formVals.password,
sin's avatar
sin committed
275 276 277 278 279 280
        })(<Input placeholder="请输入" type="password" />)}
      </FormItem>
    </Modal>
  );
});

281
// 角色分配 Modal
282 283 284 285 286 287 288 289
const RoleAssignModal = Form.create()(props => {
  const {
    modalVisible,
    form,
    handleModalVisible,
    treeData,
    checkedKeys,
    loading,
290 291
    formVals,
    dispatch,
292 293
  } = props;

294 295 296 297 298 299 300 301 302 303 304 305
  const handleCheckBoxClick = checkedKeys => {
    // 获得新选择
    const newCheckedKeys = checkedKeys.map(item => {
      return parseInt(item);
    });
    // 设置到 model 中
    dispatch({
      type: 'adminList/changeRoleCheckedKeys',
      payload: newCheckedKeys,
    });
  };

306 307
  const renderTreeNodes = data => {
    return data.map(item => {
308
      if (item.children) { // 递归拼接节点
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
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.title} key={item.key} dataRef={item} />;
    });
  };

  const renderModalContent = treeData => {
    const RenderTreeNodes = renderTreeNodes(treeData);
    if (RenderTreeNodes) {
      return (
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="角色">
          {form.getFieldDecorator('name', {})(
            <Tree
              defaultExpandAll={true}
              checkable={true}
              multiple={true}
              checkedKeys={checkedKeys}
              onCheck={handleCheckBoxClick}
            >
              {renderTreeNodes(treeData)}
            </Tree>
          )}
        </FormItem>
      );
    } else {
      return null;
    }
  };

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
      // debugger;
      dispatch({
        type: 'adminList/roleAssign',
        payload: {
          body: {
            id: formVals.id,
            roleIds: checkedKeys,
          },
          callback: () => {
            // 清空表单
            form.resetFields();
            // 提示
            message.success('分配角色成功');
            // 关闭弹窗
            handleModalVisible(false);
          },
        },
362 363 364 365 366 367 368 369 370 371 372 373
      });
    });
  };

  return (
    <Modal
      destroyOnClose
      title="分配角色"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
374 375 376
      <Spin spinning={loading}>
        {renderModalContent(treeData)}
      </Spin>
377 378 379 380
    </Modal>
  );
});

381 382

@connect(({ adminList }) => ({
383 384 385
  // list: adminList.list,
  // pagination: adminList.pagination,
  ...adminList,
sin's avatar
sin committed
386
}))
387

388
// 主界面
sin's avatar
sin committed
389
@Form.create()
390
class AdminList extends PureComponent {
sin's avatar
sin committed
391 392 393 394 395

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'adminList/query',
396 397 398
      payload: {
        ...PaginationHelper.defaultPayload
      },
sin's avatar
sin committed
399 400 401
    });
  }

402
  handleModalVisible = (modalVisible, modalType, record) => {
403 404 405 406 407 408
    const { dispatch } = this.props;
    dispatch({
      type: 'adminList/setAll',
      payload: {
        modalVisible,
        modalType,
409
        formVals: record || {}
410 411 412 413
      },
    });
  };

414
  handleRoleAssignModalVisible = (roleModalVisible, record) => {
415 416
    const { dispatch } = this.props;
    dispatch({
417
      type: 'adminList/setAll',
418
      payload: {
419 420
        roleModalVisible: roleModalVisible,
        formVals: record || {}
421 422 423 424
      },
    });
  };

sin's avatar
sin committed
425
  render() {
426
    // let that = this;
427 428 429 430 431
    const { dispatch,
      list, listLoading, searchParams, pagination,
      modalVisible, modalType, formVals,
      confirmLoading,
      roleList, roleModalVisible, roleAssignLoading, roleCheckedKeys  } = this.props;
sin's avatar
sin committed
432

433 434 435 436 437
    // 列表属性
    const listProps = {
      dataSource: list,
      pagination,
      searchParams,
438
      dispatch,
439 440
      loading: listLoading,
      confirmLoading,
441
      handleModalVisible: this.handleModalVisible, // Function
442
      handleRoleAssignModalVisible: this.handleRoleAssignModalVisible, // Function
443 444 445 446 447 448 449
    };

    // 搜索表单属性
    const searchFormProps = {
      dispatch,
    };

450 451
    // 添加 or 更新表单属性
    const addOrUpdateFormProps = {
452
      modalVisible,
453 454
      modalType,
      formVals,
455 456 457
      dispatch,
      handleModalVisible: this.handleModalVisible, // Function
    };
458

459 460 461 462 463 464 465 466 467 468
    // 分配角色 Modal 属性
    const roleAssignModal = {
      loading: roleAssignLoading,
      treeData: roleList,
      formVals,
      checkedKeys: roleCheckedKeys,
      modalVisible: roleModalVisible,
      dispatch,
      handleModalVisible: this.handleRoleAssignModalVisible, // Function
    };
sin's avatar
sin committed
469 470

    return (
471
      <PageHeaderWrapper>
sin's avatar
sin committed
472 473
        <Card bordered={false}>
          <div className={styles.tableList}>
474 475 476
            <div className={styles.tableListForm}>
              <SearchForm {...searchFormProps} />
            </div>
sin's avatar
sin committed
477 478 479 480 481 482
            <div className={styles.tableListOperator}>
              <Button
                icon="plus"
                type="primary"
                onClick={() => this.handleModalVisible(true, 'add', {})}
              >
483
                新建员工
sin's avatar
sin committed
484 485 486
              </Button>
            </div>
          </div>
487
          <List {...listProps} />
sin's avatar
sin committed
488
        </Card>
489 490 491 492

        <AddOrUpdateForm {...addOrUpdateFormProps} />

        <RoleAssignModal {...roleAssignModal} />
sin's avatar
sin committed
493 494 495 496 497
      </PageHeaderWrapper>
    );
  }
}

498
export default AdminList;