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 { delCommunity, queryCommunity } from '@/services/reporting/community';
import Edit from './edit';

interface DataType {
  name: string;
  address: string;
  created_name: string;
  record_id: string;
}

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

  const getList = () => {
    const params = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryCommunity(params).then((res) => {
      if (res && res.code === 0) {
        setDataList(res.data.list || []);
        setLoading(false);
      }
    });
  };

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

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

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

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

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

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

  const toEdit = (record: any) => {
    setEditData(record);
    setVisible(true);
  };

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

  const toDel = (record: any) => {
    Modal.confirm({
      title: '删除',
      content: `确认删除菜单：[${record.name}]`,
      onOk: () => {
        delCommunity(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: 'name',
      key: 'name',
    },
    {
      title: '省市区',
      dataIndex: 'city',
      key: 'city',
      render: (_, data: any) => (
        <span>{`${data.province}` + ' ' + `${data.city}` + ' ' + `${data.district}`}</span>
      ),
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '创建人',
      dataIndex: 'created_name',
      key: 'created_name',
    },
    {
      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="like_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 />
            新增小区
          </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 CommunityManagement;
