import React, { useEffect, useState, useReducer } from 'react';

import { getAgent, stopOrOpenAgent } from '@/services/agent';
import { getRoleList } from '@/services/role';
import { Button, Card, Col, Input, Row, Select, Space, Table, message, Tag } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import DetailModal from './detail';

const { Option } = Select;

type User = {
  id: string;
  nickName: string;
  phoneNumber: number;
  region: string;
  authRoles: string;
  followBarNum: number;
  postsNum: number;
  state: number;
  caeateTime: string;
  action?: React.ReactNode;
};

export type roleListType = {
  id: string;
  label: string;
  [key: string]: any;
};

type initStateType = {
  curPage: number;
  roleId: string;
  state: number;
  label: string | number;
};

type Action = {
  type: string;
  [key: string]: any;
};

const initState: initStateType = {
  curPage: 1,
  roleId: '',
  state: 2,
  label: '',
};

const reducer: React.Reducer<initStateType, Action> = (State, action): initStateType => {
  const { type, value } = action;

  switch (type) {
    case 'page':
      return { ...State, curPage: value };
    case 'state':
      return { ...State, state: value };
    case 'label':
      return { ...State, label: value };
    case 'roleId':
      return { ...State, roleId: value };
    case 'reload':
      return { ...State, roleId: '', state: 2, label: '' };
    default:
      throw new Error('没有对应的initStateType类型');
  }
};

const Agent: React.FC = () => {
  const [state, dispatch] = useReducer(reducer, initState);

  const [agentList, setAgentList] = useState<User[]>([]);

  const [roleList, setRoleList] = useState<roleListType[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);

  // 弹窗
  const [visible, setVisible] = useState<boolean>(false);

  // 当前点击的代理商
  const [id, setId] = useState<string>('');

  // 获取代理商列表
  const GetAgent = async () => {
    setLoading(true);
    const { code, data } = await getAgent(state);
    setLoading(false);
    if (code === 0) {
      const { records, total: Total } = data;
      setAgentList(records);
      setTotal(Total);
    }
  };

  // 获取权限列表
  const GetRoleList = async () => {
    const { code, data } = await getRoleList({ curPage: 1 });
    if (code === 0) {
      const { records } = data;
      setRoleList([{ id: '', label: '全部' }, ...records]);
    }
  };

  // 停用或者启用代理商
  const StopOrOpenAgent = async (text: Record<string, any>, index: number): Promise<void> => {
    setLoading(true);
    const { code } = await stopOrOpenAgent(text.id, { state: text.state === 1 ? 0 : 1 });
    setLoading(false);
    if (code === 0) {
      const a = { ...text, state: text.state === 1 ? 0 : 1 };
      const b = JSON.parse(JSON.stringify(agentList));
      b.splice(index, 1, a);
      setAgentList(b);
      message.success('操作成功');
    }
  };

  useEffect(() => {
    GetAgent();
    GetRoleList();
  }, []);

  // 重置搜索条件
  const reloadSate = (): void => dispatch({ type: 'reload', value: '' });
  // 打开弹窗
  const openModal = (value: Record<string, any>): void => {
    setVisible(true);
    setId(value.id);
  };

  // 关闭弹窗
  const closeModal = (): void => setVisible(false);

  // 账户状态
  const changeAccState = (value: number): void => dispatch({ type: 'state', value });

  // 手机号
  const changePhone = (e: React.ChangeEvent<HTMLInputElement>): void =>
    dispatch({ type: 'label', value: e.target.value });

  // 选择角色
  const changeRole = (value: string): void => dispatch({ type: 'roleId', value });

  // 分页
  const pagination = (changePage: number): void => dispatch({ type: 'page', value: changePage });

  return (
    <PageContainer title="代理商列表">
      <Card>
        <Row gutter={[16, 16]} justify="space-between">
          <Col span={10}>
            <Space>
              <Select
                placeholder="请选择认证角色"
                style={{ width: 200 }}
                onChange={changeRole}
                value={state.roleId}
              >
                {roleList.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.label}
                  </Option>
                ))}
              </Select>
              <Select
                placeholder="请选择账号状态"
                style={{ width: 200 }}
                onChange={changeAccState}
                value={state.state}
              >
                <Option value={2}>全部</Option>
                <Option value={1}>启用</Option>
                <Option value={0}>禁用</Option>
              </Select>
              <Input
                onChange={changePhone}
                value={state.label}
                style={{ width: 200 }}
                placeholder="输入手机号/姓名"
              ></Input>
            </Space>
          </Col>
          <Col>
            <Space>
              <Button type="primary" onClick={GetAgent}>
                搜索
              </Button>
              <Button onClick={reloadSate}>重置</Button>
            </Space>
          </Col>
        </Row>
        <Table
          rowKey={(record) => record.id}
          loading={loading}
          pagination={{ total, showSizeChanger: false, onChange: pagination }}
          dataSource={agentList}
          style={{ marginTop: '20px' }}
        >
          <Table.Column<User> title="姓名" dataIndex="nickName" key="nickName" />
          <Table.Column<User> title="手机号" dataIndex="phoneNumber" key="phoneNumber" />
          <Table.Column<User>
            title="地区"
            dataIndex="region"
            key="region"
            render={(region) => <span>{region || '未知地区'}</span>}
          />
          <Table.Column<User>
            title="认证角色"
            dataIndex="authRoles"
            key="authRoles"
            render={(authRoles) => (
              <>
                {authRoles.map((item: Record<string, any>) => {
                  return <span key={item.id}>{item.roleLabel}</span>;
                })}
              </>
            )}
          />
          <Table.Column<User> title="关注贴吧板块" dataIndex="followBarNum" key="followBarNum" />
          <Table.Column<User> title="发帖数" dataIndex="postsNum" key="postsNum" />
          <Table.Column<User> title="发帖数" dataIndex="postsNum" key="postsNum" />
          <Table.Column<User>
            title="账号状态"
            dataIndex="state"
            key="state"
            render={(text) => <Tag color="blue"> {text === 1 ? '正常' : '禁用中'} </Tag>}
          />
          <Table.Column<User> title="日期" dataIndex="createTime" key="stcreateTimeate" />
          <Table.Column<User>
            key="action"
            title="操作"
            render={(text, record, index) => (
              <Space>
                <a onClick={() => openModal(text)}>查看</a>
                <a onClick={() => StopOrOpenAgent(text, index)}>
                  {text.state === 1 ? '禁用' : '启用'}
                </a>
                {/* <Dropdown overlay={menu}>
                                  <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                                      更多 <DownOutlined />
                                  </a>
                            </Dropdown> */}
              </Space>
            )}
          />
        </Table>
      </Card>
      {/* 详情弹窗 */}
      {visible ? <DetailModal visible={visible} closeModal={closeModal} id={id} /> : null}
    </PageContainer>
  );
};

export default Agent;
