import { Permission } from "@cqsjjb/jjb-common-decorator/permission";
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, Descriptions, Divider, message, Modal, Space } from "antd";
import { useState } from "react";
import FormBuilder from "zy-react-library/components/FormBuilder";
import AddIcon from "zy-react-library/components/Icon/AddIcon";
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 { LICENSE_PLATE_NUMBER } from "zy-react-library/regular";
import { validatorEndTime, validatorTimeGECurrentDay } from "zy-react-library/utils";
import { NS_VEHICLE_APPLY } from "~/enumerate/namespace";

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

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

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

  return (
    <Page isShowAllAction={false}>
      <Search
        options={[
          { name: "remarks", label: "名称" },
          { name: "licenceNo", label: "车牌号" },
        ]}
        form={form}
        onFinish={getData}
      />
      <Table
        toolBarRender={() => (
          <Space>
            {props.permission("jgd-io-inspect-vehicle-add") && (
              <Button
                type="primary"
                icon={(<AddIcon />)}
                onClick={() => {
                  setAddModalVisible(true);
                }}
              >
                新增
              </Button>
            )}
          </Space>
        )}
        columns={[
          { title: "名称", dataIndex: "checkDepartmentName" },
          { title: "车牌号", dataIndex: "licenceNo" },
          { title: "车牌类型", dataIndex: "licenceTypeName" },
          { title: "车辆类型", dataIndex: "vehicleTypeName" },
          {
            title: "操作",
            width: 250,
            fixed: "right",
            render: (_, record) => (
              <Space>
                {props.permission("jgd-io-inspect-vehicle-show") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setViewModalVisible(true);
                      setCurrentInfo(record);
                    }}
                  >
                    查看
                  </Button>
                )}
                {props.permission("jgd-io-inspect-vehicle-edit") && (
                  <Button
                    type="link"
                    onClick={() => {
                      setAddModalVisible(true);
                      setCurrentInfo(record);
                    }}
                  >
                    编辑
                  </Button>
                )}
                {props.permission("jgd-io-inspect-vehicle-del") && (
                  <Button
                    type="link"
                    danger
                    onClick={() => {
                      onDelete(record.id);
                    }}
                  >
                    删除
                  </Button>
                )}
                {props.permission("jgd-io-inspect-vehicle-inout") && (
                  <Button
                    type="link"
                    onClick={() => {
                      props.history.push(`./vehicleRecords?vehicleId=${record.id}`);
                    }}
                  >
                    车辆进出记录
                  </Button>
                )}
              </Space>
            ),
          },
        ]}
        {...tableProps}
      />
      {
        addModalVisible && (
          <AddModal
            info={currentInfo}
            getData={getData}
            onCancel={() => {
              setAddModalVisible(false);
              setCurrentInfo({});
            }}
          />
        )
      }
      {
        viewModalVisible && (
          <ViewModal
            info={currentInfo}
            onCancel={() => {
              setViewModalVisible(false);
              setCurrentInfo({});
            }}
          />
        )
      }
    </Page>
  );
}

const formatSubmitDate = (value) => {
  if (!value) {
    return value;
  }
  if (typeof value === "string") {
    return value.includes("T") ? value.split("T")[0] : value;
  }
  if (typeof value?.format === "function") {
    return value.format("YYYY-MM-DD");
  }
  return value;
};

