import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
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 LocationIcon from "zy-react-library/components/Icon/LocationIcon";
import Map from "zy-react-library/components/Map";
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 DictionarySelect from "zy-react-library/components/Select/Dictionary";
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 { AREA_STATUS_ENUM } from "~/enumerate/constant";
import { NS_FIRST_LEVEL_DOOR_INFO } from "~/enumerate/namespace";

const mkmjLevel = 1;

function List(props) {
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [infoModalVisible, setInfoModalVisible] = useState(false);
  const [currentId, setCurrentId] = useState("");
  const [form] = Search.useForm();
  const { tableProps, getData } = useTable(props["firstLevelDoorInfoList"], {
    form,
    params: { mkmjLevel },
  });

  const onDelete = (record) => {
    if (record.videoCount > 0 || record.passageCount > 0)
      return message.warning("正在使用中的口门不能删除");

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

  return (
    <Page isShowAllAction={false}>
      <Search
        form={form}
        onFinish={getData}
        options={[
          { name: "likeMkmjName", label: "口门名称" },
          { name: "mkmjStatus", label: "口门状态", render: FORM_ITEM_RENDER_ENUM.SELECT, items: AREA_STATUS_ENUM },
          { name: "mkmjType", label: "口门类型", render: <DictionarySelect dictValue="HGKM_MKMJ_TYPE" /> },
          { name: "hgAuthArea", label: "所属区域", render: <DictionarySelect dictValue="HG_AUTH_AREA" /> },
        ]}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {props.permission("jgd-first-level-door-info-add") && (
              <Button
                type="primary"
                icon={<AddIcon />}
                onClick={() => setAddModalVisible(true)}
              >
                新增
              </Button>
            )}
          </Space>
        )}
        columns={[
          { dataIndex: "hgAuthAreaName", title: "所属区域" },
          { dataIndex: "mkmjTypeName", title: "口门类型", width: 120 },
          { dataIndex: "mkmjName", title: "口门名称" },
          {
            dataIndex: "location",
            title: "口门位置",
            render: (_, record) => `${record.longitude || ""}--${record.latitude || ""}`,
          },
          { dataIndex: "videoCount", title: "视频个数", width: 120 },
          {
            dataIndex: "mkmjStatus",
            title: "口门状态",
            width: 120,
            render: (_, record) => getLabelName({ list: AREA_STATUS_ENUM, status: record.mkmjStatus }),
          },
          {
            title: "操作",
            width: 300,
            render: (_, record) => (
              <Space>
                {props.permission("jgd-first-level-door-info-show") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setCurrentId(record.id);
                      setInfoModalVisible(true);
                    }}
                  >
                    查看
                  </Button>
                )}
                {props.permission("jgd-first-level-door-info-edit") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setCurrentId(record.id);
                      setAddModalVisible(true);
                    }}
                  >
                    编辑
                  </Button>
                )}
                {props.permission("jgd-first-level-door-info-del") && (
                  <Button
                    type="link"
                    danger
                    onClick={() => {
                      onDelete(record);
                    }}
                  >
                    删除
                  </Button>
                )}
                {props.permission("jgd-first-level-door-info-add-channel") && (
                  <Button
                    type="link"
                    onClick={() => {
                      props.history.push(`./channel/list?id=${record.id}`);
                    }}
                  >
                    添加通道
                  </Button>
                )}
                {props.permission("jgd-first-level-door-info-add-camera") && (
                  <Button
                    type="link"
                    onClick={() => {
                      props.history.push(`./camera/list?id=${record.id}&deviceType=1`);
                    }}
                  >
                    添加摄像头
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {addModalVisible && (
        <AddModal
          id={currentId}
          onCancel={() => {
            setAddModalVisible(false);
            setCurrentId("");
          }}
          getData={getData}
        />
      )}

      {infoModalVisible && (
        <InfoModal
          id={currentId}
          onCancel={() => {
            setInfoModalVisible(false);
            setCurrentId("");
          }}
          getData={getData}
        />
      )}
    </Page>
  );
}

