import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { Button, message, Modal, Tabs } from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import FormBuilder from "zy-react-library/components/FormBuilder";
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 DepartmentSelectTree from "zy-react-library/components/SelectTree/Department/Gwj";
import Table from "zy-react-library/components/Table";
import TooltipPreviewImg from "zy-react-library/components/TooltipPreviewImg";
import Upload from "zy-react-library/components/Upload";
import { FORM_ITEM_RENDER_ENUM } from "zy-react-library/enum/formItemRender";
import { UPLOAD_FILE_TYPE_ENUM } from "zy-react-library/enum/uploadFile/gwj";
import useGetFile from "zy-react-library/hooks/useGetFile";
import useGetUserInfo from "zy-react-library/hooks/useGetUserInfo";
import useTable from "zy-react-library/hooks/useTable";
import useUploadFile from "zy-react-library/hooks/useUploadFile";
import { LICENSE_PLATE_NUMBER } from "zy-react-library/regular";
import { getLabelName } from "zy-react-library/utils";
import NeedToKnowModal from "~/components/NeedToKnowModal";
import {
  NS_APPROVER_USER,
  NS_ENCLOSED_AREA,
  NS_ENCLOSED_AREA_PERSONNEL_APPLY,
  NS_ENCLOSED_AREA_VEHICLE_APPLY,
  NS_VEHICLE_APPLY,
} from "~/enumerate/namespace";

