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 BasicSelectTree from "zy-react-library/components/SelectTree/Basic";
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_ENCLOSED_AREA, NS_FIRST_LEVEL_DOOR_INFO } from "~/enumerate/namespace";
import DepartmentSelectTree from "zy-react-library/components/SelectTree/Department/Gwj";

const mkmjLevel = 2;

function List(props) {
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [viewModalVisible, setViewModalVisible] = useState(false);

  const [currentId, setCurrentId] = useState("");

  const [form] = Search.useForm();
  const { tableProps, getData } = useTable(props["firstLevelDoorInfoList"], {
    form,
    params: {
      mkmjLevel,
    },
  });

  const onUpdateStatus = (record) => {
    if (record.mkmjStatus === 2 && (record.videoNum > 0 || record.passageNum > 0))
      return message.warning("正在使用中的口门不能停用");

    const msg = record.mkmjStatus === 2 ? "停用" : "开启";
    Modal.confirm({
      title: `${msg}确认`,
      content: `确定要${msg}吗？`,
      onOk: async () => {
        const { success } = await props["firstLevelDoorInfoEditStatus"]({ id: record.id, mkmjStatus: record.mkmjStatus === 2 ? 1 : 2 });
        if (success) {
          message.success(`${msg}成功`);
          getData();
        }
      },
    });
  };

  return (
    <Page isShowAllAction={false}>
      <Search
        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" /> },
        ]}
        form={form}
        onFinish={getData}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {(props.entrance !== "enterprise" && props.permission(props.addBtn || "jgd-enclosed-door-add")) && (
              <Button
                type="primary"
                icon={(<AddIcon />)}
                onClick={() => {
                  setAddModalVisible(true);
                }}
              >
                新增
              </Button>
            )}
          </Space>
        )}
        columns={[
          { title: "所属区域", dataIndex: "hgAuthAreaName" },
          { title: "口门类型", dataIndex: "mkmjTypeName" },
          { title: "管辖公司", dataIndex: "jurisdictionalCorpName" },
          { title: "口门名称", dataIndex: "mkmjName" },
          {
            title: "口门位置",
            dataIndex: "location",
            render: (_, record) => `${record.latitude || ""}--${record.longitude || ""}`,
          },
          { title: "摄像头个数", dataIndex: "videoCount", render: (_, record) => record.videoNum || 0 },
          {
            title: "口门状态",
            dataIndex: "mkmjStatus",
            render: (_, record) => getLabelName({ list: AREA_STATUS_ENUM, status: record.mkmjStatus }),
          },
          {
            title: "操作",
            width: 300,
            fixed: "right",
            render: (_, record) => (
              <Space>
                {props.permission(props.viewBtn || "jgd-enclosed-door-show") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setCurrentId(record.id);
                      setViewModalVisible(true);
                    }}
                  >
                    查看
                  </Button>
                )}
                {(props.entrance !== "enterprise" && props.permission(props.editBtn || "jgd-enclosed-door-edit")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      setCurrentId(record.id);
                      setAddModalVisible(true);
                    }}
                  >
                    编辑
                  </Button>
                )}
                {(props.entrance !== "enterprise" && props.permission(props.updateStatusBtn || "jgd-enclosed-door-updstate")) && (
                  <Button
                    type="link"
                    onClick={() => {
                      onUpdateStatus(record);
                    }}
                  >
                    {record.mkmjStatus === 2 ? "停用" : "开启"}
                  </Button>
                )}
                {props.permission(props.addChannelBtn || "jgd-enclosed-door-add-td") && (
                  <Button
                    type="link"
                    onClick={() => {
                      props.history.push(`./channel/list?id=${record.id}`);
                    }}
                  >
                    {props.entrance !== "enterprise" ? "添加通道" : "查看通道"}
                  </Button>
                )}
                {props.permission(props.addCameraBtn || "jgd-enclosed-door-add-vedio") && (
                  <Button
                    type="link"
                    onClick={() => {
                      props.history.push(`./camera/list?id=${record.id}`);
                    }}
                  >
                    {props.entrance !== "enterprise" ? "添加摄像头" : "查看摄像头"}
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        addModalVisible && (
          <AddModal
            id={currentId}
            onClose={() => {
              setAddModalVisible(false);
              setCurrentId("");
            }}
            getData={getData}
          />
        )
      }
      {
        viewModalVisible && (
          <ViewModal
            id={currentId}
            onClose={() => {
              setViewModalVisible(false);
              setCurrentId("");
            }}
          />
        )
      }
    </Page>
  );
}

