import { Button, Card, Form, Input, Space, Table, Image, Select, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { PlusCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment';
import Edit from '@/pages/setting/UserManagement/edit';
import { disableUser, enableUser, queryUserList } from '@/services/setting';
import { PageContainer } from '@ant-design/pro-components';
import Check from '@/pages/setting/UserManagement/check';

interface DataType {
  key: string;
  user_name: string;
  real_name: string;
  photo: string;
  phone: string;
  status: number;
  record_id: string;
  updated_at: string;
}

/**
 * 用户管理页面
 * @constructor
 */
const UserManagement: React.FC = () => {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [editData, setEditData] = useState<object | null>({});
  const [searchData, setSearchData] = useState<object | null>({});
  const [dataList, setDataList] = useState([]);
  const [pagination, setPagination] = useState({ total: 0, current: 1, pageSize: 10 });
  const [loading, setLoading] = useState(false);
  const [checkVisible, setCheckVisible] = useState(false);
  const [checkId, setCheckId] = useState('');

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

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

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

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

  // 新增编辑弹框回调
  const editCallback = () => {
    setVisible(false);
    setLoading(true);
    getListData();
  };

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

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

  // 启用
  const toEnable = (record: any) => {
    enableUser(record.record_id)
      .then((res) => {
        if (res.code === 0) {
          message.success('启用成功');
          setLoading(true);
          getListData();
        } else {
          message.error('启用失败');
        }
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  //停用
  const toDisable = (record: any) => {
    disableUser(record.record_id)
      .then((res) => {
        if (res.code === 0) {
          message.success('停用成功');
          setLoading(true);
          getListData();
        } else {
          message.error('停用失败');
        }
      })
      .catch((e) => {
        message.error(e?.message);
      });
  };

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

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

  //  查看
  const toCheck = (record: DataType) => {
    setCheckVisible(true);
    setCheckId(record?.record_id);
  };

  // 查看回调
  const checkCallback = () => {
    setCheckVisible(false);
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, row: any, index: number) => index + 1,
    },
    {
      title: '头像',
      dataIndex: 'photo',
      key: 'photo',
      render: (v) => v && <Image width={50} src={v} alt="头像" />,
    },
    {
      title: '用户姓名',
      dataIndex: 'user_name',
      key: 'user_name',
    },
    {
      title: '真实姓名',
      dataIndex: 'real_name',
      key: 'real_name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (v) =>
        v && (
          <span style={{ color: `${{ 1: '#00a650', 2: 'red' }[v]}` }}>
            {{ 1: '启用', 2: '停用' }[v]}
          </span>
        ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (v) => v && moment(v).format('YYYY-MM-DD HH:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              toEdit(record);
            }}
          >
            编辑
          </a>
          {record?.status === 2 && (
            <a
              style={{ color: 'green' }}
              onClick={() => {
                toEnable(record);
              }}
            >
              启用
            </a>
          )}
          {record?.status === 1 && (
            <a
              style={{ color: 'red' }}
              onClick={() => {
                toDisable(record);
              }}
            >
              停用
            </a>
          )}
          <a
            onClick={() => {
              toCheck(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="user_name" label="用户姓名">
            <Input placeholder="请输入用户姓名" />
          </Form.Item>
          <Form.Item name="real_name" label="真实姓名">
            <Input placeholder="请输入真实姓名" />
          </Form.Item>
          <Form.Item name="phone" label="手机号">
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select style={{ width: '175px' }} placeholder="请选择状态">
              <Select.Option key={1} value={1}>
                启用
              </Select.Option>
              <Select.Option key={2} value={2}>
                停用
              </Select.Option>
            </Select>
          </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={paginationProps}
          loading={loading}
          onChange={tableChange}
        />
        {visible && <Edit visible={visible} editCallback={editCallback} params={editData} />}
        {checkVisible && <Check visible={checkVisible} id={checkId} onCallback={checkCallback} />}
      </Card>
    </PageContainer>
  );
};
export default UserManagement;
