import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Descriptions, message, Modal, Space } from "antd";
import { useEffect, useState } from "react";
import FormBuilder from "zy-react-library/components/FormBuilder";
import AddIcon from "zy-react-library/components/Icon/AddIcon";
import VideoIcon from "zy-react-library/components/Icon/VideoIcon";
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 useGetUrlQuery from "zy-react-library/hooks/useGetUrlQuery";
import useTable from "zy-react-library/hooks/useTable";
import { getLabelName } from "zy-react-library/utils";
import { NS_FIRST_LEVEL_DOOR_INFO } from "~/enumerate/namespace";
import VideoPlayModal from "./components/VideoPlay";
import { FORM_ITEM_RENDER_ENUM } from "zy-react-library/enum/formItemRender";
const IS_ONLINE_ENUM = [
  { name: "否", bianma: "0" },
  { name: "是", bianma: "1" },
];

function List(props) {
  const [list, setList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [currentId, setCurrentId] = useState("");
  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [playModalVisible, setPlayModalVisible] = useState(false);
  const [videoModalData, setVideoModalData] = useState({});
  const [mapModalVisible, setMapModalVisible] = useState(false);
  const [location, setLocation] = useState({ longitude: "", latitude: "" });

  const query = useGetUrlQuery();
  const [form] = Search.useForm();
  const { tableProps, getData } = useTable(props["firstLevelDoorInfoCameraList"], {
    form,
    params: { eqForeignId: query.id, eqDeviceType: query.deviceType },
    onSuccess: async (data) => {
      const { data: fixedCameraList } = await props["firstLevelDoorInfoFixedCameraList"]({ pageIndex: 1, pageSize: "9999" });
      for (let i = 0; i < data.list.length; i++) {
        for (let j = 0; j < fixedCameraList.length; j++) {
          if (data.list[i].videoResourceId === fixedCameraList[j].id) {
            data.list[i].isOnline = fixedCameraList[j].isOnline;
            break;
          }
        }
      }
      setList(data.list);
    },
  });

  const onDelete = (id) => {
    Modal.confirm({
      title: "删除确认",
      content: "确定要删除吗？",
      onOk: async () => {
        const { success } = await props["firstLevelDoorInfoCameraDelete"]({ id });
        if (success) {
          message.success("删除成功");
          getData();
        }
      },
    });
  };

  const onGetPlayUrl = async (videoResourceId) => {
    const { data } = await props["firstLevelDoorInfoFixedCameraInfo"]({ id: videoResourceId });
    setPlayModalVisible(true);
    setVideoModalData(data);
  };

  const onSavePosition = async (longitude, latitude) => {
    const { data } = await props["firstLevelDoorInfoCameraInfo"]({ id: currentId });
    const { success } = await props["firstLevelDoorInfoCameraEdit"]({
      ...data,
      longitude,
      latitude,
    });
    if (success) {
      message.success("保存成功");
      getData();
      setCurrentId("");
      setLocation({ longitude: "", latitude: "" });
    }
  };

  return (
    <Page headerTitle="摄像头">
      <Search
        form={form}
        onFinish={getData}
        options={[
          { name: "videoResourceName", label: "视频名称" },
          { name: "eqIsOnline", label: "是否在线", render:FORM_ITEM_RENDER_ENUM.SELECT,items:IS_ONLINE_ENUM },

        ]}
      />
      <Table
        rowSelection={{
          selectedRowKeys,
          preserveSelectedRowKeys: true,
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectedRowKeys(selectedRowKeys);
            setSelectedRows(selectedRows);
          },
        }}
        toolBarRender={() => (
          <Space>
            {props.entrance !== "enterprise" && (
              <Button
                type="primary"
                icon={<AddIcon />}
                onClick={() => {
                  setAddModalVisible(true);
                }}
              >
                新增
              </Button>
            )}
            <Button
              type="primary"
              icon={<VideoIcon />}
              ghost
              onClick={() => {
                if (selectedRowKeys.length === 0) {
                  message.error("请选择要播放的视频");
                  return;
                }
                const videoResourceData = selectedRows.map((row) => {
                  return {
                    videoName: row.videoResourceName,
                    id: row.videoResourceId,
                    cameraNumber: row.videoResourceCode,
                    isOnline: row.isOnline,
                  };
                });
                props.history.push(`./batchPlay?videoResourceData=${JSON.stringify(videoResourceData)}`);
              }}
            >
              播放全部
            </Button>
          </Space>
        )}
        columns={[
          { dataIndex: "videoResourceName", title: "视频名称" },
          {
            dataIndex: "longitude",
            title: "视频定位状态",
            width: 120,
            render: (text, record) => (record.longitude && record.latitude ? "已定位" : "未定位"),
          },
          {
            dataIndex: "isOnline",
            title: "是否在线",
            width: 100,
            render: (_, record) => getLabelName({ list: IS_ONLINE_ENUM, status: record.isOnline }),
          },
          {
            title: "操作",
            width: 230,
            render: (_, record) => (
              <Space>
                <Button
                  type="link"
                  onClick={() => {
                    setInfoModalVisible(true);
                    setCurrentId(record.id);
                  }}
                >
                  查看
                </Button>
                {props.entrance !== "enterprise" && (
                  <Button
                    type="link"
                    onClick={() => {
                      setAddModalVisible(true);
                      setCurrentId(record.id);
                    }}
                  >
                    编辑
                  </Button>
                )}
                {props.entrance !== "enterprise" && (
                  <Button
                    type="link"
                    onClick={() => {
                      setMapModalVisible(true);
                      setLocation({ longitude: record.longitude, latitude: record.latitude });
                      setCurrentId(record.id);
                    }}
                  >
                    定位
                  </Button>
                )}
                {props.entrance !== "enterprise" && (
                  <Button
                    type="link"
                    danger
                    onClick={() => {
                      onDelete(record.id);
                    }}
                  >
                    删除
                  </Button>
                )}
                <Button
                  type="link"
                  onClick={() => {
                    if (record.isOnline === 1) {
                      onGetPlayUrl(record.videoResourceId);
                    }
                    else {
                      message.error("视频资源离线");
                    }
                  }}
                >
                  播放
                </Button>
              </Space>
            ),
          },
        ]}
        {...tableProps}
        dataSource={list}
      />
      {
        addModalVisible && (
          <AddModal
            onCancel={() => {
              setAddModalVisible(false);
              setCurrentId("");
            }}
            id={currentId}
            getData={getData}
            query={query}
          />
        )
      }
      {
        infoModalVisible && (
          <InfoModal
            onCancel={() => {
              setInfoModalVisible(false);
              setCurrentId("");
            }}
            id={currentId}
          />
        )
      }
      {
        playModalVisible && (
          <VideoPlayModal
            videoName={videoModalData.videoName}
            videoAddress={videoModalData.videoAddress}
            cameraNumber={videoModalData.cameraNumber}
            getPlayUrl={props["firstLevelDoorInfoFixedCameraGetPlayUrl"]}
            playSourceType="hikvision"
            onClose={() => {
              setPlayModalVisible(false);
              setVideoModalData({});
            }}
          />
        )
      }
      {mapModalVisible && (
        <MapSelector
          visible={mapModalVisible}
          onClose={() => setMapModalVisible(false)}
          longitude={location.longitude}
          latitude={location.latitude}
          type="cesium"
          onConfirm={(longitude, latitude) => {
            onSavePosition(longitude, latitude);
          }}
        />
      )}
    </Page>
  );
}

