import { PageContainer } from '@ant-design/pro-components';
import { Button, Card, Cascader, Col, Form, Input, message, Modal, Row, Space, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { history } from 'umi';
import type { ColumnsType } from 'antd/es/table';
import { queryHomeList, updateArea } from '@/services/home';
import { queryTreeList } from '@/services/setting';

interface DataType {
  name: string;
  member: any[];
  power: number;
  record_id: string;
  district: string;
  province: string;
  city: string;
}

/**
 * 家列表
 * @constructor
 */
const Home: React.FC = () => {
  const [form] = Form.useForm();
  const [areaForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [searchData, setSearchData] = useState<object | null>({});
  const [dataList, setDataList] = useState([]);
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [areaVisible, setAreaVisible] = useState(false);
  const [areaList, setAreaList] = useState([]);
  const [areaData, setAreaData] = useState({} as DataType);

  const getData = () => {
    const params = {
      q: 'page',
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchData,
    };
    queryHomeList(params).then((res) => {
      if (res.code === 0) {
        setDataList(res.data.list);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  // 获取地区列表
  const getAreaList = () => {
    queryTreeList({ q: 'tree' }).then((res) => {
      if (res && res.code === 0) {
        setAreaList(res.data.list || []);
      }
    });
  };

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

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

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

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

  // table切换
  const tableChange = (page: any) => {
    setLoading(true);
    const param = {
      q: 'page',
      current: page.current,
      pageSize: page.pageSize,
      ...searchData,
    };
    queryHomeList(param).then((res) => {
      if (res.code === 0) {
        setDataList(res.data.list);
        setPagination(res.data.pagination);
        setLoading(false);
      }
    });
  };

  // 跳转到房间
  const toRoom = (record: DataType) => {
    history.push({ pathname: '/roomList', state: record.record_id });
  };

  // 修改地区 打开弹框
  const onChangeArea = (data: DataType) => {
    setAreaVisible(true);
    setAreaData(data);
  };

  // 地区弹框确认
  const handleAreaOk = () => {
    areaForm.validateFields().then((values) => {
      if (values) {
        const params = {
          province: values.area[0],
          city: values.area[1],
          district: values.area[2],
        };
        updateArea(params, areaData.record_id)
          .then((res) => {
            if (res && res.code === 0) {
              message.success('修改成功');
              setAreaVisible(false);
              getData();
            } else {
              message.error(res?.message);
            }
          })
          .catch((e) => {
            message.error(e?.message);
          });
      }
    });
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      width: 100,
      render: (_: any, row: any, index: number) => index + 1,
    },
    {
      title: '名称',
      width: 200,
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '设备编号',
      width: 200,
      dataIndex: 'gateway',
      key: 'gateway',
    },
    {
      title: '设备是否在线',
      width: 150,
      dataIndex: 'is_online',
      key: 'is_online',
      render: (v) => <span>{v ? '在线' : '离线'}</span>,
    },
    {
      title: '成员人数',
      width: 100,
      dataIndex: 'member',
      key: 'member',
      render: (v) => v && <span>{v.length}</span>,
    },
    {
      title: '地区',
      width: 150,
      dataIndex: 'district',
      key: 'district',
      render: (_, record) => {
        return (
          <a
            onClick={() => {
              onChangeArea(record);
            }}
            style={{ textDecoration: 'underline' }}
          >
            {record.province || record.city || record.district
              ? `${record.province} ${record.city} ${record.district}`
              : '无'}
          </a>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              toRoom(record);
            }}
          >
            查看房间
          </a>
        </Space>
      ),
    },
  ];

  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => {
      return <span> 共 {total}条 </span>;
    },
    ...pagination,
  };

  return (
    <PageContainer>
      <Card>
        <Form form={form} layout="inline" onFinish={onFinish}>
          <Form.Item name="like_name" label="名称">
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item name="like_gateway" 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>
        <Table
          columns={columns}
          dataSource={dataList}
          rowKey={(record: any) => record.record_id}
          pagination={paginationProps}
          loading={loading}
          onChange={tableChange}
          style={{ marginTop: '20px' }}
        />
        {areaVisible && (
          <Modal
            destroyOnClose
            title="选择地区"
            open={areaVisible}
            onOk={handleAreaOk}
            onCancel={() => {
              setAreaVisible(false);
            }}
          >
            <Form form={areaForm} preserve={false}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 16 }}
                    name="area"
                    label="所属地区"
                    rules={[{ required: true, message: '请选择所属地区' }]}
                    initialValue={
                      areaData?.province || areaData?.city || areaData?.district
                        ? [areaData?.province, areaData?.city, areaData?.district]
                        : []
                    }
                  >
                    <Cascader
                      options={areaList}
                      placeholder="请选择所属地区"
                      fieldNames={{ label: 'name', value: 'name', children: 'children' }}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Modal>
        )}
      </Card>
    </PageContainer>
  );
};
export default Home;
