import { Button, Card, Form, Input, Space, Table, Select, message, Modal } 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 {
  delUser,
  disableUser,
  enableUser,
  queryUserDetail,
  queryUserList,
} from '@/services/setting';
import { PageContainer } from '@ant-design/pro-components';
import Check from '@/pages/setting/UserManagement/check';
import { queryRole } from '@/services/role';

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 [detailData, setDetailData] = 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 [roleList, setRoleList] = 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);
      }
    });
  };

  const getRoleList = () => {
    queryRole({ q: 'list' }).then((res) => {
      if (res && res.code === 0) {
        setRoleList(res.data.list);
      }
    });
  };

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

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

  // 编辑弹框
  const toEdit = (data: any) => {
    // 获取详情信息
    queryUserDetail(data.record_id).then((res) => {
      if (res?.code === 0) {
        setDetailData(res?.data || null);
        setVisible(true);
      }
    });
  };

  // 新增编辑弹框回调
  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 toDel = (record: DataType) => {
    Modal.confirm({
      title: '删除',
      content: `确认删除用户：[${record.user_name}]`,
      onOk: () => {
        delUser(record.record_id)
          .then((res) => {
            if (res.data && res.data.status === 'OK') {
              message.success('删除成功');
              getListData();
            } 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: 'user_name',
      key: 'user_name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '公司名称',
      dataIndex: 'company',
      key: 'company',
    },
    {
      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>
          <a
            style={{ color: 'red' }}
            onClick={() => {
              toDel(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 name="role_id" label="角色">
            <Select style={{ width: '175px' }} placeholder="请选择状态">
              {roleList && roleList.length
                ? roleList.map((res: any) => {
                    return (
                      <Select.Option key={res.record_id} value={res.record_id}>
                        {res.name}
                      </Select.Option>
                    );
                  })
                : null}
            </Select>
          </Form.Item>
          <Form.Item name="company" 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={paginationProps}
          loading={loading}
          onChange={tableChange}
        />
        {visible && <Edit visible={visible} editCallback={editCallback} detailData={detailData} />}
        {checkVisible && <Check visible={checkVisible} id={checkId} onCallback={checkCallback} />}
      </Card>
    </PageContainer>
  );
};
export default UserManagement;