const AddModalComponent = (props) => {
  const [closedAreaListTree, setClosedAreaListTree] = useState([]);
  const [directionAreaListTree, setDirectionAreaListTree] = useState([]);

  const [form] = FormBuilder.useForm();
  const hgAuthArea = FormBuilder.useWatch("hgAuthArea", form);
  const mkmjAreaJurisdictionalCorpId = FormBuilder.useWatch("mkmjAreaJurisdictionalCorpId", form);

  const getDirectionAreaList = async () => {
    const { data } = await props["enclosedAreaDetailListTree"]({ hgAuthArea });
    setDirectionAreaListTree(data);
  };

  const getClosedAreaList = async () => {
    const { data } = await props["enclosedAreaDetailListTree"]({ jurisdictionalCorpId:mkmjAreaJurisdictionalCorpId });
    setClosedAreaListTree(data);
  };

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

  useEffect(() => {
    props.id && getData();
  }, []);

  useEffect(() => {
    if (hgAuthArea)
      getDirectionAreaList();
    else setDirectionAreaListTree([]);
  }, [hgAuthArea]);

  useEffect(() => {
    if (mkmjAreaJurisdictionalCorpId)
      getClosedAreaList();
    else setClosedAreaListTree([]);
  }, [mkmjAreaJurisdictionalCorpId]);

  const onSubmit = async (values) => {
    if (
      Number(values.outDirectionType) === 2
      && values.outDirectionArea
      && values.closedAreaId
      && String(values.outDirectionArea) === String(values.closedAreaId)
    ) {
      message.warning("口门离开区域不能和封闭区域重复");
      return;
    }

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

  return (
    <Modal
      open
      title={props.id ? "编辑" : "添加"}
      maskClosable={false}
      width={800}
      onCancel={props.onClose}
      onOk={form.submit}
      confirmLoading={props.firstLevelDoorInfo.firstLevelDoorInfoLoading}
    >
      <FormBuilder
        onFinish={onSubmit}
        showActionButtons={false}
        loading={props.firstLevelDoorInfo.firstLevelDoorInfoLoading}
        labelCol={{ span: 8 }}
        span={24}
        options={[
          {
            name: "hgAuthArea",
            label: "所属区域",
            render: (
              <DictionarySelect
                dictValue="HG_AUTH_AREA"
                onGetLabel={label => {
                  form.setFieldValue("hgAuthAreaName", label)
                  form.setFieldValue("inDirectionArea", undefined);
                  form.setFieldValue("outDirectionArea", undefined);

                }}
              />
            ),
          },
          { name: "hgAuthAreaName", label: "所属区域名称", onlyForLabel: true },
          {
            name: "mkmjAreaJurisdictionalCorpId",
            label: "管辖公司",
            render: (
              <DepartmentSelectTree
                searchType="inType"
                level={1}
                params={{ enterpriseType: [2] }}
                onChange={() => {
                  form.setFieldValue("closedAreaId", undefined);
                  form.setFieldValue("closedAreaName", "");
                }}
                onGetLabel={label => form.setFieldValue("mkmjAreaJurisdictionalCorpName", label)}
              />
            ),
            formItemProps: { preserve: true },
          },
          { name: "mkmjAreaJurisdictionalCorpName", label: "区域管辖单位名称", onlyForLabel: true },
          {
            name: "closedAreaId",
            label: "封闭区域",
            render: (
              <BasicSelectTree
                treeData={closedAreaListTree}
                placeholder="封闭区域"
                onGetLabel={label => form.setFieldValue("closedAreaName", label)}
                nameKey="closedAreaName"
              />
            ),
          },
          { name: "closedAreaName", 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: "口门位置" },
          { customizeRender: true, span: 24, render: <Map type="cesium" /> },
          { name: "mkmjStatus", label: "口门状态", render: FORM_ITEM_RENDER_ENUM.SELECT, items: AREA_STATUS_ENUM },
          {
            name: "inDirectionArea",
            label: "口门进入区域",
            render: (
              <BasicSelectTree
                treeData={directionAreaListTree}
                placeholder="口门进入区域"
                onGetLabel={label => form.setFieldValue("inDirectionAreaName", label)}
                nameKey="closedAreaName"
              />
            ),
          },
          { name: "inDirectionAreaName", label: "口门进入区域名称", onlyForLabel: true },
          {
            name: "outDirectionType",
            label: "口门离开区域",
            span: 12,
            render: FORM_ITEM_RENDER_ENUM.RADIO,
            items: [{ bianma: 1, name: "离场" }, { bianma: 2, name: "进入其他区域" }],
            componentProps: {
              onChange: () => {
                form.setFieldValue("outDirectionAreaName", "");
              },
            },
          },
          {
            name: "outDirectionArea",
            label: "",
            span: 12,
            wrapperCol: { span: 24 },
            dependencies: ["outDirectionType"],
            hidden: formValues => !(formValues.outDirectionType === 2),
            render: (
              <BasicSelectTree
                treeData={directionAreaListTree}
                placeholder="口门离开区域"
                onGetLabel={label => form.setFieldValue("outDirectionAreaName", label)}
                nameKey="closedAreaName"
              />
            ),
          },
          { name: "outDirectionAreaName", label: "口门离开区域名称", onlyForLabel: true },
        ]}
        form={form}
      />
    </Modal>
  );
};

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

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

  useEffect(() => {
    props.id && getData();
  }, []);

  return (
    <Modal
      open
      title="查看"
      maskClosable={false}
      width={800}
      onCancel={props.onClose}
      footer={[
        <Button key="cancel" onClick={props.onClose}>取消</Button>,
      ]}
      loading={props.firstLevelDoorInfo.firstLevelDoorInfoLoading}
    >
      <Descriptions
        column={1}
        bordered
        styles={{ label: { width: 200 } }}
        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: (
              <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
                <span>{info.longitude}</span>
                <span>{info.latitude}</span>
                <LocationIcon onClick={() => {
                  setMapVisible(true);
                }}
                />
              </div>
            ),
          },
          { label: "口门进入区域", children: info.inDirectionAreaName },
          { label: "口门离开区域", children: info.outDirectionType === 1 ? "离场" : `进入其他区域（${info.outDirectionAreaName}）` },
        ]}
      />

      <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, NS_ENCLOSED_AREA], true)(AddModalComponent);
const ViewModal = Connect([NS_FIRST_LEVEL_DOOR_INFO], true)(ViewModalComponent);

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