import { Button, Descriptions, Divider, Form, Modal, Space } from "antd";
import { useEffect, useState } from "react";
import Page from "zy-react-library/components/Page";
import Search from "zy-react-library/components/Search";
import DepartmentSelectTree from "zy-react-library/components/SelectTree/Department/Gwj";
import Table from "zy-react-library/components/Table";
import { FORM_ITEM_RENDER_ENUM } from "zy-react-library/enum/formItemRender";
import useTable from "zy-react-library/hooks/useTable";
import { getLabelName } from "zy-react-library/utils";
import { SENSOR_ATTR_OPTIONS } from "~/enumerate/constant";
import BindSensorModal from "./components/BindSensorModal";
import ManagerModal from "./components/ManagerModal";

function DeviceRegionList(props) {
  const [form] = Form.useForm();
  const [managerOpen, setManagerOpen] = useState(false);
  const [bindOpen, setBindOpen] = useState(false);
  const [viewOpen, setViewOpen] = useState(false);
  const [viewLoading, setViewLoading] = useState(false);
  const [currentId, setCurrentId] = useState("");
  const [viewRecord, setViewRecord] = useState(null);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [fireRegionOptions, setFireRegionOptions] = useState([]);

  const { tableProps, getData } = useTable(props.deviceRegionList, { form });

  const pageType = props.type || "fgs";
  const editPermission = `${pageType}-iotalarm-device-region-edit`;

  const loadFireRegionOptions = async () => {
    const res = await props.deviceRegionFireRegionList();
    if (!res?.success) {
      return;
    }
    setFireRegionOptions(res.data || []);
  };

  useEffect(() => {
    loadFireRegionOptions();
  }, []);

  // const dataSource = useMemo(() => (tableProps.dataSource || []).map(item => ({
  //   ...item,
  //   departmentName: item.departmentName || "-",
  //   managerName: item.managerName || "-",
  //   bindSensorCount: item.bindSensorCount ?? 0,
  // })), [tableProps.dataSource]);

  const handleOpenManager = async (record) => {
    setCurrentRecord(record);
    setManagerOpen(true);
  };

  const handleOpenBind = async (record) => {
    setCurrentRecord(record);
    setBindOpen(true);
  };

  const handleOpenView = async (record) => {
    setViewLoading(true);
    try {
      const res = await props.deviceRegionInfo({ id: record.fireRegionId });
      setViewRecord({
        ...record,
        boundSensors: res?.data?.boundSensors || [],
      });
      setViewOpen(true);
    }
    finally {
      setViewLoading(false);
    }
  };

  return (
    <Page isShowAllAction={false}>
      <Search
        form={form}
        onFinish={getData}
        options={[
          {
            name: "fireRegionId",
            label: "消防区域",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: fireRegionOptions.map(item => ({
              bianma: item.id,
              name: item.fireRegionName,
            })),
          },
          {
            name: "departmentId",
            label: "负责部门",
            render: <DepartmentSelectTree />,
          },
        ]}
      />
      <Table
        rowKey={record => record.id || record.fireRegionId}
        loading={props.deviceRegionLoading}
        columns={[
          { title: "消防区域", dataIndex: "fireRegionName" },
          { title: "消防区域编码", dataIndex: "fireRegionCode" },
          { title: "负责部门", dataIndex: "departmentName" },
          { title: "负责人", dataIndex: "managerName" },
          { title: "关联传感器数", dataIndex: "bindSensorCount" },
          {
            title: "操作",
            width: 260,
            render: (_, record) => (
              <Space>
                {props.permission("sbqugl-glcgq") && (
                  <Button type="link" onClick={() => handleOpenBind(record)}>
                    关联传感器
                  </Button>
                )}
                {props.permission("sbqugl-szfer") && (
                  <Button type="link" onClick={() => handleOpenManager(record)}>
                    设置负责人
                  </Button>
                )}
                {
                  props.permission("sbqugl-info")

                  && (
                    <Button
                      type="link"
                      onClick={() => handleOpenView(record)}
                    >
                      查看
                    </Button>
                  )
                }
              </Space>
            ),
          },
        ]}
        {...tableProps}
        // dataSource={dataSource}
      />
      <Modal
        destroyOnClose
        open={viewOpen}
        title="查看"
        footer={null}
        maskClosable={false}
        onCancel={() => {
          setViewOpen(false);
          setViewRecord(null);
        }}
        width={1200}
      >
        <Divider orientation="left">区域信息</Divider>
        <Descriptions bordered column={2}>
          <Descriptions.Item label="消防区域">{viewRecord?.fireRegionName || "-"}</Descriptions.Item>
          <Descriptions.Item label="消防区域编码">{viewRecord?.fireRegionCode || "-"}</Descriptions.Item>
          <Descriptions.Item label="负责部门">{viewRecord?.departmentName || "-"}</Descriptions.Item>
          <Descriptions.Item label="负责人">{viewRecord?.managerName || "-"}</Descriptions.Item>
        </Descriptions>

        <Divider orientation="left">设备信息</Divider>

        <Table
          options={false}
          rowKey="id"
          loading={viewLoading}
          disabledResizer={true}
          pagination={false}
          dataSource={viewRecord?.boundSensors || []}
          columns={[

            { title: "传感器编码", dataIndex: "sensorCode" },
            { title: "传感器名称", dataIndex: "sensorName" },
            { title: "传感器类型", dataIndex: "sensorTypeName" },
            {
              title: "传感器属性",
              dataIndex: "sensorAttr",
              render: (_, record) => getLabelName({ status: record.sensorAttr, list: SENSOR_ATTR_OPTIONS }),
            },
            {
              title: "传感器状态",
              dataIndex: "sensorStatusName",
            },
            {
              title: "是否定位",
              dataIndex: "positioningFlag",
              render: (_, record) => record.latitude ? "是" : "否",
            },
          ]}
        />
      </Modal>
      {managerOpen && (
        <ManagerModal
          open={managerOpen}
          currentId={currentId}
          currentRecord={currentRecord}
          loading={props.deviceRegionLoading}
          getData={getData}
          deviceRegionInfo={props.deviceRegionInfo}
          deviceRegionManager={props.deviceRegionManager}
          onCancel={() => {
            setManagerOpen(false);
            setCurrentId("");
            setCurrentRecord({});
          }}
        />
      )}
      {bindOpen && (
        <BindSensorModal
          open={bindOpen}
          currentId={currentId}
          currentRecord={currentRecord}
          loading={props.deviceRegionLoading}
          getData={getData}
          deviceRegionInfo={props.deviceRegionInfo}
          deviceRegionBindSensor={props.deviceRegionBindSensor}
          deviceRegionUnbindSensor={props.deviceRegionUnbindSensor}
          sensorDeviceList={props.sensorDeviceList}
          onCancel={() => {
            setBindOpen(false);
            setCurrentId("");
            setCurrentRecord({});
          }}
        />
      )}
    </Page>
  );
}

export default DeviceRegionList;