function Add(props) {
  const [enclosedAreaList, setEnclosedAreaList] = useState([]);
  const [vehicleList, setVehicleList] = useState([]);
  const [selectVehicleModalVisible, setSelectVehicleModalVisible] = useState(false);
  const [needToKnowModalVisible, setNeedToKnowModalVisible] = useState(false);
  const [approvalUserListAll, setApprovalUserListAll] = useState([]);
  const [xgfProjectListAll, setXgfProjectListAll] = useState([]);
  const [xgfProjectUser, setXgfProjectUser] = useState([]);

  const signatureUrl = useRef("");

  const [form] = FormBuilder.useForm();
  const isSelectVehicle = FormBuilder.useWatch("isSelectVehicle", form);
  const { loading: uploadFileLoading, uploadFile } = useUploadFile();
  const { getUserInfo } = useGetUserInfo();

  const getApprovalUserListAll = async (corpId) => {
    const { data } = await props["approvalUserListAll"]({ vehiclePermissionFlag: 1, corpId });
    setApprovalUserListAll(data);
  };

  const getEnclosedAreaList = async (jurisdictionalCorpId) => {
    const { data } = await props["enclosedAreaDetailListTree"]({ jurisdictionalCorpId });
    setEnclosedAreaList(data);
  };

  const getXgfProjectListAll = async () => {
    const { data } = await props["xgfProjectListAll"]({betweenProjectTime :1 });
    setXgfProjectListAll(data);
  };

  const getXgfProjectUserGetPeopleProject = async (id) => {
    const { data } = await props["xgfProjectUserGetPeopleProject"]({ id });
    setXgfProjectUser(data);
  };

  useEffect(() => {
    props.entrance === "stakeholder" && getXgfProjectListAll();
  }, []);

  const onSubmit = async (values) => {
    if (values.isSelectVehicle === 1 && vehicleList.length === 0) {
      message.warning("请选择车辆");
      return;
    }
    if (!values.informSignFile) {
      message.warning("请勾选《安全进港须知》并签字");
      return;
    }
    if (isSelectVehicle === 2 || props.entrance === "stakeholder") {
      if (values.drivingLicenseFile.length !== 2) {
        message.error("请上传两张驾驶证");
        return;
      }
    }
    let carBelongType = 1;
    if (props.entrance === "enterprise")
      carBelongType = 2;
    if (props.entrance === "stakeholder")
      carBelongType = 3;
    const { id: informSignId } = await uploadFile({
      files: [{ originFileObj: values.informSignFile }],
      single: false,
      params: { foreignKey: "", type: UPLOAD_FILE_TYPE_ENUM[609] },
    });
    const { id: drivingLicenseId } = await uploadFile({
      files: values.drivingLicenseFile,
      single: false,
      params: { foreignKey: "", type: UPLOAD_FILE_TYPE_ENUM[601] },
    });
    const { id: attachmentId } = await uploadFile({
      files: values.attachmentFile,
      single: false,
      params: { foreignKey: "", type: UPLOAD_FILE_TYPE_ENUM[602] },
    });
    const { success } = await props["enclosedAreaVehicleApplySave"]({
      ...values,
      visitStartTime: values.visitTime[0],
      visitEndTime: values.visitTime[1],
      carBelongType,
      informSignId,
      licenceType: values.isSelectVehicle === 1 ? vehicleList[0].licenceType : values.licenceType,
      licenceTypeName: values.isSelectVehicle === 1 ? vehicleList[0].licenceTypeName : values.licenceTypeName,
      vehicleType: values.isSelectVehicle === 1 ? vehicleList[0].vehicleType : values.vehicleType,
      vehicleTypeName: values.isSelectVehicle === 1 ? vehicleList[0].vehicleTypeName : values.vehicleTypeName,
      licenceNo: values.isSelectVehicle === 1 ? vehicleList[0].licenceNo : values.licenceNo,
      drivingLicenseId: values.isSelectVehicle === 1 ? vehicleList[0].drivingLicenseId : drivingLicenseId,
      attachmentId: values.isSelectVehicle === 1 ? vehicleList[0].attachmentId : attachmentId,
    });
    if (success) {
      message.success("操作成功");
      props.history.goBack();
    }
  };

  return (
    <Page headerTitle="车辆申请" isShowFooter={false}>
      <FormBuilder
        submitButtonText="提交申请"
        onFinish={onSubmit}
        loading={props.enclosedAreaVehicleApply.enclosedAreaVehicleApplyLoading || uploadFileLoading}
        options={[
          {
            name: "projectId",
            label: "项目",
            tip: "如果无法找到相应的项目，请在“项目审核管理”栏目中查看，项目是否备案审核成功。",
            span: 24,
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: xgfProjectListAll,
            itemsField: { labelKey: "projectName", valueKey: "id" },
            hidden: !(props.entrance === "stakeholder"),
            componentProps: {
              onChange: (value) => {
                const item = xgfProjectListAll.find(i => i.id === value) || {};
                form.setFieldValue("projectName", item.projectName);
                form.setFieldValue("drivingUserId", "");
                form.setFieldValue("drivingUserName", "");
                if (value) {
                  getXgfProjectUserGetPeopleProject(value);
                  form.setFieldValue("visitTime", [dayjs(item.startProjectTime).format("YYYY-MM-DD"), dayjs(item.endProjectTime).format("YYYY-MM-DD")]);
                }
                else {
                  setXgfProjectUser([]);
                  form.setFieldValue("visitTime", []);
                }
              },
            },
          },
          { name: "projectName", label: "项目名称", onlyForLabel: true },
          {
            name: "isApplyCompanyArea",
            label: "是否申请本公司区域",
            span: 24,
            render: FORM_ITEM_RENDER_ENUM.RADIO,
            items: [{ bianma: 1, name: "是" }, { bianma: 2, name: "否" }],
            hidden: !(props.entrance === "enterprise"),
            componentProps: {
              onChange: async (event) => {
                if (event.target.value === 1) {
                  const userInfo = await getUserInfo();
                  form.setFieldValue("jurisdictionalCorpId", userInfo.corpinfoId);
                  form.setFieldValue("jurisdictionalCorpName", userInfo.corpinfoName);
                  form.setFieldValue("closedAreaId", "");
                  form.setFieldValue("closedAreaName", "");
                  getEnclosedAreaList(userInfo.corpinfoId);
                  getApprovalUserListAll(userInfo.corpinfoId);
                }
                else {
                  form.setFieldValue("jurisdictionalCorpId", "");
                  form.setFieldValue("jurisdictionalCorpName", "");
                  form.setFieldValue("closedAreaId", "");
                  form.setFieldValue("closedAreaName", "");
                  setEnclosedAreaList([]);
                  setApprovalUserListAll([]);
                }
              },
            },
          },
          {
            name: "jurisdictionalCorpId",
            label: "区域管辖单位",
            render: (
              <DepartmentSelectTree
                searchType="inType"
                params={{ enterpriseType: [2] }}
                onChange={(value) => {
                  if (value) {
                    getEnclosedAreaList(value);
                    getApprovalUserListAll(value);
                  }
                  else {
                    setEnclosedAreaList([]);
                    setApprovalUserListAll([]);
                  }
                  form.setFieldValue("closedAreaId", "");
                }}
                onGetLabel={label => form.setFieldValue("jurisdictionalCorpName", label)}
              />
            ),
            dependencies: ["isApplyCompanyArea"],
            hidden: (formValues) => {
              if (props.entrance !== "enterprise")
                return false;
              return !(formValues.isApplyCompanyArea === 2 || formValues.isApplyCompanyArea === null);
            },
            formItemProps: { preserve: true },
          },
          { name: "jurisdictionalCorpName", label: "区域管辖单位名称", onlyForLabel: true },
          {
            name: "closedAreaId",
            label: "封闭区域",
            render: (
              <BasicSelectTree
                treeData={enclosedAreaList}
                placeholder="封闭区域"
                onGetLabel={label => form.setFieldValue("closedAreaName", label)}
                nameKey="closedAreaName"
              />
            ),
          },
          { name: "closedAreaName", label: "封闭区域名称", onlyForLabel: true },
          {
            name: "auditPersonUserId",
            label: "审核人员",
            render: FORM_ITEM_RENDER_ENUM.SELECT,
            items: approvalUserListAll,
            itemsField: { labelKey: item => `${item.userName}（${item.corpName}）（${item.deptName}）`, valueKey: "userId" },
            componentProps: {
              onChange: (value) => {
                const item = approvalUserListAll.find(item => item.userId === value);
                form.setFieldValue("auditPersonUserName", item.userName);
                form.setFieldValue("auditPersonCorpId", item.corpId);
                form.setFieldValue("auditPersonCorpName", item.corpName);
                form.setFieldValue("auditPersonDepartmentId", item.deptId);
                form.setFieldValue("auditPersonDepartmentName", item.deptName);
              },
            },
          },
          { name: "auditPersonUserName", label: "审核人员名称", onlyForLabel: true },
          { name: "auditPersonCorpId", label: "审核企业ID", onlyForLabel: true },
          { name: "auditPersonCorpName", label: "审核企业名称", onlyForLabel: true },
          { name: "auditPersonDepartmentId", label: "审核部门ID", onlyForLabel: true },
          { name: "auditPersonDepartmentName", label: "审核部门名称", onlyForLabel: true },
          {
            name: "visitTime",
            label: "申请时间范围",
            render: FORM_ITEM_RENDER_ENUM.DATE_RANGE,
            componentProps: { disabled: props.entrance === "stakeholder" },
          },
          {
            name: "isSelectVehicle",
            label: "车辆类型",
            span: 24,
            render: FORM_ITEM_RENDER_ENUM.RADIO,
            items: [{ bianma: 1, name: "选择现有车辆" }, { bianma: 2, name: "新增车辆" }],
            componentProps: {
              onChange: () => {
                setVehicleList([]);
              },
            },
            hidden: props.entrance === "stakeholder",
          },
          ...(isSelectVehicle === 1
            ? [
                {
                  label: "选择现有车辆",
                  span: 24,
                  customizeRender: true,
                  render: (
                    <Table
                      style={{ marginBottom: 16 }}
                      toolBarRender={() => (
                        <Button
                          type="primary"
                          onClick={() => {
                            setSelectVehicleModalVisible(true);
                          }}
                        >
                          选择车辆
                        </Button>
                      )}
                      options={false}
                      disabledResizer={true}
                      pagination={false}
                      columns={[
                        { title: "车牌类型", dataIndex: "licenceTypeName" },
                        { title: "车辆类型", dataIndex: "vehicleTypeName" },
                        { title: "车牌号", dataIndex: "licenceNo" },
                        {
                          title: "车辆照片",
                          dataIndex: "files",
                          render: (_, record) => <TooltipPreviewImg files={record.files} />,
                        },
                        {
                          title: "操作",
                          render: (_, record) => (
                            <Button
                              type="link"
                              danger
                              onClick={() => {
                                setVehicleList(vehicleList.filter(item => item.id !== record.id));
                              }}
                            >
                              删除
                            </Button>
                          ),
                        },
                      ]}
                      dataSource={vehicleList}
                    />
                  ),
                },
              ]
            : []),
          ...(props.entrance === "stakeholder"
            ? [
                {
                  name: "drivingUserId",
                  label: "驾驶人员",
                  render: FORM_ITEM_RENDER_ENUM.SELECT,
                  items: xgfProjectUser,
                  itemsField: { labelKey: "userName", valueKey: "userId" },
                  componentProps: {
                    onChange: (value) => {
                      form.setFieldValue("drivingUserName", getLabelName({
                        list: xgfProjectUser,
                        status: value,
                        idKey: "userId",
                        nameKey: "userName",
                      }));
                    },
                  },
                },
                { name: "drivingUserName", label: "驾驶人员名称", onlyForLabel: true },
              ]
            : []),
          ...(isSelectVehicle === 2 || props.entrance === "stakeholder"
            ? [
                {
                  name: "licenceType",
                  label: "车牌类型",
                  render: (
                    <DictionarySelect
                      dictValue="LICENSE_PLATE_TYPE"
                      onGetLabel={label => form.setFieldValue("licenceTypeName", label)}
                    />
                  ),
                },
                { name: "licenceTypeName", label: "车牌类型名称", onlyForLabel: true },
                {
                  name: "vehicleType",
                  label: "车辆类型",
                  render: (
                    <DictionarySelect
                      dictValue="VEHICLE_TYPE"
                      onGetLabel={label => form.setFieldValue("vehicleTypeName", label)}
                    />
                  ),
                },
                { name: "vehicleTypeName", label: "车辆类型名称", onlyForLabel: true },
                {
                  name: "licenceNo",
                  label: "车牌号",
                  rules: [
                    { pattern: LICENSE_PLATE_NUMBER, message: "请输入正确的车牌号" },
                    {
                      validator: async (_, value) => {
                        if (value) {
                          const { data } = await props["vehicleApplyCheckLicenceNo"]({
                            licenceNo: value,
                          });
                          return data.available ? Promise.resolve() : Promise.reject(new Error(data.availableMessage));
                        }
                        else {
                          Promise.resolve();
                        }
                      },
                      validateTrigger: "onBlur",
                    },
                  ],
                  formItemProps: { validateTrigger: ["onChange", "onBlur"] },
                },
                {
                  name: "attachmentFile",
                  label: "车辆照片",
                  span: 24,
                  render: (
                    <Upload
                      maxCount={4}
                      size={5}
                      tipContent={(
                        <div style={{ color: "red", fontSize: 12 }}>
                          <div>1.上限4张</div>
                          <div>2. 请从车辆左前侧45°拍摄，车牌清晰可见</div>
                          <div>3. 背景简洁，避免逆光或阴影</div>
                          <div>4. 支持格式:.jpg/.jpeg/.png，单张5MB</div>
                        </div>
                      )}
                    />
                  ),
                },
                {
                  name: "drivingLicenseFile",
                  label: "行驶证照片",
                  span: 24,
                  render: (
                    <Upload
                      maxCount={2}
                      size={5}
                      tipContent={(
                        <div style={{ color: "red", fontSize: 12 }}>
                          <div>1. 请拍摄行驶证正面和反面，确保四角完整、无遮挡</div>
                          <div>2. 文字、印章清晰可见，避免反光</div>
                          <div>3. 支持格式:.jpg/.jpeg/.png，单张5MB</div>
                        </div>
                      )}
                    />
                  ),
                },
              ]
            : []),
          { name: "applyReason", label: "申请原因", span: 24, render: FORM_ITEM_RENDER_ENUM.TEXTAREA },
          {
            name: "securityProtocol",
            label: " ",
            span: 24,
            required: false,
            rules: [{ required: true, message: "请勾选" }],
            formItemProps: {
              colon: false,
              required: false,
              style: { textAlign: "center" },
              labelCol: { span: 0 },
              wrapperCol: { span: 24 },
            },
            render: FORM_ITEM_RENDER_ENUM.CHECKBOX,
            items: [{
              bianma: "1",
              name: (
                <>
                  我已阅读并同意
                  <Button
                    type="link"
                    style={{ padding: 0 }}
                    onClick={() => {
                      setNeedToKnowModalVisible(true);
                    }}
                  >
                    《安全进港须知》
                  </Button>
                </>
              ),
            }],
          },
          { name: "informSignFile", label: "签字", onlyForLabel: true },
        ]}
        form={form}
      />
      {
        selectVehicleModalVisible && (
          <SelectVehicleModal
            vehicleList={vehicleList}
            entrance={props.entrance}
            onClose={() => {
              setSelectVehicleModalVisible(false);
            }}
            onOk={(values) => {
              setVehicleList(values);
              setSelectVehicleModalVisible(false);
            }}
          />
        )
      }
      {
        needToKnowModalVisible && (
          <NeedToKnowModal
            signatureUrl={signatureUrl.current}
            onCancel={() => {
              setNeedToKnowModalVisible(false);
            }}
            onOk={(values) => {
              form.setFieldValue("informSignFile", values.file);
              signatureUrl.current = values.base64;
              setNeedToKnowModalVisible(false);
            }}
          />
        )
      }
    </Page>
  );
}

