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 { adsItems, adsCreate, adsDelete, adsUpdate } = services.AdsController;

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

  const actionRef = useRef();

  const initRow = {
    id: '',
    title: '',
    cover: '',
    scene: 1

  };

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

  const handleDelete = async (fields) => {

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

  };

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

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

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

  const handleUpdate = async (fields) => {

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

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

      setUpdateFormModal(false);
    }
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      search: false,
    },
    {
      title: '标题',
      dataIndex: 'title',
      search: false,
    },
    {
      title: '图片',
      dataIndex: 'cover',
      valueType: 'image',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <AuthConsumer action={'admin/ads/update'} key="admin/ads/update">
            <Button
              type="link"
              onClick={() => {
                setRow(record);
                setUpdateFormModal(true)
              }}
            >
              编辑
            </Button>
          </AuthConsumer>
          <AuthConsumer action={'admin/ads/delete'} key="admin/ads/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={{
            defaultCollapsed: false,
          }}
          toolBarRender={() => [
            <AuthConsumer action={'admin/ads/create'} key="admin/ads/create">
              <Button
                type="primary"
                onClick={() => {
                  setCreateFormModal(true)
                }}
              >
                添加
              </Button>
            </AuthConsumer>
          ]}
          request={async (params, sorter, filter) => {
            const { data, success } = await adsItems({
              ...params,
              sorter,
              filter,
            });
            return {
              data: data || [],
              total: 0,
              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/ads/delete'} key="admin/ads/delete">
                  <Popconfirm
                    title="确认删除？"
                    onConfirm={() => {
                      handleDelete({ id: selectedRowKeys });
                    }}
                  >
                    <Button
                      type="link"
                      danger
                    >
                      批量删除
                    </Button>
                  </Popconfirm>
                </AuthConsumer>
              </Space>
            );
          }}
          pagination={false}
        />
      </>
    </PageContainer>
  );
};
