import React, { useRef, useEffect, useState } from 'react';
import { history } from '@umijs/max';

import { Button, Space, Image, Popconfirm } from 'antd';
import {
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';

import AuthConsumer from '@/components/Authority';
import CreateFormModal from './components/CreateFormModal';
import UpdateFormModal from './components/UpdateFormModal';

import services from '@/services/admin';

const { deviceProfitItems, deviceProfitCreate, deviceProfitDelete, deviceProfitUpdate } = services.DeviceProfitController;

export default () => {
  const [createFormModal, setCreateFormModal] = useState(false);
  const [updateFormModal, setUpdateFormModal] = useState(false);

  const actionRef = useRef();

  const initRow = {
    id: '',
    real_money: 0,
    bonus_money: 0,
    note: '',
    date: null
  };

  const [row, setRow] = useState(initRow);

  const handleDelete = async (fields) => {

    const { success } = await deviceProfitDelete(fields);
    if (success) {
      actionRef.current.clearSelected();
      actionRef.current?.reload();
    }

  };

  const handleCreate = async (fields) => {
    setRow(fields);

    const { success } = await deviceProfitCreate({ ...fields });

    if (success) {
      setRow(initRow);
      actionRef.current?.reload();
      setCreateFormModal(false);
    }
  };

  const handleUpdate = async (fields) => {

    const { success } = await deviceProfitUpdate({ ...fields });

    if (success) {
      setRow(initRow);
      actionRef.current?.reload();
      setUpdateFormModal(false);
    }
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
    },
    {
      title: '结算日期',
      dataIndex: 'date',
      search: false,
    },
    {
      title: '收益',
      dataIndex: 'real_money',
      search: false,
    },
    {
      title: '分红额度',
      dataIndex: 'bonus_money',
      search: false,
    },
    {
      title: '分红人数',
      dataIndex: 'bonus_num',
      search: false,
    },
    {
      title: '备注',
      dataIndex: 'note',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <AuthConsumer action={'admin/device_profit/update'} key="admin/device_profit/update">
            <Button
              type="link"
              onClick={() => {
                setRow(record);
                setUpdateFormModal(true)
              }}
            >
              编辑
            </Button>
          </AuthConsumer>
          <AuthConsumer action={'admin/device_profit/delete'} key="admin/device_profit/delete">
            <Popconfirm
              title="确认删除？"
              onConfirm={() => {
                handleDelete({ id: [record.id] });
              }}
            >
              <Button
                type="link"
                danger
              >
                删除
              </Button>
            </Popconfirm>
          </AuthConsumer>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      ghost
    >
      <>
        <UpdateFormModal
          values={row}
          modalOpenState={updateFormModal}
          onModalOpenState={setUpdateFormModal}
          onSubmit={handleUpdate}

        />
        <CreateFormModal
          values={row}
          modalOpenState={createFormModal}
          onModalOpenState={setCreateFormModal}
          onSubmit={handleCreate}

        />
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={false}
          toolBarRender={() => [
            <AuthConsumer action={'admin/device_profit/create'} key="admin/device_profit/create">
              <Button
                type="primary"
                onClick={() => {
                  setRow(initRow);
                  setCreateFormModal(true)
                }}
              >
                添加
              </Button>
            </AuthConsumer>
          ]}
          request={async (params, sorter, filter) => {
            const { data, success } = await deviceProfitItems({
              ...params,
              sorter,
              filter,
            });
            return {
              data: data.items || [],
              total: data.total,
              success,
            };
          }}
          columns={columns}
          tableAlertRender={({
            selectedRowKeys,
            selectedRows,
            onCleanSelected,
          }) => {
            return (
              <Space size={24}>
                <span>已选 {selectedRowKeys.length} 项</span>
                <span>
                  <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                    取消选择
                  </a>
                </span>
              </Space>
            );
          }}
          tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
            return (
              <Space size={16}>
                <AuthConsumer action={'admin/device_profit/delete'} key="admin/device_profit/delete">
                  <Popconfirm
                    title="确认删除？"
                    onConfirm={() => {
                      handleDelete({ id: selectedRowKeys });
                    }}
                  >
                    <Button
                      type="link"
                      danger
                    >
                      批量删除
                    </Button>
                  </Popconfirm>
                </AuthConsumer>
              </Space>
            );
          }}
          pagination={false}
        />
      </>
    </PageContainer>
  );
};