const AddModalComponent = (props) => {
  const [selectFixedCameraModalVisible, setSelectFixedCameraModalVisible] = useState(false);
  const [form] = FormBuilder.useForm();

  const getData = async () => {
    const { data } = await props["firstLevelDoorInfoCameraInfo"]({ id: props.id });
    form.setFieldsValue({
      ...data,
    });
  };
  useEffect(() => {
    props.id && getData();
  }, []);

  const onSubmit = async (values) => {
    const { success } = await props[!props.id ? "firstLevelDoorInfoCameraAdd" : "firstLevelDoorInfoCameraEdit"]({
      ...values,
      id: props.id,
      foreignId: props.query.id,
      deviceType: props.query.deviceType,
      videoType: 2,
    });
    if (success) {
      props.onCancel();
      props.getData();
    }
  };

  return (
    <Modal
      open
      onCancel={props.onCancel}
      onOk={form.submit}
      title={props.id ? "编辑" : "新增"}
      maskClosable={false}
      confirmLoading={props.firstLevelDoorInfo.firstLevelDoorInfoCameraLoading}
      width={600}
    >
      <FormBuilder
        labelCol={{ span: 10 }}
        form={form}
        loading={props.firstLevelDoorInfo.firstLevelDoorInfoCameraLoading}
        span={24}
        onFinish={onSubmit}
        showActionButtons={false}
        options={[
          {
            label: "视频选择",
            required: false,
            render: (
              <Button
                type="primary"
                onClick={() => {
                  setSelectFixedCameraModalVisible(true);
                }}
              >
                选择
              </Button>
            ),
          },
          { name: "videoResourceName", label: "视频名称", componentProps: { disabled: true } },
          { name: "videoResourceId", label: "视频ID", onlyForLabel: true },
          { name: "videoResourceCode", label: "摄像头编号", componentProps: { disabled: true } },
        ]}
      />
      {
        selectFixedCameraModalVisible && (
          <SelectFixedCameraModal
            onCancel={() => {
              setSelectFixedCameraModalVisible(false);
            }}
            onSubmit={(values) => {
              form.setFieldValue("videoResourceName", values.videoName);
              form.setFieldValue("videoResourceId", values.id);
              form.setFieldValue("videoResourceCode", values.cameraNumber);
            }}
          />
        )
      }
    </Modal>
  );
};

