import { MagnifyingGlassIcon } from "@heroicons/react/24/outline";
import { Button, DatePicker, Form, Input, Modal, Select } from "antd";
import { useCallback, useEffect, useState, useRef } from "react";
import _ from "lodash";
import { useMainContext } from "../layout/MainProvider";
import DeviceTable from "./devicetable/page";
import DeviceModal from "./devicemodal/page";
import React from "react";
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  ImportOutlined,
  ExportOutlined,
  UpOutlined,
  DownOutlined,
} from "@ant-design/icons";
import DepartmentSelect from "@web/src/components/models/department/department-select";

import SystemTypeSelect from "@web/src/app/main/devicepage/select/System-select";
import DeviceTypeSelect from "@web/src/app/main/devicepage/select/Device-select";
import dayjs from "dayjs";
// 添加筛选条件类型
type SearchCondition = {
  deletedAt: null;
  systemType?: string;
  deviceType?: string;
  deptId?: string;
  responsiblePerson?: { contains: string };
  createdAt?: {
    gte: string;
    lte: string;
  }
};

export default function DeviceMessage() {
  const {
    form,
    formValue,
    setFormValue,
    setVisible,
    setSearchValue,
    editingRecord,
  } = useMainContext();
  // 控制展开/收起状态
  const [expanded, setExpanded] = useState(false);
  // 添加所有筛选条件的状态
  const [selectedSystem, setSelectedSystem] = useState<string | null>(null);
  const [selectedDeviceType, setSelectedDeviceType] = useState<string[] | null>(
    null
  );
  const [selectedDept, setSelectedDept] = useState<string | null>(null)
  const [time, setTime] = useState<string>("");
  const [ipAddress, setIpAddress] = useState<string>("");
  const [macAddress, setMacAddress] = useState<string>("");
  const [serialNumber, setSerialNumber] = useState<string>("");
  const [assetNumber, setAssetNumber] = useState<string>("");
  const [manufacturer, setManufacturer] = useState<string>("");
  const [model, setModel] = useState<string>("");
  const [location, setLocation] = useState<string>("");
  const [status, setStatus] = useState<string | null>(null);
  const [selectedSystemTypeId, setSelectedSystemTypeId] = useState<string>("");

  // 创建ref以访问DeviceTable内部方法
  const tableRef = useRef(null);
  // 存储选中行的状态
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [selectedData, setSelectedData] = useState<any[]>([]);

  const handleNew = () => {
    form.setFieldsValue(formValue);
    console.log(editingRecord);
    setVisible(true);
  };

  // 查询按钮点击处理
  const handleSearch = () => {
    // 构建查询条件
    const whereCondition: SearchCondition = {
      deletedAt: null,
      ...(selectedSystem && { systemType: selectedSystem }),
      ...(selectedDeviceType && { deviceType: selectedDeviceType }),
      ...(selectedDept && { deptId: selectedDept }),
      ...(time && {
        createdAt: {
          gte: dayjs(time).startOf('day').toISOString(),
          lte: dayjs(time).endOf('day').toISOString()
        }
      }),

      // ...(status && { status: { contains: status } }),
    };

    // 更新查询条件到全局上下文
    setSearchValue(whereCondition as any);

    // 也可以直接使用refetch方法进行刷新，确保查询条件生效
    // 如果DeviceTable组件暴露了refetch方法，可以通过ref调用
  };

  // 重置按钮处理
  const handleReset = () => {
    setSelectedSystem(null);
    setSelectedDeviceType(null);
    setSelectedDept(null);
    setTime("");
    setIpAddress("");
    setMacAddress("");
    setSerialNumber("");
    setAssetNumber("");
    setManufacturer("");
    setModel("");
    setLocation("");

    // 重置为只查询未删除的记录
    setSearchValue({ deletedAt: null } as any);
  };

  // 修复DepartmentSelect的onChange类型
  const handleDeptChange = (value: string | string[]) => {
    setSelectedDept(value as string);
  };

  // 处理选择变更的回调
  const handleSelectedChange = (keys: React.Key[], data: any[]) => {
    console.log("选中状态变化:", keys.length);
    setSelectedKeys(keys);
    setSelectedData(data);
  };

  // 处理导出按钮点击
  const handleExport = () => {
    if (tableRef.current) {
      tableRef.current.handleExportSelected();
    }
  };

  // 系统类别变化处理
  const handleSystemTypeChange = (value: string) => {
    setSelectedSystemTypeId(value);
    form.setFieldValue('deviceType', undefined); // 清空已选故障类型
  };

  return (
    <div className="p-2 min-h-screen bg-gradient-to-br">
      <div className="pl-4 pr-4 pt-2 text-2xl flex items-center justify-between">
        <span>故障收录检索</span>
        <div className="flex space-x-2">
          <Button type="primary" icon={<PlusOutlined />} onClick={handleNew}>
            新建
          </Button>

        </div>
      </div>
      <Form>
        <div className="p-2 h-full flex">
          <div className="max-w-full mx-auto flex-1 flex flex-col">
            {/* 搜索区域 - 分为左右两块布局 */}
            <div className="mb-2">
              <div className="flex w-full">
                {/* 左侧搜索框区域 */}
                <div className="flex-1 flex flex-col space-y-3">
                  {/* 第一行搜索框 - 始终显示 */}
                  <div className="flex w-full space-x-3">
                    <SystemTypeSelect
                      value={selectedSystem}
                      onChange={setSelectedSystem}
                      className="w-1/5"
                    />
                    <DeviceTypeSelect
                      value={selectedDeviceType}
                      onChange={setSelectedDeviceType}
                      className="w-1/5"
                      systemTypeId={selectedSystemTypeId}
                    />
                    <DepartmentSelect
                      placeholder="单位"
                      className="w-1/5"
                      value={selectedDept}
                      onChange={handleDeptChange}
                    />
                    {/* <Select
                        placeholder="状态"
                        className="w-1/5"
                        options={[
                          { label: "正常", value: "normal" },
                          { label: "故障", value: "fault" },
                          { label: "维修", value: "repair" },
                        ]}
                        value={status}
                        onChange={setStatus}  
                        allowClear
                      /> */}
                    <DatePicker
                      placeholder="选择日期"
                      className="w-1/5"
                      value={time ? dayjs(time) : null}
                      onChange={(date, dateString) => setTime(dateString as string)}
                      format="YYYY-MM-DD"
                      allowClear
                    />
                  </div>
                </div>

                {/* 右侧按钮区域 */}
                <div className="flex flex-row justify-between ml-4 space-x-2">
                  <Button
                    type="primary"
                    icon={<SearchOutlined />}
                    onClick={handleSearch}
                  >
                    查询
                  </Button>
                  <Button icon={<ReloadOutlined />} onClick={handleReset}>
                    重置
                  </Button>
                </div>
              </div>
            </div>

            <div className="flex-1 overflow-auto justify-between">
              <DeviceTable
                ref={tableRef}
                onSelectedChange={handleSelectedChange}
              ></DeviceTable>
              <DeviceModal></DeviceModal>
            </div>
          </div>
        </div>
      </Form>
    </div>
  );
}
