import React, { useState, useEffect } from 'react';
import { 
  Layout, Button, Table, Space,
  Form, Input, Select, message, Modal,
  Card, Row, Col, Typography,
  Popconfirm, Tag, DatePicker, Radio
} from 'antd';
import { 
  useQuery,
} from '@tanstack/react-query';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { EnableStatus } from '../share/types.ts'
import type { 
  ZichanInfo, ZichanTransLog, ZichanCategory, ZichanArea, 
} from '../share/monitorTypes.ts';
import {
  DeviceCategory, DeviceStatus, AssetTransferType, 
  AssetTransferTypeNameMap, AssetTransferTypeColorMap,
  DeviceStatusNameMap, DeviceStatusColorMap, DeviceCategoryNameMap
} from '../share/monitorTypes.ts';

import { ZichanAPI, ZichanCategoryAPI, ZichanAreaAPI, ZichanTransferAPI } from './api/index.ts';

import { getEnumOptions } from './utils.ts';

const { Title } = Typography;

// 资产管理页面组件
export const ZichanPage = () => {
  const [form] = Form.useForm();
  const [formMode, setFormMode] = useState<'create' | 'edit'>('create');
  const [editingId, setEditingId] = useState<number | null>(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    asset_name: '',
    device_category: undefined as DeviceCategory | undefined,
    device_status: undefined as DeviceStatus | undefined
  });
  
  // 设备分类选项
  const categoryOptions = getEnumOptions(DeviceCategory, DeviceCategoryNameMap);
  
  // 设备状态选项
  const statusOptions = getEnumOptions(DeviceStatus, DeviceStatusNameMap);
  
  // 查询资产列表
  const { 
    data: zichanResult = { data: [], pagination: { total: 0, current: 1, pageSize: 10 } }, 
    isLoading: isFetching,
    refetch
  } = useQuery({
    queryKey: ['zichan', searchParams],
    queryFn: () => ZichanAPI.getZichanList(searchParams),
    // staleTime: 5000, // 数据5秒内不会被认为是过期的
  });
  
  // 提取数据和分页信息
  const zichanList = zichanResult.data || [];
  const pagination = zichanResult.pagination || { total: 0, current: 1, pageSize: 10 };
  
  // 处理表单提交
  const handleSubmit = async (values: Partial<ZichanInfo>) => {
    try {
      setIsLoading(true);
      if (formMode === 'create') {
        await ZichanAPI.createZichan(values);
        message.success('资产创建成功');
      } else {
        if (editingId) {
          await ZichanAPI.updateZichan(editingId, values);
          message.success('资产更新成功');
        }
      }
      setModalVisible(false);
      refetch();
    } catch (error: any) {
      message.error(error.response?.data?.error || '操作失败');
    } finally {
      setIsLoading(false);
    }
  };
  
  // 处理编辑
  const handleEdit = async (id: number) => {
    try {
      setIsLoading(true);
      const data = await ZichanAPI.getZichan(id);
      form.setFieldsValue(data);
      setEditingId(id);
      setFormMode('edit');
      setModalVisible(true);
    } catch (error: any) {
      message.error(error.response?.data?.error || '获取资产详情失败');
    } finally {
      setIsLoading(false);
    }
  };
  
  // 处理删除
  const handleDelete = async (id: number) => {
    try {
      await ZichanAPI.deleteZichan(id);
      message.success('资产删除成功');
      refetch();
    } catch (error: any) {
      message.error(error.response?.data?.error || '删除资产失败');
    }
  };
  
  // 处理搜索
  const handleSearch = (values: any) => {
    setSearchParams({
      ...searchParams,
      page: 1, // 重置为第一页
      asset_name: values.asset_name,
      device_category: values.device_category,
      device_status: values.device_status
    });
  };
  
  // 处理页码变化
  const handlePageChange = (page: number, pageSize?: number) => {
    setSearchParams({
      ...searchParams,
      page,
      limit: pageSize || 10
    });
  };
  
  // 处理新增
  const handleAdd = () => {
    form.resetFields();
    setFormMode('create');
    setEditingId(null);
    setModalVisible(true);
  };
  
  // 表格列定义
  const columns = [
    { 
      title: '资产ID', 
      dataIndex: 'id', 
      key: 'id',
      width: 80
    },
    { 
      title: '资产名称', 
      dataIndex: 'asset_name', 
      key: 'asset_name' 
    },
    { 
      title: '设备分类', 
      dataIndex: 'device_category', 
      key: 'device_category',
      render: (category: DeviceCategory) => {
        return DeviceCategoryNameMap[category] || '未知分类';
      }
    },
    { 
      title: '品牌', 
      dataIndex: 'brand', 
      key: 'brand' 
    },
    { 
      title: '使用地址', 
      dataIndex: 'use_address', 
      key: 'use_address' 
    },
    { 
      title: '运行情况', 
      dataIndex: 'operation_status', 
      key: 'operation_status' 
    },
    { 
      title: '设备状态', 
      dataIndex: 'device_status', 
      key: 'device_status',
      render: (status: DeviceStatus) => {
        return <Tag color={DeviceStatusColorMap[status] || 'default'}>
          {DeviceStatusNameMap[status] || '未知状态'}
        </Tag>;
      }
    },
    { 
      title: 'IP地址', 
      dataIndex: 'ip_address', 
      key: 'ip_address' 
    },
    { 
      title: '创建时间', 
      dataIndex: 'created_at', 
      key: 'created_at',
      render: (date: string) => date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: ZichanInfo) => (
        <Space>
          <Button size="small" type="primary" onClick={() => handleEdit(record.id)}>编辑</Button>
          <Button size="small" danger onClick={() => 
            Modal.confirm({
              title: '确认删除',
              content: `确定要删除资产"${record.asset_name}"吗？`,
              onOk: () => handleDelete(record.id)
            })
          }>删除</Button>
        </Space>
      )
    }
  ];
  
  return (
    <div>
      <Title level={2}>资产管理</Title>
      <Card>
        <Form layout="inline" onFinish={handleSearch} style={{ marginBottom: 16 }}>
          <Form.Item name="asset_name" label="资产名称">
            <Input placeholder="请输入资产名称" allowClear />
          </Form.Item>
          <Form.Item name="device_category" label="设备分类">
            <Select
              placeholder="请选择设备分类"
              style={{ width: 140 }}
              allowClear
              options={categoryOptions}
            />
          </Form.Item>
          <Form.Item name="device_status" label="设备状态">
            <Select
              placeholder="请选择设备状态"
              style={{ width: 140 }}
              allowClear
              options={statusOptions}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">查询</Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleAdd}>添加资产</Button>
          </Form.Item>
        </Form>
        
        <Table
          columns={columns}
          dataSource={zichanList}
          rowKey="id"
          loading={isFetching}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: handlePageChange,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
        />
        
        <Modal
          title={formMode === 'create' ? '添加资产' : '编辑资产'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={null}
          width={800}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="asset_name"
                  label="资产名称"
                  rules={[{ required: true, message: '请输入资产名称' }]}
                >
                  <Input placeholder="请输入资产名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="device_category"
                  label="设备分类"
                  rules={[{ required: true, message: '请选择设备分类' }]}
                >
                  <Select
                    placeholder="请选择设备分类"
                    options={categoryOptions}
                  />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="brand"
                  label="品牌"
                >
                  <Input placeholder="请输入品牌" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="supplier"
                  label="供应商"
                >
                  <Input placeholder="请输入供应商" />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="use_address"
                  label="使用地址"
                >
                  <Input placeholder="请输入使用地址" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="device_status"
                  label="设备状态"
                >
                  <Select
                    placeholder="请选择设备状态"
                    options={statusOptions}
                  />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="ip_address"
                  label="IP地址"
                >
                  <Input placeholder="请输入IP地址" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="operation_status"
                  label="运行情况"
                >
                  <Input placeholder="请输入运行情况" />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item
                  name="cpu"
                  label="CPU信息"
                >
                  <Input placeholder="请输入CPU信息" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="memory"
                  label="内存信息"
                >
                  <Input placeholder="请输入内存信息" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="disk"
                  label="硬盘信息"
                >
                  <Input placeholder="请输入硬盘信息" />
                </Form.Item>
              </Col>
            </Row>
            
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" loading={isLoading}>
                  {formMode === 'create' ? '创建' : '保存'}
                </Button>
                <Button onClick={() => setModalVisible(false)}>取消</Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};