import React, { useEffect, useState } from "react";
import http from '@src/http';
import { Button, Table, Input, message, ConfigProvider } from "antd";
import zhCN from 'antd/locale/zh_CN';
import { UserAddOutlined } from '@ant-design/icons'
import ChatRoomConfig from '../dialog/config'
import QrCodeModal from '../dialog/qrcode'
import { wechatUserInfoPage, qwQuiteQwLogin } from '@src/http/api';
import type { TableProps, TablePaginationConfig } from 'antd';

interface DataType {
  id: number;
  uuid: string;
  vid: string;
  name: string;
  avatar: string;
  phone: string;
  corpId: number;
  corpName: string;
  unionId: string;
  loginStatus: number;
}

interface PaginationParams {
  currentPage: number;
  pageSize: number;
  phone?: string;
}

interface WechatUserResponse {
  currentPage: number;
  totalSize: number;
  pageSize: number;
  objs: DataType[];
  totalPage: number;
  nextPage: number;
  prePage: number;
  curPageFirstRecNum: number;
  curPageLastRecNum: number;
  offset: number;
}

const Gzh: React.FC = () => {
  const [loading, setLoading] = useState(false)
  const [tableData, setTableData] = useState<DataType[]>([])
  const [pagination, setPagination] = useState<{
    current: number;
    pageSize: number;
    total: number;
  }>({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  const [searchPhone, setSearchPhone] = useState<string>('')
  const [configVisible, setConfigVisible] = useState(false)
  const [currentUuid, setCurrentUuid] = useState('')
  const [qrModalVisible, setQrModalVisible] = useState(false)
  const [qrModalTitle, setQrModalTitle] = useState('')
  const [currentVid, setCurrentVid] = useState<string | undefined>(undefined)

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '企微实名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '企微主体',
      dataIndex: 'corpName',
      key: 'corpName',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '账号状态',
      dataIndex: 'loginStatus',
      key: 'loginStatus',
      render: (status) => {
        const statusMap: Record<number, string> = {
          0: '离线',
          1: '在线',
          2: '注销'
        }
        return <span style={{
          color: status === 1 ? '#52c41a' : status === 0 ? '#f5222d' : '#999999'
        }}>{statusMap[status]}</span>
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          {record.loginStatus === 0 && <a onClick={() => handleLogin(record.vid)}>登录</a>}
          {record.loginStatus === 1 && <>
            <a onClick={() => handleLogout(record.uuid)}>登出</a>&emsp;
            <a onClick={() => handleConfigClick(record.uuid)}>配置</a>
          </>}
        </>
      ),
    }
  ]

  const fetchUserList = async (params: PaginationParams) => {
    try {
      setLoading(true)
      const res = await http.get<WechatUserResponse>(wechatUserInfoPage, { params })
      if (res.success) {
        setTableData(res.data.objs || [])
        setPagination({
          current: res.data.currentPage,
          pageSize: res.data.pageSize,
          total: res.data.totalSize
        })
      } else {
        message.error(res.msg || '获取用户列表失败')
      }
    } catch {
      message.error('获取用户列表失败')
    } finally {
      setLoading(false)
    }
  }

  const handleTableChange = (pagination: TablePaginationConfig) => {
    fetchUserList({
      currentPage: pagination.current as number,
      pageSize: pagination.pageSize as number,
      phone: searchPhone
    })
  }

  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }))
    fetchUserList({
      currentPage: 1,
      pageSize: pagination.pageSize,
      phone: searchPhone
    })
  }

  const handleConfigClick = (uuid: string) => {
    setCurrentUuid(uuid)
    setConfigVisible(true)
  }

  const handleConfigClose = () => {
    setConfigVisible(false)
  }

  const handleAddAccount = () => {
    setQrModalTitle('添加账号')
    setCurrentVid('') // 添加账号不需要 vid
    setQrModalVisible(true)
  }

  const handleLogin = (vid: string) => {
    setQrModalTitle('账号登录')
    setCurrentVid(vid) // 设置当前 vid
    setQrModalVisible(true)
  }

  const handleQrModalClose = () => {
    setQrModalVisible(false)
  }

  const handleLogout = async (uuid: string) => {
    try {
      setLoading(true)
      const res = await http.post(qwQuiteQwLogin, { uuid })
      if (res.success) {
        message.success('登出成功')
        // 刷新列表
        fetchUserList({
          currentPage: pagination.current,
          pageSize: pagination.pageSize,
          phone: searchPhone
        })
      } else {
        message.error(res.msg || '登出失败')
      }
    } catch {
      message.error('登出失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchUserList({
      currentPage: pagination.current,
      pageSize: pagination.pageSize
    })
  }, [])

  return (
    <>
      <div className={"text-[20px] font-medium mb-[10px]"}>
        账号管理
      </div>
      <div className={"flex mb-[10px]"}>
        <div className={"flex-1 flex gap-[10px]"}>
          <Input
            className={"!w-[200px]"}
            allowClear
            placeholder="请输入手机号"
            value={searchPhone}
            onChange={(e) => {
              const value = e.target.value.replace(/[^\d]/g, '');
              setSearchPhone(value);
            }}
            onPressEnter={handleSearch}
            maxLength={11}
          />
          <Button type="primary" onClick={handleSearch}>搜索</Button>
        </div>
        <div>
          <Button type="primary" className={"mr-[10px]"} onClick={handleAddAccount}><UserAddOutlined />添加账号</Button>
        </div>
      </div>
      <ConfigProvider locale={zhCN}>
        <Table 
          columns={columns}
          dataSource={tableData}
          rowKey="uuid"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
          onChange={handleTableChange}
        />
      </ConfigProvider>

      <ChatRoomConfig 
        visible={configVisible} 
        onClose={handleConfigClose} 
        uuid={currentUuid} 
      />

      <QrCodeModal
        visible={qrModalVisible}
        onClose={handleQrModalClose}
        title={qrModalTitle}
        vid={currentVid}
        onSuccess={(data) => {
          // 获取二维码成功后的回调，可以在这里处理后续逻辑
          console.log('获取二维码成功:', data);
        }}
        onLoginSuccess={() => {
          // 登录成功后刷新列表
          fetchUserList({
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            phone: searchPhone
          });
        }}
      />
    </>
  )
}

export default Gzh;
