import React, { useEffect, useState } from 'react';
import { Button, Card, Form, Input, message, Modal, Space, Table } from 'antd';
import { PlusCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import type { ColumnsType } from 'antd/es/table';
import Edit from './edit';
import { delBanner, queryBanner } from '@/services/banner';

interface DataType {
  name: string;
  level: string;
  record_id: string;
}

const BannerManagement: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [dataList, setDataList] = useState([]);
  const [editData, setEditData] = useState(null);
  const [visible, setVisible] = useState(false);
  const [searchData, setSearchData] = useState<object | null>({});
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });

  //  获取列表数据
  const getList = () => {
    const params = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryBanner(params).then((res) => {
      if (res && res.code === 0) {
        setDataList(res.data.list || []);
        setLoading(false);
      }
    });
    setDataList([]);
    setLoading(false);
  };

  useEffect(() => {
    setLoading(true);
    getList();
  }, []);

  const onFinish = () => {
    form.validateFields().then((data) => {
      setLoading(true);
      setSearchData(data);
    });
  };

  useEffect(() => {
    getList();
  }, [searchData]);

  // 分页切换
  const tableChange = () => {
    setLoading(true);
    const params = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryBanner(params).then((res) => {
      if (res?.code === 0) {
        setDataList(res?.data?.list || []);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  // 重置
  const onReset = () => {
    form.resetFields();
    setLoading(true);
    setSearchData(null);
  };

  // 新增弹框打开
  const onAdd = () => {
    setEditData(null);
    setVisible(true);
  };

  //  编辑弹框打开
  const toEdit = (data: any) => {
    setEditData(data);
    setVisible(true);
  };

  //  编辑回调
  const onEditCallback = () => {
    setVisible(false);
    getList();
  };

  //  删除
  const toDel = (record: any) => {
    Modal.confirm({
      title: '删除',
      content: `确认删除banner图：[${record.title}]`,
      onOk: () => {
        delBanner(record.record_id)
          .then((res) => {
            if (res.code === 0) {
              message.success('删除成功');
              getList();
            } else {
              message.error('删除失败');
            }
          })
          .catch((e) => {
            message.error(e?.message);
          });
      },
    });
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, row: any, index: number) => index + 1,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_, record: any) => {
        return <span>{{ 1: '停用', 2: '启用' }[record.status]}</span>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              toEdit(record);
            }}
          >
            编辑
          </a>
          <a
            style={{ color: 'red' }}
            onClick={() => {
              toDel(record);
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <div>
        <Card>
          <Form form={form} layout="inline" onFinish={onFinish}>
            <Form.Item name="name" label="区域名称">
              <Input placeholder="请输入区域名称" />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  <SearchOutlined />
                  查询
                </Button>
                <Button htmlType="button" onClick={onReset}>
                  <ReloadOutlined />
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
          <Button htmlType="button" type="primary" style={{ margin: '20px 0' }} onClick={onAdd}>
            <PlusCircleOutlined />
            新增banner图
          </Button>
          <Table
            columns={columns}
            dataSource={dataList}
            rowKey={(record) => record.record_id}
            pagination={pagination}
            loading={loading}
            onChange={tableChange}
          />
          {visible && <Edit editCallback={onEditCallback} params={editData} visible={visible} />}
        </Card>
      </div>
    </PageContainer>
  );
};
export default BannerManagement;