const SelectFixedCameraModalComponent = (props) => {
  const [form] = FormBuilder.useForm();
  const { tableProps, getData } = useTable(props["firstLevelDoorInfoFixedCameraList"], {
    form,
    useStorageQueryCriteria: false,
  });

  return (
    <Modal
      open
      onCancel={props.onCancel}
      title="选择固定摄像头"
      maskClosable={false}
      width={1200}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      <Search
        form={form}
        onFinish={getData}
        options={[
          { name: "videoName", label: "视频名称" },
        ]}
      />
      <Table
        options={false}
        disabledResizer={true}
        columns={[
          { dataIndex: "videoName", title: "视频名称" },
          { dataIndex: "corpinfoName", title: "所属单位" },
          {
            title: "操作",
            width: 120,
            render: (_, record) => (
              <Space>
                <Button
                  type="link"
                  onClick={() => {
                    props.onSubmit(record);
                    props.onCancel();
                  }}
                >
                  选择
                </Button>
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
    </Modal>
  );
};

const InfoModalComponent = (props) => {
  const [info, setInfo] = useState({});

  const getData = async () => {
    const { data } = await props["firstLevelDoorInfoCameraInfo"]({ id: props.id });
    setInfo(data);
  };
  useEffect(() => {
    props.id && getData();
  }, []);

  return (
    <Modal
      open
      onCancel={props.onCancel}
      title="查看"
      maskClosable={false}
      loading={props.firstLevelDoorInfo.firstLevelDoorInfoCameraLoading}
      width={600}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
    >
      <Descriptions
        column={1}
        bordered
        styles={{ label: { width: 200 } }}
        items={[
          { label: "视频名称", children: info.videoResourceName },
          { label: "摄像头编号", children: info.videoResourceCode },
        ]}
      />
    </Modal>
  );
};

const AddModal = Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(AddModalComponent);
const SelectFixedCameraModal = Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(SelectFixedCameraModalComponent);
const InfoModal = Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(InfoModalComponent);

export default Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(List);
