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

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

import AuthConsumer from '@/components/Authority';

import services from '@/services/admin';

const { userLevelItems, userLevelCreate, userLevelDelete, userLevelUpdate } = services.UserLevelController;

export default () => {

  const actionRef = useRef();

  const initRow = {
    id: '',
    name: '',
    level: '',
    device_num: '',
    user_num: '',
    note: ''
  };

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

  const handleDelete = async (fields) => {

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

  };

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

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

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

  const handleUpdate = async (fields) => {

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

    if (success) {
      actionRef.current?.reload();
    }
  };

  const columns = [
    {
      title: '会员等级',
      dataIndex: 'level',
      search: false,
    },
    {
      title: '晋级(设备数=自购+下级)',
      dataIndex: 'device_num',
      search: false,
    },
    {
      title: '充电桩销售提成',
      dataIndex: 'device_sales',
      search: false,
    },
    {
      title: '充电积分(每次)',
      dataIndex: 'device_order',
      search: false,
    },
    {
      title: '推荐充电积分(每次)',
      dataIndex: 'device_order_invite',
      search: false,
    },
    {
      title: '积分转化率(‰)',
      dataIndex: 'change_rate',
      search: false,
    },
    {
      title: '备注',
      dataIndex: 'note',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
      editable: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (text, record, _, action) => [
        <AuthConsumer action={'admin/user_level/update'} key="admin/user_level/update">
          <Button
            key="editable"
            type="link"
            onClick={() => {
              setRow(record);
              action?.startEditable?.(record.id);
            }}
          >
            编辑
          </Button>
        </AuthConsumer>,
        <AuthConsumer action={'admin/user_level/delete'} key="admin/user_level/delete">
          <Popconfirm
            title="确认删除？"
            onConfirm={() => {
              handleDelete({ id: [record.id] });
            }}
          >
            <Button
              key="delete"
              type="link"
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </AuthConsumer>
      ],
    },
  ];

  return (
    <PageContainer
      ghost
    >
      <>
        <EditableProTable
          actionRef={actionRef}
          rowKey="id"
          search={false}
          request={async (params, sorter, filter) => {
            const { data, success } = await userLevelItems({
              ...params,
              sorter,
              filter,
            });
            return {
              data: data || [],
              total: 0,
              success,
            };
          }}
          recordCreatorProps={
            {
              position: 'bottom',
              record: () => ({ id: 0 }),
            }
          }
          editable={{
            type: 'multiple',
            editableKeys,
            onSave: async (rowKey, data, row) => {
              if (rowKey) {
                handleUpdate(data)
              } else {
                handleCreate(data)
              }

            },
            onChange: setEditableRowKeys,
          }}
          columns={columns}
          pagination={false}
        />
      </>
    </PageContainer>
  );
};
