import React from 'react';
import './index.less';
import Page from '@src/containers/Page';
import TableLayout from '@src/layouts/TableLayout';
import ActionLayout from '@src/layouts/ActionLayout';
import Block from '@src/components/Block';
import { asyncDelConfirm, asyncForm, asyncSMessage } from '@src/services/AsyncTools';
import { System } from '../../../../stores/system';

const actionList = [
  {
    key: 'add',
    name: '新增',
  },
];

const itemList = [
  {
    key: 'id',
    type: 'hidden',
  },
  {
    key: 'username',
    name: '用户名',
    type: 'input',
    placeholder: '请输入用户名',
    require: true,
  },
  {
    key: 'password',
    name: '密码',
    type: 'password',
    placeholder: '请输入密码',
    require: true,
  },
];

export default class extends Page {
  init() {
    this.columns = [
      {
        title: '用户名',
        dataIndex: 'username',
      },
      {
        title: '操作',
        dataIndex: 'handler',
        render: (text, record) => {
          return <div className="table-button">
            {(
              <a onClick={() => {
                this.editAction(record);
              }} >编辑</a>
            )}
          </div>;
        },
      },
    ];
  }

  initData() {
    System.listManager(this.state.search).then(result => {
      this.setTableData(result.list, result.total);
    });
  }

  addAction() {
    asyncForm('新增', itemList, {}, data => {
      return System.addManager(data).then(() => {
        asyncSMessage('新增成功!');
        this.refresh();
      });
    });
  }

  editAction(row) {
    asyncForm('编辑', itemList, row, data => {
      return System.putManager(data).then(() => {
        asyncSMessage('编辑成功!');
        this.refresh();
      });
    });
  }

  delAction() {
    const { selectedKeys } = this.state;
    asyncDelConfirm('删除确认', '是否删除选中账号?', () => {
      Promise.all(selectedKeys.map(row => System.delManager({ id: row }))).then(() => {
        asyncSMessage('删除成功!');
        this.refresh();
      });
    });
  }

  renderView() {
    return (
      <Block flex>
        <ActionLayout
          itemList={actionList}
          selectedKeys={this.state.selectedKeys}
          onAction={key => this.onAction(key)}
        />
        <TableLayout
          // select
          columns={this.columns}
          list={this.state.list}
          pagination={this.state.page}
          loading={this.props.core.loading}
          onChange={(pagination, filters, sorter) => this.tableChange(pagination, filters, sorter)}
          onSelect={(keys, rows) => this.tableSelect(keys, rows)}
          selectedKeys={this.state.selectedKeys}
        />
      </Block>
    );
  }
}
