import React, { useRef, useEffect, useState } from 'react';
import { Button, Space, Select, Popconfirm } from 'antd';
import {
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';

import AuthConsumer from '@/components/Authority';
import CreateFormModal from './components/CreateFormModal';
import LevelFormModal from './components/LevelFormModal';
import MoneyFormModal from './components/MoneyFormModal';
import TempFormModal from './components/TempFormModal';
import TradeFormModal from './components/TradeFormModal';
import ShopModal from './components/ShopModal';
import services from '@/services/admin';

const { shopItems, shopMoney, shopCreate, shopLevel, shopTemp, shopTrade } = services.ShopController;

export default () => {
  const [createFormModal, setCreateFormModal] = useState(false);
  const [levelFormModal, setLevelFormModal] = useState(false);
  const [moneyFormModal, setMoneyFormModal] = useState(false);
  const [tempFormModal, setTempFormModal] = useState(false);
  const [tradeFormModal, setTradeFormModal] = useState(false);
  const [shopOption, setShopOption] = useState([]);

  const [shopModal, setBonusFormModal] = useState(false);

  const actionRef = useRef();

  const initRow = {
    id: '',
    username: '',
    nickname: '',
    vip: 0,
    password: '',
    mobile: '',
    level: 0,
    moeny: 0,
    profit: 0,
    device_num: 0
  };

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

  const [selectedRowsState, setSelectedRows] = useState([]);


  const handleTemp = async (fields) => {

    const { success } = await shopTemp(fields);
    if (success) {
      actionRef.current?.reload();
      setTempFormModal(false);
    }
  };

  const handleTrade = async (fields) => {

    const { success } = await shopTrade(fields);
    if (success) {
      actionRef.current?.reload();
      setTradeFormModal(false);
    }
  };

  const handleCreate = async (fields) => {
    setRow(fields);
    const { success } = await shopCreate({ ...fields });

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

  const handleMoney = async (fields) => {

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

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

  const handleLevel = async (fields) => {

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

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

      setLevelFormModal(false);
    }
  };


  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
      render: (_, record) => {
        return <Space>
          <div>{record?.id}</div>
          <Button
            type="link"
            onClick={() => {
              setRow(record);
              setBonusFormModal(true);
            }}
          >
            查看
          </Button>
        </Space>;
      },
    },
    {
      title: '投资人',
      dataIndex: 'username',
      search: true,
      render: (_, record) => {
        return <>
          <div>{record?.username}</div>
          <div>{record?.mobile}</div>
          <div>{`v${record?.level?.level} : ${record?.level?.name}`}</div>
        </>
      }
    },
    {
      title: '推荐人',
      dataIndex: 'pid',
      search: false,
      render: (_, record) => {
        return <>
          <div>{record?.pshop?.username}</div>
        </>
      }
    },
    // {
    //   title: '收益',
    //   dataIndex: 'profit',
    //   search: false,
    // },
    {
      title: '余额',
      dataIndex: 'money',
      search: false,
    },
    {
      title: '充电桩',
      dataIndex: 'device_num',
      search: false,
    },
    // {
    //   title: '期权值',
    //   dataIndex: 'option',
    //   search: false,
    // },
    {
      title: '备注',
      dataIndex: 'admin_note',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <AuthConsumer action={'admin/shop/money'} key="admin/shop/money">
            <Button
              danger
              type="link"
              onClick={() => {
                setRow(record);
                setMoneyFormModal(true)
              }}
            >
              余额变动
            </Button>
          </AuthConsumer>

        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      ghost
    >
      <>
        <TradeFormModal
          modalOpenState={tradeFormModal}
          onModalOpenState={setTradeFormModal}
          onSubmit={handleTrade}
        />
        <TempFormModal
          modalOpenState={tempFormModal}
          onModalOpenState={setTempFormModal}
          onSubmit={handleTemp}
        />
        <MoneyFormModal
          values={row}
          modalOpenState={moneyFormModal}
          onModalOpenState={setMoneyFormModal}
          onSubmit={handleMoney}
        />
        <LevelFormModal
          values={row}
          modalOpenState={levelFormModal}
          onModalOpenState={setLevelFormModal}
          onSubmit={handleLevel}
        />
        <CreateFormModal
          values={row}
          modalOpenState={createFormModal}
          onModalOpenState={setCreateFormModal}
          onSubmit={handleCreate}
        />
        <ShopModal
          values={row}
          modalOpenState={shopModal}
          onModalOpenState={setBonusFormModal}
        />
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          search={{
            defaultCollapsed: false,
          }}
          toolBarRender={() => [
            <AuthConsumer action={'admin/shop/trade'} key="admin/shop/trade">
              <Button
                danger
                onClick={() => {
                  setTradeFormModal(true)
                }}
              >
                账号变更
              </Button>
            </AuthConsumer>,
            <AuthConsumer action={'admin/shop/temp'} key="admin/shop/temp">
              <Button
                danger
                onClick={() => {
                  setTempFormModal(true)
                }}
              >
                转挂
              </Button>
            </AuthConsumer>,
            <AuthConsumer action={'admin/shop/level'} key="admin/shop/level">
              <Button
                danger
                onClick={() => {
                  setLevelFormModal(true)
                }}
              >
                等级变更
              </Button>
            </AuthConsumer>,
            <AuthConsumer action={'admin/shop/create'} key="admin/shop/create">
              <Button
                type="primary"
                onClick={() => {
                  setCreateFormModal(true)
                }}
              >
                添加
              </Button>
            </AuthConsumer>
          ]}
          request={async (params, sorter, filter) => {
            const { data, success } = await shopItems({
              ...params,
              sorter,
              filter,
            });
            return {
              data: data?.data || [],
              total: data?.total,
              success,
            };
          }}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows)
            },
          }}
          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/admin/delete'} key="admin/admin/delete">
            //       <Popconfirm
            //         title="确认删除？"
            //         onConfirm={() => {
            //           handleDelete({ id: selectedRowKeys });
            //         }}
            //       >
            //         <Button
            //           type="link"
            //           danger
            //         >
            //           批量删除
            //         </Button>
            //       </Popconfirm>
            //     </AuthConsumer>
            //   </Space>
            // );
          }}
          pagination={{
            showSizeChanger: true,
          }}
        />
      </>
    </PageContainer>
  );
};
