import { Button, Form, message, Modal, Space, Switch } from "antd";
import { useEffect, useState } from "react";
import AddIcon from "zy-react-library/components/Icon/AddIcon";
import MapSelector from "zy-react-library/components/Map/MapSelector";
import Page from "zy-react-library/components/Page";
import Search from "zy-react-library/components/Search";
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, SENSOR_STATUS_OPTIONS, YES_NO_OPTIONS } from "~/enumerate/constant";
import SensorDeviceAdd from "../Add";
import PositionModal from "../components/PositionModal";
import RealtimeModal from "../components/RealtimeModal";
import ThresholdModal from "../components/ThresholdModal";
import SensorDeviceView from "../View";

function SensorDeviceList(props) {
  const [form] = Form.useForm();
  const [modalOpen, setModalOpen] = useState(false);
  const [viewOpen, setViewOpen] = useState(false);
  const [positionOpen, setPositionOpen] = useState(false);
  const [thresholdOpen, setThresholdOpen] = useState(false);
  const [realtimeOpen, setRealtimeOpen] = useState(false);
  const [currentId, setCurrentId] = useState("");
  const [currentRecord, setCurrentRecord] = useState({});
  const [sensorTypeOptions, setSensorTypeOptions] = useState([]);
  const { tableProps, getData } = useTable(props["sensorDeviceList"], { form });
  const [visible, setVisible] = useState(false);
  const [selectedLng, setSelectedLng] = useState("");
  const [selectedLat, setSelectedLat] = useState("");
  const [rowData, setRowData] = useState({});

  const loadSensorTypeOptions = async () => {
    const res = await props["sensorTypeList"]({
      pageIndex: 1,
      pageSize: 500,
      status: 1,
    });
    if (res?.success) {
      setSensorTypeOptions(res.data || []);
    }
  };
  const handleOpen = (row) => {
    setSelectedLng(row.longitude);
    setSelectedLat(row.latitude);
    setRowData(row);
    setVisible(true);
  };
  const handleConfirm = (lng, lat, extra) => {
    rowData.latitude = lat;
    rowData.longitude = lng;
    props["sensorDeviceEdit"](rowData).then((res) => {
      if (res?.success) {
        message.success("定位成功！");
      }
    });
  };
  useEffect(() => {
    loadSensorTypeOptions();
  }, []);

  const sensorTypeSelectOptions = sensorTypeOptions.map(item => ({
    bianma: item.id,
    name: item.typeName,
  }));

  const handleDelete = (record) => {
    Modal.confirm({
      title: "确定删除这条传感器设备吗？",
      maskClosable: false,
      onOk: async () => {
        const res = await props["sensorDeviceRemove"]({ id: record.id });
        if (res?.success) {
          message.success("删除成功");
          getData();
        }
      },
    });
  };

  const handleAlarmSwitch = async (record, checked) => {
    const res = await props["sensorDeviceEdit"]({ id: record.id, alarmSwitch: checked ? 1 : 0 });
    if (res?.success) {
      message.success("报警开关更新成功");
      getData();
    }
  };

  return (
    <Page isShowAllAction={false}>
      <Search
        form={form}
        onFinish={getData}
        options={[
          { name: "sensorName", label: "传感器名称" },
          {
            name: "thresholdFlag",
            label: "是否阈值设定",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: YES_NO_OPTIONS,
          },
          {
            name: "sensorStatus",
            label: "传感器状态",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: SENSOR_STATUS_OPTIONS,
          },
          {
            name: "sensorTypeId",
            label: "传感器类型",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: sensorTypeSelectOptions,
          },
        ]}
      />
      <Table
        rowKey="id"
        toolBarRender={() => (
          <Space>
            {props.permission("cgqsbgl-add") && (
              <Button
                type="primary"
                icon={<AddIcon />}
                onClick={() => {
                  setCurrentId("");
                  setModalOpen(true);
                }}
              >
                新增
              </Button>
            )}
          </Space>
        )}
        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: "sensorStatus",
            render: (_, record) => getLabelName({ status: record.sensorStatus, list: SENSOR_STATUS_OPTIONS }) || "-",
          },
          {
            title: "是否定位",
            dataIndex: "positioningFlag",
            render: (_, record) => record.latitude ? "是" : "否",
          },
          {
            title: "报警开关",
            dataIndex: "alarmSwitch",
            render: (_, record) => (
              <Switch
                checked={record.alarmSwitch === 1}
                checkedChildren="开"
                unCheckedChildren="关"
                // disabled={!props.permission(editPermission)}
                onChange={checked => handleAlarmSwitch(record, checked)}
              />
            ),
          },
          {
            title: "是否通过系统设定报警",
            ellipsis: false,
            dataIndex: "thresholdFlag",
            render: (_, record) => getLabelName({ status: record.thresholdFlag, list: YES_NO_OPTIONS }) || "-",
          },
          {
            title: "操作",
            width: 320,
            render: (_, record) => (
              <Space>
                {
                  props.permission("cgqsbgl-info")

                  && (
                    <Button
                      type="link"
                      onClick={() => {
                        setCurrentRecord(record);
                        setViewOpen(true);
                      }}
                    >
                      查看
                    </Button>
                  )
                }
                {props.permission("cgqsbgl-edit") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setCurrentId(record.id);
                      setModalOpen(true);
                    }}
                  >
                    编辑
                  </Button>
                )}

                {props.permission("cgqsbgl-del") && (
                  <Button danger type="link" onClick={() => handleDelete(record)}>
                    删除
                  </Button>
                )}
                {
                  props.permission("cgqsbgl-locate")

                  && (
                    <Button
                      type="link"
                      onClick={() => handleOpen(record)}
                    >
                      定位
                    </Button>
                  )
                }
                {
                  props.permission("cgqsbgl-sssj")

                  && (
                    <Button
                      type="link"
                      onClick={() => {
                        setCurrentRecord(record);
                        setRealtimeOpen(true);
                      }}
                    >
                      实时数据
                    </Button>
                  )
                }
                {props.permission("cgqsbgl-yzsd") && record.sensorAttr === "NUMBER" && record.thresholdFlag === 1 && (
                  <Button
                    type="link"
                    onClick={() => {
                      setCurrentId(record.id);
                      setCurrentRecord(record);
                      setThresholdOpen(true);
                    }}
                  >
                    阈值设定
                  </Button>
                )}

              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {modalOpen && (
        <SensorDeviceAdd
          open={modalOpen}
          currentId={currentId}
          loading={props.sensorDeviceLoading}
          getData={getData}
          sensorTypeOptions={sensorTypeOptions}
          sensorDeviceInfo={props.sensorDeviceInfo}
          sensorDeviceSave={props.sensorDeviceSave}
          sensorDeviceEdit={props.sensorDeviceEdit}
          onCancel={() => {
            setModalOpen(false);
            setCurrentId("");
          }}
        />
      )}
      {thresholdOpen && (
        <ThresholdModal
          open={thresholdOpen}
          currentId={currentId}
          record={currentRecord}
          loading={props.sensorDeviceLoading}
          getData={getData}
          sensorDeviceInfo={props.sensorDeviceInfo}
          sensorDeviceEdit={props.sensorDeviceEdit}
          onCancel={() => {
            setThresholdOpen(false);
            setCurrentId("");
            setCurrentRecord({});
          }}
        />
      )}
      {viewOpen && (
        <SensorDeviceView
          open={viewOpen}
          record={currentRecord}
          onCancel={() => {
            setViewOpen(false);
            setCurrentRecord({});
          }}
        />
      )}
      {positionOpen && (
        <PositionModal
          open={positionOpen}
          record={currentRecord}
          onCancel={() => {
            setPositionOpen(false);
            setCurrentRecord({});
          }}
        />
      )}
      {realtimeOpen && (
        <RealtimeModal
          open={realtimeOpen}
          record={currentRecord}
          sensorDeviceList={props["sensorDevicelistBySensorDevice"]}
          sensorDeviceLineChart={props["sensorDeviceLineChart"]}
          onCancel={() => {
            setRealtimeOpen(false);
            setCurrentRecord({});
          }}
        />
      )}
      {
        visible
        && (
          <MapSelector

            visible={visible}
            latitude={selectedLat}
            longitude={selectedLng}
            onClose={() => setVisible(false)}
            onConfirm={handleConfirm}
          />
        )
      }

    </Page>
  );
}

export default SensorDeviceList;