function AddModalComponent(props) {
  const [form] = FormBuilder.useForm();

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

  const onSubmit = async (values) => {
    const { success } = await props[!props.id ? "firstLevelDoorInfoAdd" : "firstLevelDoorInfoEdit"]({
      ...values,
      mkmjLevel,
      id: props.id,
    });
    if (success) {
      message.success("操作成功");
      props.onCancel();
      props.getData();
    }
  };

  return (
    <Modal
      open
      onCancel={props.onCancel}
      onOk={form.submit}
      title={props.id ? "编辑" : "新增"}
      maskClosable={false}
      confirmLoading={props.firstLevelDoorInfo.firstLevelDoorInfoLoading}
      width={800}
    >
      <FormBuilder
        labelCol={{ span: 6 }}
        form={form}
        loading={props.firstLevelDoorInfo.firstLevelDoorInfoLoading}
        span={24}
        onFinish={onSubmit}
        showActionButtons={false}
        options={[
          {
            name: "hgAuthArea",
            label: "所属区域",
            render: (
              <DictionarySelect
                dictValue="HG_AUTH_AREA"
                onGetLabel={label => form.setFieldValue("hgAuthAreaName", label)}
              />
            ),
          },
          { name: "hgAuthAreaName", label: "所属区域名称", onlyForLabel: true },
          {
            name: "mkmjName",
            label: "口门名称",
            rules: [{
              validator: async (_, value) => {
                if (value) {
                  const { data } = await props["firstLevelDoorInfoCheckName"]({ mkmjName: value, id: props.id });
                  return data.available ? Promise.resolve() : Promise.reject(new Error("口门名称已存在"));
                }
                else {
                  Promise.resolve();
                }
              },
              validateTrigger: "onBlur",
            }],
            formItemProps: { validateTrigger: ["onChange", "onBlur"] },
          },
          {
            name: "mkmjType",
            label: "口门类型",
            render: (
              <DictionarySelect
                dictValue="HGKM_MKMJ_TYPE"
                onGetLabel={label => form.setFieldValue("mkmjTypeName", label)}
              />
            ),
          },
          { name: "mkmjTypeName", label: "口门类型名称", onlyForLabel: true },
          { name: "remarks", label: "口门位置" },
          { key: "map", customizeRender: true, render: <Map type="cesium" /> },
          { name: "mkmjStatus", label: "口门状态", render: FORM_ITEM_RENDER_ENUM.SELECT, items: AREA_STATUS_ENUM },
        ]}
      />
    </Modal>
  );
}

function InfoModalComponent(props) {
  const [info, setInfo] = useState({});
  const [mapVisible, setMapVisible] = useState(false);

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

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

  return (
    <Modal
      open
      onCancel={props.onCancel}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>关闭</Button>,
      ]}
      maskClosable={false}
      title="查看"
      loading={props.firstLevelDoorInfo.firstLevelDoorInfoLoading}
      width={600}
    >
      <Descriptions
        styles={{ label: { width: 200 } }}
        column={1}
        bordered
        items={[
          { label: "所属区域", children: info.hgAuthAreaName },
          { label: "口门名称", children: info.mkmjName },
          { label: "口门类型", children: info.mkmjTypeName },
          { label: "口门位置", children: info.remarks },
          { label: "口门状态", children: getLabelName({ list: AREA_STATUS_ENUM, status: info.mkmjStatus }) },
          {
            label: "位置",
            children: (
              <Button type="text"  style={{ display: "flex", alignItems: "center", gap: "8px" }} onClick={() => {
                setMapVisible(true);
              }}>
                <span>{info.longitude}</span>
                <span>--</span>
                <span>{info.latitude}</span>

              </Button>
            ),
          },
        ]}
      />

      <MapSelector
        visible={mapVisible}
        onClose={() => setMapVisible(false)}
        longitude={info.longitude}
        latitude={info.latitude}
        disable={true}
        type="cesium"
      />
    </Modal>
  );
}

const AddModal = Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(AddModalComponent);
const InfoModal = Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(InfoModalComponent);
export default Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(Permission(List));