const SelectVehicleModalComponent = (props) => {
  const [tabActiveKey, setTabActiveKey] = useState("1");
  const [selectedRowKeys, setSelectedRowKeys] = useState(props.vehicleList.map(item => item.id));
  const [list, setList] = useState([]);

  const selectedRowsRef = useRef(props.vehicleList || []);

  const { loading: getFileLoading, getFile } = useGetFile();

  const [form] = Search.useForm();
  const { tableProps, getData } = useTable(props["enclosedAreaVehicleApplyVehicleList"], {
    form,
    useStorageQueryCriteria: false,
    params: () => {
      let vehicleBelongType;
      if (!props.entrance) {
        if (tabActiveKey === "1")
          vehicleBelongType = 1;
        else if (tabActiveKey === "2")
          vehicleBelongType = 2;
      }
      else if (props.entrance === "enterprise") {
        if (tabActiveKey === "1")
          vehicleBelongType = 3;
        else if (tabActiveKey === "2")
          vehicleBelongType = 4;
      }
      return { vehicleBelongType };
    },
    onSuccess: async (data) => {
      const list = await getFile({
        single: false,
        dataSource: data.list,
        eqType: UPLOAD_FILE_TYPE_ENUM[602],
        foreignKey: "attachmentId",
      });
      setList(list);
    },
  });

  return (
    <Modal
      title="选择车辆"
      open
      maskClosable={false}
      width={900}
      onCancel={props.onClose}
      onOk={() => {
        props.onOk(selectedRowsRef.current);
      }}
    >
      <Search
        options={[
          { name: "licenceNo", label: "车牌号" },
        ]}
        form={form}
        onFinish={getData}
      />
      <Table
        headerTitle={(
          <Tabs
            activeKey={tabActiveKey}
            items={[{ label: "个人车辆", key: "1" }, { label: "公司车辆", key: "2" }]}
            onChange={(event) => {
              setTabActiveKey(event);
              getData();
            }}
          />
        )}
        rowSelection={{
          selectedRowKeys,
          type: "radio",
          preserveSelectedRowKeys: true,
          onChange: (selectedRowKeys, selectedRows) => {
            setSelectedRowKeys(selectedRowKeys);
            selectedRowsRef.current = selectedRows;
          },
        }}
        options={false}
        disabledResizer={true}
        columns={[
          { title: "车牌类型", dataIndex: "licenceTypeName" },
          { title: "车辆类型", dataIndex: "vehicleTypeName" },
          { title: "车牌号", dataIndex: "licenceNo" },
          {
            title: "车辆照片",
            dataIndex: "files",
            render: (_, record) => <TooltipPreviewImg files={record.files} />,
          },
        ]}
        {...tableProps}
        loading={tableProps.loading || getFileLoading}
        dataSource={list}
      />
    </Modal>
  );
};

const SelectVehicleModal = Connect([NS_ENCLOSED_AREA_VEHICLE_APPLY], true)(SelectVehicleModalComponent);

export default Connect([NS_ENCLOSED_AREA_VEHICLE_APPLY, NS_ENCLOSED_AREA, NS_APPROVER_USER, NS_VEHICLE_APPLY, NS_ENCLOSED_AREA_PERSONNEL_APPLY], true)(Add);