const AddModalComponent = (props) => {
  const { info } = props;
  const isEdit = !!info.id;
  const [form] = FormBuilder.useForm();
  const inspectCarList = FormBuilder.useWatch("inspectCarList", form);

  const onSubmit = async (values) => {
    let outsideSuccess = false;
    const submitInspectCarList = (values.inspectCarList || []).map((item) => ({
      ...item,
      visitEndTime: formatSubmitDate(item.visitEndTime),
    }));
    const submitValues = {
      ...values,
      inspectCarList: submitInspectCarList,
    };
    if (!isEdit) {
      const { success } = await props["inspectDepartmentVehiclesAdd"]({
        ...submitValues,
        vehicleBelongType: 7,
      });
      outsideSuccess = success;
    }
    else {
      const { success } = await props["inspectDepartmentVehiclesUpdate"]({
        id: info.id,
        ...submitValues,
        ...submitInspectCarList[0],
        vehicleBelongType: 7,
      });
      outsideSuccess = success;
    }
    if (outsideSuccess) {
      message.success("保存成功");
      props.getData();
      props.onCancel();
    }
  };

  return (
    <Modal
      open
      title={isEdit ? "编辑" : "新增"}
      maskClosable={false}
      width={600}
      onCancel={props.onCancel}
      onOk={form.submit}
      confirmLoading={props.vehicleApply.vehicleApplyLoading}
    >
      <FormBuilder
        form={form}
        loading={props.vehicleApply.vehicleApplyLoading}
        showActionButtons={false}
        onFinish={onSubmit}
        span={24}
        labelCol={{ span: 10 }}
        values={{
          remarks: info.checkDepartmentName,
          inspectCarList: [{
            licenceType: info.licenceType,
            licenceTypeName: info.licenceTypeName,
            licenceNo: info.licenceNo,
            vehicleType: info.vehicleType,
            vehicleTypeName: info.vehicleTypeName,
          }],
        }}
        options={[
          { name: "checkDepartmentName", label: "名称" },
          { label: "车辆信息", render: FORM_ITEM_RENDER_ENUM.DIVIDER },
          {
            name: "inspectCarList",
            render: FORM_ITEM_RENDER_ENUM.FORM_LIST,
            formListUniqueProps: {
              showAddButton: !isEdit,
              showRemoveButton: !isEdit,
              options: (field, fieldIndex) => ([
                {
                  name: [field.name, "licenceType"],
                  label: "车牌类型",
                  render: (
                    <DictionarySelect
                      dictValue="LICENSE_PLATE_TYPE"
                      onGetLabel={(label) => {
                        form.setFieldValue(["inspectCarList", field.name, "licenceTypeName"], label);
                      }}
                    />
                  ),
                },
                { name: [field.name, "licenceTypeName"], label: "车牌类型名称", onlyForLabel: true },
                {
                  name: [field.name, "licenceNo"],
                  label: "车牌号",
                  rules: [{ pattern: LICENSE_PLATE_NUMBER, message: "请输入正确的车牌号" }],
                },
                {
                  name: [field.name, "vehicleType"],
                  label: "车辆类型",
                  render: (
                    <DictionarySelect
                      dictValue="VEHICLE_TYPE"
                      onGetLabel={(label) => {
                        form.setFieldValue(["inspectCarList", field.name, "vehicleTypeName"], label);
                      }}
                    />
                  ),
                },
                { name: [field.name, "vehicleTypeName"], label: "车辆类型名称", onlyForLabel: true },
                {
                  name: [field.name, "visitStartTime"],
                  label: "访问开始时间",
                  render: FORM_ITEM_RENDER_ENUM.DATE,
                  rules: [validatorTimeGECurrentDay({ type: "date" })],
                },
                {
                  name: [field.name, "visitEndTime"],
                  label: "访问结束时间",
                  render: FORM_ITEM_RENDER_ENUM.DATE,
                  rules: [validatorEndTime({ startTime: inspectCarList?.[fieldIndex]?.visitStartTime })],
                },
              ]),
            },
          },
        ]}
      />
    </Modal>
  );
};

const ViewModalComponent = (props) => {
  const { info } = props;

  return (
    <Modal
      open
      title="查看"
      maskClosable={false}
      width={600}
      onCancel={props.onCancel}
      footer={[
        <Button key="cancel" onClick={props.onCancel}>取消</Button>,
      ]}
      loading={props.vehicleApply.vehicleApplyLoading}
    >
      <Descriptions
        bordered
        column={1}
        styles={{ label: { width: 200 } }}
        items={[
          { label: "名称", children: info.checkDepartmentName },
        ]}
      />
      <Divider orientation="left">车辆信息</Divider>
      <Descriptions
        bordered
        column={1}
        styles={{ label: { width: 200 } }}
        items={[
          { label: "车牌类型", children: info.licenceTypeName },
          { label: "车牌号", children: info.licenceNo },
          { label: "车辆类型", children: info.vehicleTypeName },
          { label: "访问开始时间", children: info.visitStartTime },
          { label: "访问结束时间", children: info.visitEndTime },
        ]}
      />
    </Modal>
  );
};

const AddModal = Connect([NS_VEHICLE_APPLY], true)(AddModalComponent);
const ViewModal = Connect([NS_VEHICLE_APPLY], true)(ViewModalComponent);

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