import useUrlState from "@ahooksjs/use-url-state";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, message, Modal, Space, Tag } 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 BackIcon from "zy-react-library/components/Icon/BackIcon";
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 DictionarySelectTree from "zy-react-library/components/SelectTree/Dictionary";
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 ElectronicFenceModal from "~/components/ElectronicFenceModal";
import { NS_ENCLOSED_AREA } from "~/enumerate/namespace";

function DetailList(props) {
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [electronicFenceModalVisible, setElectronicFenceModalVisible] = useState(false);
  const [currentId, setCurrentId] = useState("");
  const [currentInfo, setCurrentInfo] = useState({});

  const query = useGetUrlQuery();
  const [urlState, setUrlState] = useUrlState({
    parentId: 0,
    parentName: "",
    backParentIds: [],
    backParentNames: [],
  }, {
    navigateMode: "replace",
    parseOptions: {
      arrayFormat: "index",
    },
    stringifyOptions: {
      arrayFormat: "index",
    },
  });

  const [form] = Search.useForm();

  const { tableProps, getData } = useTable(props["enclosedAreaDetailList"], {
    form,
    params: { parentId: urlState.parentId, closedArea: query.hgAuthArea },
    manual: true,
  });

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

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

  const onUpdateElectronicFence = async (id) => {
    const { data } = await props["enclosedAreaDetailInfo"]({ id });
    setCurrentInfo(data);
    setElectronicFenceModalVisible(true);
  };

  const onSaveElectronicFence = async (value) => {
    const { success } = await props["enclosedAreaDetailUpdate"]({ id: currentId, ...currentInfo, location: value });
    if (success) {
      message.success("保存成功");
      setElectronicFenceModalVisible(false);
      setCurrentId("");
      getData();
    }
  };

  return (
    <Page headerTitle="查看">
      <Search
        options={[
          { name: "closedAreaName", label: "区域名称" },
        ]}
        form={form}
        onFinish={getData}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {props.entrance !== "enterprise" && (
              <Button
                type="primary"
                icon={(<AddIcon />)}
                onClick={() => {
                  setAddModalVisible(true);
                }}
              >
                新增区域
              </Button>
            )}
            {
              urlState.parentId !== 0 && (
                <Button
                  icon={<BackIcon />}
                  onClick={() => {
                    setUrlState({
                      parentId: urlState.backParentIds.at(-1),
                      parentName: urlState.backParentNames.at(-1),
                      backParentIds: urlState.backParentIds.slice(0, -1),
                      backParentNames: urlState.backParentNames.slice(0, -1),
                      closedAreaType: urlState.backParentIds.at(-1) === "0" ? undefined : urlState.closedAreaType,
                      closedAreaTypeName: urlState.backParentIds.at(-1) === "0" ? undefined : urlState.closedAreaTypeName,
                      jurisdictionalCorpId: urlState.backParentIds.at(-1) === "0" ? undefined : urlState.jurisdictionalCorpId,
                      jurisdictionalCorpName: urlState.backParentIds.at(-1) === "0" ? undefined : urlState.jurisdictionalCorpName,
                    });
                  }}
                  // ghost
                >
                  返回
                </Button>
              )
            }
          </Space>
        )}
        columns={[
          {
            title: "区域名称",
            dataIndex: "closedAreaName",
            render: (_, record) => (
              <Button
                type="link"
                onClick={() => {
                  setUrlState({
                    parentId: record.id,
                    parentName: record.closedAreaName,
                    backParentIds: [...urlState.backParentIds, urlState.parentId],
                    backParentNames: [...urlState.backParentNames, urlState.parentName],
                    closedAreaType: record.closedAreaType,
                    closedAreaTypeName: record.closedAreaTypeName,
                    jurisdictionalCorpId: record.jurisdictionalCorpId,
                    jurisdictionalCorpName: record.jurisdictionalCorpName,
                  });
                }}
              >
                {record.closedAreaName}
              </Button>
            ),
          },
          { title: "管辖公司", dataIndex: "jurisdictionalCorpName" },
          { title: "区域类型", dataIndex: "closedAreaTypeName" },
          {
            title: "操作",
            width: 200,
            fixed: "right",
            render: (_, record) => (
              <Space>
                {props.entrance !== "enterprise" && (
                  <Button
                    type="link"
                    onClick={() => {
                      setCurrentId(record.id);
                      setAddModalVisible(true);
                    }}
                  >
                    修改
                  </Button>
                )}
                <Button
                  type="link"
                  // hidden={true}
                  onClick={() => {
                    onUpdateElectronicFence(record.id);
                  }}
                >
                  电子围栏
                </Button>
                {props.entrance !== "enterprise" && (
                  <Button
                    type="link"
                    danger
                    onClick={() => {
                      onDelete(record.id);
                    }}
                  >
                    删除
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        addModalVisible && (
          <AddModal
            id={currentId}
            urlState={urlState}
            query={query}
            onCancel={() => {
              setAddModalVisible(false);
              setCurrentId("");
            }}
            getData={getData}
          />
        )
      }
      {
        electronicFenceModalVisible && (
          <ElectronicFenceModal
            confirmLoading={props.enclosedArea.enclosedAreaLoading}
            onCancel={() => {
              setElectronicFenceModalVisible(false);
              setCurrentId("");
            }}
            onOk={onSaveElectronicFence}
            disabled={props.entrance === "enterprise"}
            position={currentInfo.location}
          />
        )
      }
    </Page>
  );
}

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

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

  useEffect(() => {
    if (props.id) {
      getData();
    }
    else {
      form.setFieldValue("closedAreaType", props.urlState.closedAreaType);
      form.setFieldValue("closedAreaTypeName", props.urlState.closedAreaTypeName);
      form.setFieldValue("jurisdictionalCorpId", props.urlState.jurisdictionalCorpId);
      form.setFieldValue("jurisdictionalCorpName", props.urlState.jurisdictionalCorpName);
    }
  }, []);

  const onSubmit = async (values) => {
    const { success } = await props[props.id ? "enclosedAreaDetailUpdate" : "enclosedAreaDetailAdd"]({
      ...values,
      id: props.id,
      parentId: props.urlState.parentId,
      hgAuthArea: props.query.hgAuthArea,
      hgAuthAreaName: props.query.hgAuthAreaName,
    });
    if (success) {
      message.success("操作成功");
      props.onCancel();
      props.getData();
    }
  };

  return (
    <Modal
      open
      title={props.id ? "修改" : "新增"}
      maskClosable={false}
      onCancel={props.onCancel}
      onOk={form.submit}
      confirmLoading={props.enclosedArea.enclosedAreaLoading}
      width={600}
    >
      <FormBuilder
        onFinish={onSubmit}
        showActionButtons={false}
        span={24}
        labelCol={{ span: 10 }}
        loading={props.enclosedArea.enclosedAreaLoading}
        options={[
          {
            name: "parentName",
            label: "上级区域名称",
            required: false,
            render: <Tag color="blue">{props.urlState.parentName || "无"}</Tag>,
          },
          { name: "closedAreaName", label: "区域名称" },
          {
            name: "closedAreaType",
            label: "区域类型",
            render: (
              <DictionarySelectTree
                disabled={props.urlState.closedAreaType}
                dictValue="ENCLOSED_AREA_TYPE"
                onGetLabel={label => form.setFieldValue("closedAreaTypeName", label)}
              />
            ),
          },
          { name: "closedAreaTypeName", label: "区域类型名称", onlyForLabel: true },
          {
            name: "jurisdictionalCorpId",
            label: "管辖公司",
            render: (
              <DepartmentSelectTree
                searchType="inType"
                params={{ enterpriseType: [2] }}
                disabled={props.urlState.jurisdictionalCorpId}
                onGetLabel={label => form.setFieldValue("jurisdictionalCorpName", label)}
              />
            ),
          },
          { name: "jurisdictionalCorpName", label: "管辖公司名称", onlyForLabel: true },
        ]}
        form={form}
      />
    </Modal>
  );
};

const AddModal = Connect([NS_ENCLOSED_AREA], true)(AddModalComponent);

export default Connect([NS_ENCLOSED_AREA], true)(DetailList);
