import React, { useRef } from 'react';
import { Button, Tag, Modal, message } from 'antd';

import router from 'umi/router';
import moment from 'moment';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import AuthButton from '@/components/AuthButton';
import TableList from '@/components/TableList';
import request from '@/utils/request';
import apis from '@/services/apis';

export default function BuildType() {
  const ref = useRef();

  const columns = [
    {
      title: '编号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      render: (_text, _record, index) => <span>{index + 1}</span>,
    },
    {
      title: '类型名称',
      dataIndex: 'buildingTypeName',
      key: 'buildingTypeName',
      align: 'center',
      render: (_, record) => (
        <Tag color="blue" onClick={() => toEdi(record.buildingTypeId)}>
          {record.buildingTypeName}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: (_, record) => <span>{moment(record.createDate).format('YYYY-MM-DD')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'row',
      key: 'row',
      align: 'center',
      render: withActions((_, record) => [
        <AuthButton name="building.type.delete" noRight={null}>
          <EditIcon text="删除" type="delete" onClick={() => deleteType(record)} />
        </AuthButton>,
        <AuthButton name="building.type.edit" noRight={null}>
          <EditIcon text="编辑" type="edit" onClick={() => toEdi(record.buildingTypeId)} />
        </AuthButton>,
      ]),
    },
  ];

  function deleteType(row) {
    row.status = -1;
    const modal = Modal.confirm();
    modal.update({
      content: '确认删除？',
      okText: '确认',
      cancelText: '关闭',
      onOk: () => {
        request({
          ...apis.buildingType.update,
          urlData: { id: row.buildingTypeId },
          data: { ...row },
        })
          .then(() => {
            ref.current.reload();
            message.info('删除成功！');
          })
          .catch(err => {
            // openNotificationWithIcon('error', err.message)
          });

        modal.destroy();
      },
      onCancel: () => {
        modal.destroy();
      },
    });
  }

  // 跳转修改页
  function toEdi(currentId) {
    router.push({
      pathname: '/building/type/edi',
      query: {
        id: currentId || '',
      },
    });
  }
  const actionRender = () => {
    return (
      <AuthButton name="admin.tdBuildingType.add" noRight={null}>
        <Button type="primary" onClick={() => toEdi()} style={{ marginBottom: '20px' }}>
          新增类型
        </Button>
      </AuthButton>
    );
  };

  return (
    <>
      <TableList
        ref={ref}
        rowKey="buildingTypeId"
        api={apis.buildingType.getList}
        // searchFields={searchFields}
        actionRender={actionRender}
        columns={columns}
      />
    </>
  );
}
