import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Alert, Drawer, Form, Input, message, Modal } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  getExaCustomerList,
  getExaCustomer,
  createExaCustomer,
  updateExaCustomer,
  deleteExaCustomer,
  type Customer,
} from '@/services/kratos/customer';
import { formatDate } from '@/utils/format';
import './index.less';

/**
 * 客户管理示例页面
 */
const CustomerPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<Customer[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editType, setEditType] = useState<'create' | 'update'>('create');

  // 获取表格数据
  const getTableData = async () => {
    setLoading(true);
    try {
      const res = await getExaCustomerList({ page, pageSize });
      if (res.code === 0) {
        setTableData(res.data?.list || []);
        setTotal(res.data?.total || 0);
      }
    } catch (error) {
      console.error('获取客户列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getTableData();
  }, [page, pageSize]);

  // 打开新增抽屉
  const openDrawer = () => {
    setEditType('create');
    form.resetFields();
    setDrawerVisible(true);
  };

  // 编辑客户
  const handleEdit = async (record: Customer) => {
    try {
      const res = await getExaCustomer({ ID: record.ID! });
      if (res.code === 0) {
        setEditType('update');
        form.setFieldsValue(res.data?.customer);
        setDrawerVisible(true);
      }
    } catch (error) {
      message.error('获取客户信息失败');
    }
  };

  // 删除客户
  const handleDelete = (record: Customer) => {
    Modal.confirm({
      title: '提示',
      content: '确定要删除吗?',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await deleteExaCustomer({ ID: record.ID! });
          if (res.code === 0) {
            message.success('删除成功');
            // 如果当前页只有一条数据且不是第一页，则回到上一页
            if (tableData.length === 1 && page > 1) {
              setPage(page - 1);
            } else {
              getTableData();
            }
          }
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 关闭抽屉
  const closeDrawer = () => {
    setDrawerVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      let res;
      if (editType === 'create') {
        res = await createExaCustomer(values);
      } else {
        res = await updateExaCustomer(values);
      }
      if (res.code === 0) {
        message.success(editType === 'create' ? '创建成功' : '更新成功');
        closeDrawer();
        getTableData();
      }
    } catch (error) {
      console.error('提交失败:', error);
    }
  };

  // 表格列定义
  const columns: ColumnsType<Customer> = [
    {
      title: '接入日期',
      dataIndex: 'CreatedAt',
      key: 'CreatedAt',
      width: 180,
      render: (text) => formatDate(text),
    },
    {
      title: '姓名',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 120,
    },
    {
      title: '电话',
      dataIndex: 'customerPhoneData',
      key: 'customerPhoneData',
      width: 120,
    },
    {
      title: '接入人ID',
      dataIndex: 'sysUserID',
      key: 'sysUserID',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            变更
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="customer-container">
      <Alert
        message="在资源权限中将此角色的资源权限清空 或者不包含创建者的角色 即可屏蔽此客户资源的显示"
        type="warning"
        showIcon
        className="customer-alert"
      />

      <Card className="customer-table-card">
        <div className="table-toolbar">
          <Button type="primary" icon={<PlusOutlined />} onClick={openDrawer}>
            新增
          </Button>
        </div>

        <Table
          rowKey="ID"
          columns={columns}
          dataSource={tableData}
          loading={loading}
          pagination={{
            current: page,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ['10', '30', '50', '100'],
            onChange: (p, ps) => {
              setPage(p);
              setPageSize(ps);
            },
          }}
        />
      </Card>

      {/* 新增/编辑抽屉 */}
      <Drawer
        title="客户"
        open={drawerVisible}
        onClose={closeDrawer}
        width={400}
        extra={
          <Space>
            <Button onClick={closeDrawer}>取消</Button>
            <Button type="primary" onClick={handleSubmit}>
              确定
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item name="ID" hidden>
            <Input />
          </Form.Item>
          <Form.Item
            name="customerName"
            label="客户名"
            rules={[{ required: true, message: '请输入客户名' }]}
          >
            <Input placeholder="请输入客户名" />
          </Form.Item>
          <Form.Item
            name="customerPhoneData"
            label="客户电话"
            rules={[{ required: true, message: '请输入客户电话' }]}
          >
            <Input placeholder="请输入客户电话" />
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default CustomerPage;
