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

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

import UpdateIntegralFormModal from './components/UpdateIntegralFormModal';
import UpdateBonusFormModal from './components/UpdateBonusFormModal';

import AuthConsumer from '@/components/Authority';

import services from '@/services/admin';

const { userItems, userBonus, userUnbonus } = services.UserController;

export default () => {

  const [updateBonusFormModal, setUpdateBonusFormModal] = useState(false);

  const actionRef = useRef();

  const initRow = {
    id: '',
    integral: 0,
    type: '+',
    level_id: '',
    group_id: ''
  };

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

  const handleBnbonus = async (fields) => {

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

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

  const handleBonusUpdate = async (fields) => {

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

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

      setUpdateBonusFormModal(false);
    }
  };

  const columns = [
    {
      title: '头像',
      dataIndex: 'avatar',
      valueType: 'avatar',
      search: false,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      search: false,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      search: false,
    },
    // {
    //   title: '等级',
    //   dataIndex: 'level_id',
    //   search: false,
    //   render: (_, record) => {
    //     if (record?.bonus_level) {
    //       return <>
    //         <div>等级：{record?.bonus_level?.name}</div>
    //         <div>备注：{record.bonus_level?.note}</div>
    //       </>;
    //     }
    //   },
    // },
    {
      title: '所在分组',
      dataIndex: 'level_id',
      search: false,
      render: (_, record) => {
        if (record?.bonus_group) {
          return <>
            <div>组号：{record.bonus_group?.num}组</div>
            <div>人数：{record.bonus_group?.user_num_use}/{record.bonus_group?.user_num}</div>
            <div>桩数量：{record.bonus_group?.device_num_use}/{record.bonus_group?.device_num}</div>
            <div>桩数量（赠）：{record.bonus_group?.device_num_give_use}/{record.bonus_group?.device_num_give}</div>
          </>;
        }
      },
    },
    {
      title: '角色',
      dataIndex: 'is_admin',
      search: false,
      render: (_, record) => {
        return record.is_admin == 1 ? '管理员' : '';
      },
    },
    {
      title: '余额',
      dataIndex: 'money',
      search: false,
    },
    {
      title: '积分',
      dataIndex: 'integral',
      search: false,
    },
    {
      title: '收益',
      dataIndex: 'profit',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return <Space>
          {
            record.group_id ? <AuthConsumer action={'admin/user/unbonus'} key="admin/user/unbonus">
              <Popconfirm
                title="确认退出分组？"
                onConfirm={() => {
                  handleBnbonus(record);
                }}
              >
                <Button
                  danger
                  type="link"
                >
                  退出分组
                </Button>
              </Popconfirm>
            </AuthConsumer> : <AuthConsumer action={'admin/user/bonus'} key="admin/user/bonus">
              <Button
                type="link"
                onClick={() => {
                  setRow(record);
                  setUpdateBonusFormModal(true);
                }}
              >
                加入分组
              </Button>
            </AuthConsumer>
          }
        </Space>
      }
    },
  ];

  return (
    <PageContainer
      ghost
    >
      <>
        <UpdateBonusFormModal
          values={row}
          modalOpenState={updateBonusFormModal}
          onModalOpenState={setUpdateBonusFormModal}
          onSubmit={handleBonusUpdate}
        />
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={{
            defaultCollapsed: false,
          }}
          request={async (params, sorter, filter) => {
            const { data, success } = await userItems({
              ...params,
              sorter,
              filter,
            });
            return {
              data: data?.items || [],
              total: data?.total,
              success,
            };
          }}
          columns={columns}
          pagination={{
            showSizeChanger: true,
          }}
        />
      </>
    </PageContainer>
  );
};
