import React, { useEffect, useState } from 'react';
import { Button, Input, Select, Table, Pagination, Tag, Typography } from 'antd';
import { LockOutlined, SearchOutlined } from '@ant-design/icons';
import { getOAuthAccountList, getOpenTypeAll } from '../api';
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const { Text } = Typography;

const AdminOAuthList: React.FC = () => {
  const [tableData, setTableData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [searchAccountId, setSearchAccountId] = useState('');
  const [searchUserId, setSearchUserId] = useState('');
  const [openTypeMap, setOpenTypeMap] = useState<Record<number, string>>({});
  const [openTypeOptions, setOpenTypeOptions] = useState<{ value: number; label: string }[]>([]);
  const [searchOpenType, setSearchOpenType] = useState<number | undefined>(undefined);

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 60,
      render: (text: number) => <span style={{ color: '#64748b' }}>{text}</span>,
    },
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '前台用户ID',
      dataIndex: 'userId',
      key: 'userId',
    },
    {
      title: '前台用户手机号',
      dataIndex: 'userPhone',
      key: 'userPhone',
    },
    {
      title: '授权应用ID',
      dataIndex: 'appid',
      key: 'appid',
    },
    {
      title: '授权绑定账户ID',
      dataIndex: 'accountId',
      key: 'accountId',
    },
    {
      title: '授权绑定账户名称',
      dataIndex: 'accountName',
      key: 'accountName',
    },
    {
      title: '授权绑定账户角色',
      dataIndex: 'accountRole',
      key: 'accountRole',
      render: (role: string) => {
        const roleMap: Record<string, string> = {
          ADVERTISER: '客户',
          CUSTOMER_ADMIN: '普通版工作台-管理员',
          CUSTOMER_OPERATOR: '普通版工作台-协作者',
          AGENT: '代理商',
          CHILD_AGENT: '二级代理商',
          PLATFORM_ROLE_STAR: '星图账户',
          PLATFORM_ROLE_SHOP_ACCOUNT: '抖音店铺账户',
          PLATFORM_ROLE_QIANCHUAN_AGENT: '千川代理商',
          PLATFORM_ROLE_STAR_AGENT: '星图代理商',
          PLATFORM_ROLE_AWEME: '抖音号',
          PLATFORM_ROLE_STAR_MCN: '星图MCN机构',
          PLATFORM_ROLE_STAR_ISV: '星图服务商',
          AGENT_SYSTEM_ACCOUNT: '代理商系统账户',
          PLATFORM_ROLE_LOCAL_AGENT: '本地推代理商',
          PLATFORM_ROLE_YUNTU_BRAND_ISV_ADMIN: '云图品牌服务商管理员',
          PLATFORM_ROLE_LIFE: '抖音来客账户',
          PLATFORM_ROLE_ENTERPRISE_BP_ADMIN: '升级版工作台管理员',
          PLATFORM_ROLE_ENTERPRISE_BP_OPERATOR: '升级版工作台协作者',
        };
        return roleMap[role] || role;
      },
    },
    {
      title: '授权登录账户用户ID',
      dataIndex: 'accountUserid',
      key: 'accountUserid',
    },
    {
      title: '授权登录账户用户名',
      dataIndex: 'accountUsername',
      key: 'accountUsername',
    },
    {
      title: '开户方式',
      dataIndex: 'openType',
      key: 'openType',
      width: 120,
      render: (text: number) => <span style={{ color: '#1e293b' }}>{openTypeMap[text] || text}</span>,
    },
    {
      title: '平台端口',
      dataIndex: 'portType',
      key: 'portType',
      render: (role: string) => {
        const roleMap: Record<string, string> = {
          1: '巨量',
          2: '磁力',
          3: '巨量星图',
          4: '服务单',
          5: '腾讯',
        };
        return roleMap[role] || role;
      },
      // 1=巨量，2=磁力，3=巨量星图，4=服务单，5=腾讯
      // render: (text: number) => <span style={{ color: '#1e293b' }}>{text}</span>,
    },
    {
      title: '授权刷新Token',
      dataIndex: 'refreshToken',
      key: 'refreshToken',
    },
    {
      title: '刷新Token过期时间',
      dataIndex: 'refreshTokenExpired',
      key: 'refreshTokenExpired',
      render: (text: string) => <span style={{ color: '#64748b' }}>{formatDateTime(text)}</span>,
    },
    {
      title: '授权Token',
      dataIndex: 'accessToken',
      key: 'accessToken',
    },
    {
      title: 'Token过期时间',
      dataIndex: 'accessTokenExpired',
      key: 'accessTokenExpired',
      render: (text: string) => <span style={{ color: '#64748b' }}>{formatDateTime(text)}</span>,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (text: string) => <span style={{ color: '#64748b' }}>{formatDateTime(text)}</span>,
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (text: string) => <span style={{ color: '#64748b' }}>{formatDateTime(text)}</span>,
    },
  ];
  const loadOpenTypeList = async () => {
    try {
      const res = await getOpenTypeAll();
      const data = res.data || [];
      const map: Record<number, string> = {};
      const options: { value: number; label: string }[] = [];
      data.forEach(item => {
        map[item.openType] = item.typeName;
        options.push({ value: item.openType, label: item.typeName });
      });
      setOpenTypeMap(map);
      setOpenTypeOptions(options);
    } catch (error) {
      console.error('加载开户方式列表失败:', error);
    }
  };
  const loadOAuthList = async () => {
    setLoading(true);
    try {
      const res = await getOAuthAccountList({
        account_id: searchAccountId || undefined,
        account_userid: searchUserId || undefined,
        open_type: searchOpenType,
        page: currentPage,
        page_size: pageSize,
      });
      const data = res.data || [];
      const tableData = data.map((item: any, index: number) => ({
        ...item,
        index: (currentPage - 1) * pageSize + index + 1,
      }));
      setTableData(tableData);
      setTotal(res.pagination?.total || 0);
    } catch (error) {
      console.error('加载数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadOpenTypeList();
    loadOAuthList();
  }, [currentPage, pageSize]);

  const handleSearch = () => {
    setCurrentPage(1);
    loadOAuthList();
  };

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <LockOutlined style={{ color: '#6366f1', fontSize: 16 }} />
        <Text strong style={{ fontSize: 16 }}>投放平台授权列表</Text>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <Input
            placeholder="授权绑定账户ID"
            value={searchAccountId}
            onChange={(e) => setSearchAccountId(e.target.value)}
            style={{ width: 180 }}
            allowClear
            prefix={<SearchOutlined />}
            onPressEnter={handleSearch}
          />
          <Input
            placeholder="授权登录账户用户ID"
            value={searchUserId}
            onChange={(e) => setSearchUserId(e.target.value)}
            style={{ width: 180 }}
            allowClear
            prefix={<SearchOutlined />}
            onPressEnter={handleSearch}
          />
          <Select
            placeholder="开户方式"
            value={searchOpenType}
            onChange={(value) => setSearchOpenType(value)}
            style={{ width: 140 }}
            allowClear
            options={openTypeOptions}
          />
          <Button
            type="primary"
            onClick={handleSearch}
          >
            搜索
          </Button>
        </div>
      </div>
      <div style={{ background: '#fff', borderRadius: 12, boxShadow: '0 1px 3px rgba(0,0,0,0.05)' }}>
        <Table
          dataSource={tableData}
          columns={columns}
          loading={loading}
          rowKey="id"
          bordered={false}
          scroll={{ x: 'max-content' }}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            showSizeChanger: true,
            showTotal: (t) => `共 ${t} 条记录`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size);
            }
          }}
        />
      </div>
    </div>
  );
};

export default AdminOAuthList;