/*
 * @Author: cclu
 * @Date: 2021-12-13 11:01:23
 * @LastEditTime: 2024-10-29 16:42:14
 * @LastEditors: cclu 1106109051@qq.com
 * @Description: 编辑/新增合同组件
 * @FilePath: \cloud-platform\src\pages\contract\components\editor.tsx
 */
import moment from 'moment';
import { connect } from "umi";
import React, { useRef, useState, useImperativeHandle } from 'react';
import useRequest from "@ahooksjs/use-request";
import ProTable from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, {
  ProFormDateRangePicker, ProFormDateTimePicker, ProFormDigit, ProFormSelect,
  ProFormText, ProFormTextArea, ProFormUploadButton
} from '@ant-design/pro-form';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import {
  Button,
  Card,
  Col,
  Menu,
  message,
  Modal,
  Row,
  Avatar,
  Image,
  Popconfirm,
  Select,
  Descriptions,
  Upload, Drawer, Tooltip
} from 'antd';
import { ExclamationCircleOutlined, FileSearchOutlined, MinusOutlined, MinusSquareOutlined, PlusOutlined } from '@ant-design/icons';

import type { FormInstance } from 'antd';
import type { ConnectState } from "@/models/connect";
import type { ActionType } from '@ant-design/pro-table';
import type { MerchantModel } from '@/pages/basicManage/Merchats/data'
import type { ContractListModel, ContractSubModel, ServerpartContractModel } from '../data';
import type { BrandModel } from '@/pages/basicManage/Brand/data';
import type { CurrentUser } from '@/models/user';

import { businessType, contractType, severpartType } from '../emun';
import type { ServerpartTree } from '@/services/options';
import { getServerpartOption, getServerpartTree } from '@/services/options';
import { getList as getMerchatsList } from '@/pages/basicManage/Merchats/service'
import { getList as getBrandList } from '@/pages/basicManage/Brand/service'
import { getBusniessBrandTree, getBusinessMerchatsList } from '@/pages/basicManage/service';
import {
  delCompact,
  getContractServerpartList,
  getDetail,
  getList as getContractList,
  getSubDetail,
  handleGetRelatedList,
  updateContract,
  updateSubContract
} from '../service';

import { getBase64 } from '@/utils/utils';
import { getPictureList, deletePicture, uploadPicture } from '@/services/picture';
import type { UploadFile } from 'antd/es/upload/interface';
import type { PictureModel } from '@/services/options/typings';

import '../style.less';
import Draggable from "react-draggable";
import type { BusinessProjectModel } from "@/pages/BussinessProject/data";
import { handleGetServiceShopList } from "@/pages/DataVerification/service";
import './editor.less'
import addPartyC from '/src/assets/detail/addPartyC.svg'
import fileIcon from "@/assets/detail/fileIcon.svg";
import ContractDetail from './detail';
import session from '@/utils/session';
import { handleGetRegisterCompactDetail } from '@/pages/reports/component/service';

const { SubMenu } = Menu;
const { confirm } = Modal;
/**
 * @description: 根据服务区类型 和 经营业态 计算每平方物业费
 * @param {number} a 服务区类型
 * @param {number} b 经营业态
 * @return {*} 每平方米物业费 元/月
 */
const calcServiceCoast = (a: number | string, b: number | string) => {
  const coastRule: Record<number, number[]> = {
    1000: [0, 13, 32, 15, 5, 3],
    2000: [0, 10, 25, 12, 4, 2],
    3000: [0, 8, 20, 10, 2, 1],
    4000: [0, 5, 10, 5, 1, 0.5]
  }
  return a && b ? coastRule[a][b] : ''
}

// 创建或更新合同
const handleAddUpdate = async (fields: ContractListModel & ContractSubModel & any) => {
  const hide = message.loading('正在提交...');
  const result = await updateContract(fields);
  if (result.Result_Code !== 100) {
    message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`);
    return false;
  }

  const subResult = await updateSubContract({ ...fields, REGISTERCOMPACT_ID: result.Result_Data.REGISTERCOMPACT_ID })
  hide();
  if (subResult.Result_Code !== 100) {
    message.error(`${subResult.Result_Desc}` || `${subResult.Result_Code}:提交失败`);
    return false;
  }
  message.success(fields.REGISTERCOMPACT_ID ? '更新成功！' : '新建成功！');
  return result.Result_Data;
};
// 上传附件
const customUploadRequest = async (fileList: UploadFile[], tableId: string) => {
  if (!fileList.length) {
    message.error("您上传的附件不存在.")
    return false
  }
  const formData = new FormData();
  fileList.forEach(file => {
    formData.append('files[]', file);
  });
  formData.append('TableType', '1115');
  formData.append('TableId', tableId);
  const success = await uploadPicture(formData)
  if (success) {
    return true
  }
  return false
}

// 删除数据
const handelDelete = async (registerCompactId: number) => {
  const hide = message.loading('正在删除...');
  try {
    const result = await delCompact(registerCompactId);

    hide();
    if (result.Result_Code !== 100) {
      message.error(`${result.Result_Desc}`);
      return false;
    }
    message.success('删除成功！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败');
    return false;
  }
};

function getMenuDomModal(data: ServerpartTree[], callback?: Function) {
  // 遍历菜单数据源并返回相应的菜单子父级节点
  return (
    data.map((element: any) => {
      // 判断数据是否为父级菜单 是则返回父级菜单容器并生成包含的子菜单
      if (element.type === 0) {

        return (
          <SubMenu  // 父级菜单andt组件
            title={element.label}
            key={`${element.value}`}
            onTitleClick={(item) => { // 点击父级菜单标题方法 执行传入的回调方法
              callback?.call(callback, item);
              item.domEvent.stopPropagation();
            }}
          >
            {/* 父级菜单有子级存在,则遍历子级数据生成子菜单 */}
            {element.children && element.children.length > 0 && getMenuDomModal(element.children, callback)}
          </SubMenu>
        );
      }
      // 返回子菜单
      return (
        <Menu.Item key={`${element.value}`}>{element.label}</Menu.Item>); // 子级菜单andt组件
    })
  );
}


const EditContract = ({ contractId: id, actionRef, setShowDetail, showDelete, currentUser, handleGetChildrenData, handleGetContractChild, showType }: { contractId?: number, actionRef: any, setShowDetail: any, showDelete?: boolean, type?: string, currentUser?: CurrentUser, handleGetChildrenData?: any, handleGetContractChild?: any, showType?: string }) => {
  // const EditContract: React.FC<{ contractId?: number, actionRef: any, setShowDetail: any, showDelete?: boolean,type?: string, currentUser?: CurrentUser,onRef?: any }> = ({
  //     contractId: id, actionRef, setShowDetail, showDelete, currentUser ,onRef}) => {
  const formRef = useRef<FormInstance>();
  const compayActionRef = useRef<ActionType>();
  const brandActionRef = useRef<ActionType>();
  const [visible, setVisible] = useState<boolean>()
  const [brandVisible, setBrandVisible] = useState<boolean>() // 选择品牌弹出框
  const [brand, setBrand] = useState<BrandModel>() // 选中的品牌
  // 关联合同列表
  const [relatedContractsList, setRelatedContractsList] = useState<any>()
  // 选中的关联合同
  const [childrenRow, setChildrenRow] = useState<any>()
  // 显示关联合同的抽屉
  const [showChildDetailDrawer, setShowChildDetailDrawer] = useState<boolean>(false)
  const [selectName, setSelectName] = useState<string>() // 当前选中的商户名称 甲乙丙三方
  const [company, setCompany] = useState<MerchantModel>() // 选中的商户数据对象
  const [fields, setFields] = useState<ContractListModel & ContractSubModel & {
    serverpartIds: [], SERVERPART_IDS: string
  }>(); // 当前组件显示的 合同详情 包括主表和子表数据
  const [currenMenu, setCurrenMenu] = useState<any>(); // 当前弹出的左侧菜单选中的详细数据
  const [selectedKeys, setSelectedKeys] = useState<any>(); // 当前弹出的左侧菜单选中的ids值
  const [fileList, setFileList] = useState<UploadFile[]>([]) // 需要上传的附件图片列表
  const [priviewImage, setPriviewImage] = useState<string>(); // 预览的文件地址
  const [showBtn, setShowBtn] = useState<boolean>(false)
  const [confirmLoading, handleConfirmLoading] = useState<boolean>(false) // 弹出框的内容表单是否在提交
  const [contract, setContract] = useState<ContractListModel>() // 当前选择的合同
  const [currentRow, setCurrentRow] = useState<BusinessProjectModel | any>(undefined)
  const [selectShops, setSelectShops] = useState<any[]>() // 选择的门店数据
  const draggleRef = React.createRef<any>()
  // 显示关联合同的附件
  const [showChildrenFile, setShowChildrenFile] = useState<boolean>(false)
  // 关联合同的附件
  const [childrenFile, setChildrenFile] = useState<any>()
  // 拖动开始
  const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
  const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
  const [COMPACTLIST, setCOMPACTLIST] = useState<any>()

  // 获取合同类型子项
  const { loading: COMPACTLoading, data: COMPACTLISTS } = useRequest(async () => {
    const options = session.get("COMPACT_DETAILSList")
    if (options && options.length > 0) {
      options.forEach((item: any) => {
        if (item.value === 2002 || item.value === 3000) {
          item.disabled = true
          item.label = <Tooltip title={'请跳转到主体合同内添加！'}>
            <span style={{ color: 'rgba(0,0,0,0.25)' }}>{item.label}</span>
          </Tooltip>
        }
      })
    }
    setCOMPACTLIST(options)
    const obj: any = session.get("COMPACT_DETAILSObj")

    return obj;
  })
  const onDraggaleStart = (event, uiData) => {

    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };
  // 拖动结束

  // 请求服务区树列表
  const { loading: serverPartLoading, data: serverpartTree } = useRequest(async () => {
    const data = await getServerpartTree()
    return data
  })
  const [serverpartId, setServerpartId] = useState<string>() // 合同包含的服务区ids
  const [shopId, setShopId] = useState<any>()// 搜索框选择的门店id
  const [shopList, setShopList] = useState<any>()
  const [contractId, setContractId] = useState<any>()
  // 合同列表内容
  const compactColumns = [
    {
      dataIndex: 'COMPACT_NAME',
      title: '合同名称',
      ellipsis: true,
      // hideInSearch: true
    },
    {
      dataIndex: 'shopName',
      title: '门店列表',
      hideInTable: true,
      renderFormItem: (_, record) => {
        return <Select
          value={shopId}
          options={shopList}
          onChange={(e: any) => {
            setShopId(e)
          }}
          filterOption={(input, option) =>
            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
          }
          showSearch
          allowClear
        >

        </Select>
      }
    },
    {
      dataIndex: 'SERVERPARTSHOP_NAME',
      title: '门店名称',
      hideInSearch: true,
    },
    {

      title: '合同金额',
      dataIndex: 'COMPACT_AMOUNT',
      hideInSearch: true,
      width: 130,
      align: "center",
      render: (_) => {
        return <div style={{ width: 100, textAlign: "right" }}>{_}</div>
      }
    },
    {
      title: '开始日期',
      hideInSearch: true,
      dataIndex: 'COMPACT_STARTDATE',
      valueType: 'date',
      sorter: true,
      width: 110
    },
    {
      title: '结束日期',
      hideInSearch: true,
      dataIndex: 'COMPACT_ENDDATE',
      valueType: 'date',
      sorter: true,
      width: 110
    },

  ]
  // 选择了的门店列表
  const contractActionRef = useRef<ActionType>()  // 合同列表对象
  const contractFormRef = useRef<ProFormInstance>(); // 合同列表查询对象
  // 是否显示丙方
  const [showAddPartyC, setAddPartyC] = useState<boolean>(false)
  // 请求经营品牌树
  const { loading, data: busiessBrand = [] } = useRequest(getBusniessBrandTree)
  const [contractVisible, setContractVisible] = useState<number>(0) // 0关闭 1 合同 2 门店
  // 根据选中的经营业态或品牌查询经营商户
  const searchBusiness = (item: any) => {
    setSelectedKeys(item.selectedKeys || [])
    const [key, value] = item.key.split('-')
    setCurrenMenu({ [key]: value, current: 1 })
    compayActionRef.current?.reload()
  }
  const renderOption = (option: any) => {
    if (option.disabled) {
      return (
        <Tooltip key={option.value} title={'请跳转到主体合同内添加！'}>
          <div style={{ color: 'rgba(0, 0, 0, 0.25)', padding: '8px 12px' }}>
            {option.label}
          </div>
        </Tooltip>
      );
    }
    return (
      <div key={option.value} style={{ padding: '8px 12px' }}>
        {option.label}
      </div>
    );
  };

  // 根据选中的经营业态查询品牌
  const searchBrand = (item: any) => {
    setSelectedKeys(item.selectedKeys || [])
    const [_, value] = item.key.split('-')
    setCurrenMenu({ 'BRAND_INDUSTRY': value, current: 1 })
    brandActionRef.current?.reload()
  }
  // 生成商户左侧菜单
  const getMenuDom = (data: any[], callback: () => void, noBrand?: boolean) => {
    return (data.map((element: any) => {
      if ((!noBrand && element.BrandTreeList && element.BrandTreeList.length > 0) || element.children) {
        return (
          <SubMenu title={element.BusinessTrade_Name}
            icon={<Avatar src={element.BusinessTrade_ICO} size={16} style={{ marginRight: 4 }} shape="square" />}
            key={`BUSINESSTRADE_ID-${element.BusinessTrade_Id}`}
            onTitleClick={(item) => {
              if (!currenMenu || item.key !== `BUSINESSTRADE_ID-${currenMenu?.BUSINESSTRADE_ID}`) {
                callback.call(callback, item)
              }
              item.domEvent.stopPropagation();
            }}
          >
            {!noBrand && element.BrandTreeList.length > 0 && element.BrandTreeList.map((c: any) =>
              <Menu.Item key={`BRAND_ID-${c.Brand_ID}`}
                icon={<Avatar src={c.Brand_ICO} style={{ backgroundColor: '#fafafa' }} size={22} shape="square" />} >
                {c.Brand_Name}
              </Menu.Item>
            )}
            {element.children && element.children.length > 0 && getMenuDom(element.children, callback, noBrand || undefined)}
          </SubMenu>
        )
      }
      return (<Menu.Item icon={<Avatar src={element.BusinessTrade_ICO} size={16} shape="square" />}
        key={`BUSINESSTRADE_ID-${element.BusinessTrade_Id}`}>{element.BusinessTrade_Name}</Menu.Item>)
    }))
  }

  // 选择甲乙丙三方公司
  const openModal = (value: string) => {
    setSelectName(value)
    setVisible(true)
    if (compayActionRef) {
      compayActionRef.current?.reset()
    }
  }

  // 拿到关联合同列表
  const handleGetRelatedContracts = async (id: number) => {
    const req = {
      SearchParameter: {
        REGISTERCOMPACT_HOSTID: id,
        COMPACT_STATE: 1000
      },
      PageIndex: 1,
      PageSize: 999999
    }
    const data = await handleGetRelatedList(req)
    if (data && data.data && data.data.length > 0) {
      const list: any = []
      data.data.forEach((item: any) => {
        if (item.COMPACT_DETAILS !== 1000) {
          list.push(item)
        }
      })
      setRelatedContractsList(list)
    }
  }

  return (
    <PageContainer header={{ title: "", breadcrumb: {} }}>
      <ProForm
        formRef={formRef}
        wrapperCol={{ span: 18 }}
        initialValues={{
          STAFF_NAME: currentUser ? currentUser.Name : '',
          USER_ID: currentUser ? currentUser.ID : '',
          OPERATE_DATE: moment().format('YYYY-MM-DD hh:mm:ss'),
        }}
        submitter={{
          render: (_, dom) => (
            <FooterToolbar
              style={{
                // left: 208,
                width: "73%",
              }}
            >
              {[...dom,
              showDelete && id && <Popconfirm
                title="确认删除该合同记录吗?"
                onConfirm={async () => {
                  const sucesse = await handelDelete(id || 0);
                  if (sucesse && actionRef.current) {
                    actionRef.current.reload();
                    setShowDetail(0)
                  }
                }}
              >
                <Button danger key="delete">
                  作废
                </Button>
              </Popconfirm>
              ]}
            </FooterToolbar>
          )
        }}
        request={async (value) => {
          // 初始化数据
          const data: any = {
            STAFF_NAME: currentUser ? currentUser.Name : '',
            USER_ID: currentUser ? currentUser.ID : '',
            OPERATE_DATE: moment().format('YYYY-MM-DD hh:mm:ss'),
          };
          // 如果是编辑数据 则需要请求原数据
          if (id) {
            const orgData: any = await getDetail(id); // 主表合同详情
            if (orgData && orgData.REGISTERCOMPACT_ID) {
              handleGetRelatedContracts(orgData.REGISTERCOMPACT_ID)
            }
            if (handleGetChildrenData) {
              handleGetChildrenData(orgData)
            }
            const subData: any = await getSubDetail(id); // 子表合同详情
            const serverpart: any = await getContractServerpartList(id) // 合同包含的服务区
            const serverpartIds: [] = serverpart.map((n: ServerpartContractModel) => n.SERVERPART_ID) || []
            const newData = {
              ...orgData,
              ...subData,
              BUSINESS_TYPE: `${subData?.BUSINESS_TYPE}`,
              BUSINESS_TRADE: subData?.BUSINESS_TRADE ? `${subData?.BUSINESS_TRADE.toString()}` : "",
              BUSINESS_BRAND: subData?.BUSINESS_BRAND ? `${subData?.BUSINESS_BRAND.toString()}` : "",
              SERVERPART_TYPE: subData?.SERVERPART_TYPE ? `${subData?.SERVERPART_TYPE}` : "",
              serverpartIds,
              SERVERPART_IDS: serverpartIds.toString(),
              contractRangeDate: [orgData?.COMPACT_STARTDATE, orgData?.COMPACT_ENDDATE],
              contractRentrfreeRangeDate: [subData?.RENTFREE_STARTDATE, subData?.RENTFREE_ENDDATE],
              contractDecorateRangeDate: [subData?.DECORATE_STARTDATE, subData?.DECORATE_ENDDATE],
              SERVERPARTREGION: subData?.SERVERPARTREGION ? subData?.SERVERPARTREGION.split(',') : []
            }
            const pictureList = await getPictureList(id, '1115')
            const files = pictureList && pictureList?.total > 0 ? pictureList?.data.map((n: PictureModel) => {
              return {
                uid: n.ImageId,
                name: n.ImageName,
                status: 'done',
                url: n.ImageUrl,
                deletepath: n.ImagePath
              }
            }) : []
            setFields(newData);
            setFileList(files);
            if (newData.COMPACT_DETAILS !== 1000) {
              setShowBtn(true)
            } else {
              setShowBtn(false)
            }
            return newData;
          }
          return { ...data };
        }}
        params={{ id }}
        onFinish={async (values) => {
          let newValue: any = { ...values };
          if (fields && fields.REGISTERCOMPACT_ID) {
            // 编辑数据
            newValue = { ...fields, ...values };
          } else {
            newValue.COMPACT_STATE = 1000;
            newValue.FIRSTPART_ID = fields?.FIRSTPART_ID;
            newValue.SECONDPART_ID = fields?.SECONDPART_ID;
          }
          let [COMPACT_STARTDATE, COMPACT_ENDDATE] = ["", ""]
          // 格式化数据
          if (values.contractRangeDate) {
            [COMPACT_STARTDATE, COMPACT_ENDDATE] = values.contractRangeDate
          }

          newValue.COMPACT_STARTDATE = COMPACT_STARTDATE
          newValue.COMPACT_ENDDATE = COMPACT_ENDDATE
          newValue.REPAIR_TIME = values.REPAIR_TIME ? values.REPAIR_TIME : null
          newValue.WATER_CHARGE = values.WATER_CHARGE ? values.WATER_CHARGE : null
          newValue.ELECTRICITY_FEES = values.ELECTRICITY_FEES ? values.ELECTRICITY_FEES : null
          newValue.OTHER_SCHARGE = values.OTHER_SCHARGE ? values.OTHER_SCHARGE : null
          newValue.EQUIPMENT_DEPOSIT = values.EQUIPMENT_DEPOSIT ? values.EQUIPMENT_DEPOSIT : null
          // newValue.BUSINESS_BRAND = brand?.BRAND_ID || fields?.BUSINESS_BRAND
          // 装修周期
          if (values.contractDecorateRangeDate) {
            newValue.DECORATE_STARTDATE = values.contractDecorateRangeDate[0] || ''
            newValue.DECORATE_ENDDATE = values.contractDecorateRangeDate[1] || ''
          }
          else {
            newValue.DECORATE_STARTDATE = ''
            newValue.DECORATE_ENDDATE = ''
          }
          // 免租周期
          if (values.contractRentrfreeRangeDate) {
            newValue.RENTFREE_STARTDATE = values.contractRentrfreeRangeDate[0] || ''
            newValue.RENTFREE_ENDDATE = values.contractRentrfreeRangeDate[1] || ''
          }
          else {
            newValue.RENTFREE_STARTDATE = ''
            newValue.RENTFREE_ENDDATE = ''
          }
          if (fields?.SERVERPART_IDS !== newValue.serverpartIds.toString()) {
            newValue.SERVERPART_IDS = newValue.serverpartIds.toString()
          }
          // 所属区域
          if (newValue?.SERVERPARTREGION && typeof newValue.SERVERPARTREGION === 'object') {
            newValue.SERVERPARTREGION = newValue.SERVERPARTREGION.toString()
          }
          if (contractId) {
            newValue.REGISTERCOMPACT_HOSTID = contractId
          }
          // 提交编辑后的数据
          const success = await handleAddUpdate({ ...newValue });
          if (success) {
            const waitUpload = fileList.filter(n => n.status !== 'done')
            if (waitUpload.length > 0) {
              await customUploadRequest(waitUpload, success?.REGISTERCOMPACT_ID)
            }
            actionRef.current.reload();
          }

          return true;
        }}
      >
        <Card style={{ marginTop: 24, marginBottom: 24 }}>
          <Row>
            <Col span={12} className={'upLoadBox'}>
              {/* 上传文件组件 */}
              <ProFormUploadButton
                name="ImgList"
                title="合同附件"
                label=""
                wrapperCol={{ span: 20 }}
                labelCol={{ span: 3 }}
                // 附件默认要求必传，可以取消限制
                // rules={[
                //     {
                //         required: showDelete,
                //         message: '请上传合同文件',
                //     }
                // ]}
                fieldProps={{
                  name: 'files',
                  listType: 'text',
                  className: 'is-dragging',
                  // defaultFileList: priviewFileList,
                  fileList,
                  multiple: true,
                  onPreview: async (file) => {
                    if (file.type && file.type?.indexOf('image/') > -1) { // 未上传的文件 如果是图片类型的
                      if (!file.url && !file.preview) {
                        setPriviewImage(await getBase64(file.lastModifiedDate))
                      } else {
                        setPriviewImage(file?.url)
                      }
                    } else {
                      const filenameSplitPointArr = file.fileName?.split('.') || []
                      if (['png', 'jpg', 'jpeg'].indexOf(filenameSplitPointArr[filenameSplitPointArr?.length - 1]) > -1) {
                        setPriviewImage(file?.url)
                      }
                      else if (file?.url) {
                        window.open(file?.url)
                      }
                    }
                  },
                  beforeUpload: (file, files) => {
                    setFileList([...fileList, ...files])
                    return false
                  },
                  onChange: async (info: any) => {
                    if (info.file.status === 'removed') {
                      // 如果在待上传列表中找到，则说明当前图片没有上传服务器，可直接删除
                      const index = fileList.findIndex(n => n.uid === info.file.uid);
                      if (!info.file?.deletepath) {
                        const newFileList = fileList.slice();
                        newFileList.splice(index, 1);
                        setFileList(newFileList)
                        return
                      }
                      confirm({
                        title: '确认删除该文件吗？',
                        icon: <ExclamationCircleOutlined />,
                        async onOk() {
                          const deleteLoading = message.loading('正在删除...')
                          const success = await deletePicture(info.file?.deletepath, info.file?.uid, '', '3000')
                          deleteLoading()
                          if (success) {
                            const files = [...fileList]
                            files.splice(index, 1)
                            setFileList(files)
                          }
                          else {
                            message.error("删除失败")
                          }
                        },
                        onCancel() {
                        },
                      });
                    }
                  }
                }}
              />
              {/* 查看文件组件 */}
              <div style={{ display: 'none' }}>
                <Image width={100} height={100} src={priviewImage} style={{ objectFit: "contain", display: 'none' }}
                  preview={{
                    visible: !!priviewImage,
                    onVisibleChange: (value: any) => {
                      if (!value) {
                        setPriviewImage('');
                      }
                    },
                  }} />
              </div>
            </Col>
            <Col span={12}>
              <Descriptions column={1}>
                {
                  relatedContractsList && relatedContractsList.length > 0 ?
                    <Descriptions.Item label="关联合同列表">
                      <div style={{ display: "block" }}>
                        {
                          relatedContractsList.map((item: any) => {
                            return <div style={{ display: 'flex', alignItems: 'center' }}>
                              <span style={{
                                color: '#1890ff',
                                cursor: 'pointer'
                              }} onClick={() => {
                                setChildrenRow(item)
                                setShowChildDetailDrawer(true)
                              }}>{`${item.COMPACT_NAME}(${COMPACTLISTS[item.COMPACT_DETAILS]})`}</span>
                              {
                                item.ATTACHMENT_STATE === 1000 ?
                                  <img
                                    style={{ width: '15px', height: '15px', marginLeft: '15px', cursor: 'pointer' }}
                                    src={fileIcon}
                                    onClick={async () => {
                                      const data = await getPictureList(item.REGISTERCOMPACT_ID, '1115')
                                      const files = data && data?.total > 0 ? data?.data.map((n: PictureModel) => {
                                        return {
                                          uid: n.ImageId,
                                          name: n.ImageName,
                                          status: 'done',
                                          url: n.ImageUrl,
                                          deletepath: n.ImagePath
                                        }
                                      }) : []
                                      setChildrenFile(files)
                                      setShowChildrenFile(true)
                                    }}
                                  /> : ''
                              }
                            </div>
                          })
                        }
                      </div>
                    </Descriptions.Item> : ''
                }
              </Descriptions>
            </Col>
          </Row>
        </Card>

        <Card title={<div className="card-title">合同概况</div>} bordered={false}>
          <Row>
            <Col span={6}>
              <ProFormSelect
                name="COMPACT_TYPE"
                label="合同类型"
                placeholder="请选择合同类型"
                rules={[
                  {
                    required: true,
                    message: '请选择合同类型',
                  },
                ]}
                initialValue={340001}
                request={async () => {
                  const options = session.get("COMPACT_CHARACTERList")
                  return options;
                }}
              />
            </Col>
            <Col span={6}>
              <ProFormSelect
                name="COMPACT_DETAILS"
                label="合同类型子项"
                placeholder="请选择合同类型子项"
                rules={[
                  {
                    required: true,
                    message: '请选择合同类型子项',
                  },
                ]}
                initialValue={1000}
                options={COMPACTLIST}
                addonAfter={showBtn ?
                  <Button type="primary" icon={<FileSearchOutlined />}
                    onClick={() => {
                      setContractVisible(1)
                    }}>选择</Button> :
                  false
                }
                fieldProps={{
                  onChange: (e: any) => {
                    console.log('e', e);
                    if (handleGetContractChild) {
                      handleGetContractChild(e)
                    }
                    if (e !== 1000) {
                      setShowBtn(true)
                    } else {
                      setShowBtn(false)
                    }
                  },
                }}
              />
            </Col>
            <Col span={6}>
              <ProFormSelect
                name="serverpartIds"
                label="合同主体"
                placeholder="请选择合同主体"
                rules={[
                  {
                    required: true,
                    message: '请选择合同主体',
                  },
                ]}
                mode="multiple"
                request={async () => {
                  const options = await getServerpartOption();

                  return options;
                }}
              />
            </Col>
            <Col span={6}>
              <ProFormText
                label="合同编号"
                name="COMPACT_CODE"
                placeholder="请输入合同编号"
              />
            </Col>

            <Col span={12}>
              <ProFormText
                label="合同名称"
                name="COMPACT_NAME"
                placeholder="请输入合同名称"
                rules={[
                  {
                    required: true,
                    message: '请输入合同名称',
                  },
                ]}
                // addonAfter={<Button type="primary">+</Button> }
                wrapperCol={{ span: 21 }}
              >
              </ProFormText>
            </Col>
            <Col span={6}>
              <ProFormSelect
                name="ORGANIZER_TEL"
                label="签订程序"
                placeholder="请选择签订程序"
                // rules={[
                //     {
                //         required: true,
                //         message: '请选择签订程序',
                //     },
                // ]}
                request={async () => {
                  const options = session.get("COMPACTREGPROINSTList");

                  return options;
                }}
              />
            </Col>
            <Col span={6}>
              <ProFormSelect
                name="COMPACT_CHILDTYPE"
                label="合同附属类型"
                placeholder="请选择合同附属类型"
                request={async () => {
                  const options = session.get("COMPACT_CHILDTYPEList")
                  return options;
                }}
                rules={[
                  {
                    required: showDelete,
                    message: '请选择合同附属类型',
                  },
                ]}
              // valueEnum={compactType}
              />
            </Col>
          </Row>
          {/* <div className="from-group-title">甲方信息</div> */}
          <Row>
            <Col span={12}>
              <ProFormText
                label="甲方名称"
                name="FIRSTPART_NAME"
                placeholder="请选择甲方"
                rules={[
                  {
                    required: true,
                    message: '请选择甲方',
                  },
                ]}
                readonly
                addonAfter={<Button type="primary" icon={<FileSearchOutlined />} onClick={() => {
                  openModal("FIRSTPART")

                }}>选择</Button>}
                wrapperCol={{ span: 21 }}
              />
            </Col>
            <Col span={6}>
              <ProFormText
                label="联系人"
                name="FIRSTPART_LINKMAN"
                placeholder="请输入甲方联系人"
              />
            </Col>
            <Col span={6}>
              <ProFormText
                label="联系电话"
                name="FIRSTPART_MOBILE"
                placeholder="请输入甲方联系电话"
              />
            </Col>
          </Row>
          {/* <div className="from-group-title">乙方信息</div> */}
          <Row>
            <Col span={12}>
              <ProFormText
                label="乙方名称"
                name="SECONDPART_NAME"
                placeholder="请选择乙方"
                readonly
                rules={[
                  {
                    required: true,
                    message: '请选择乙方',
                  },
                ]}

                addonAfter={<Button type="primary" icon={<FileSearchOutlined />} onClick={() => {
                  openModal("SECONDPART")

                }}>选择</Button>}
                wrapperCol={{ span: 21 }}
              />
            </Col>
            <Col span={6}>
              <ProFormText
                label="联系人"
                name="SECONDPART_LINKMAN"
                placeholder="请输入乙方联系人"
                rules={[
                  {
                    required: showDelete,
                    message: '请输入乙方联系人',
                  },
                ]}
              />
            </Col>
            <Col span={6}>
              <div style={{ position: 'relative' }}>
                <ProFormText
                  label="联系电话"
                  name="SECONDPART_MOBILE"
                  placeholder="请输入乙方联系电话"
                  rules={[
                    {
                      required: showDelete,
                      message: '请输入乙方联系电话',
                    },
                  ]}
                />
                {
                  showAddPartyC ?
                    // 去除
                    <Button
                      key="new"
                      icon={<MinusOutlined />}
                      type="primary"
                      style={{ position: 'absolute', cursor: 'pointer', bottom: '3px', right: '30px', width: '30px', height: '30px', marginLeft: '8px' }}
                      onClick={() => {
                        setAddPartyC(false)
                      }} /> :
                    // 增加
                    <Button
                      key="new"
                      icon={<PlusOutlined />}
                      type="primary"
                      style={{ position: 'absolute', cursor: 'pointer', bottom: '3px', right: '30px', width: '30px', height: '30px', marginLeft: '8px' }}
                      onClick={() => {
                        setAddPartyC(true)
                      }} />
                }
                {/* <img style={{position:'absolute',cursor:'pointer',bottom:'3px',right:'30px',width:'30px',height:'30px',marginLeft:'8px'}} src={addPartyC} onClick={()=>{ */}
                {/*  setAddPartyC(true)  */}
                {/* }}/> */}
              </div>
            </Col>
          </Row>
          {/* <div className="from-group-title">丙方信息</div> */}
          {
            showAddPartyC ?
              <Row>
                <Col span={12}>
                  <ProFormText
                    readonly
                    label="丙方名称"
                    name="THREEPART_NAME"
                    placeholder="请选择丙方"
                    addonAfter={<Button type="primary" icon={<FileSearchOutlined />} onClick={() => {
                      openModal("THREEPART")

                    }}>选择</Button>}
                    wrapperCol={{ span: 21 }}
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    label="联系人"
                    name="THREEPART_LINKMAN"
                    placeholder="请输入丙方联系人"
                  />
                </Col>
                <Col span={6}>
                  <ProFormText
                    label="联系电话"
                    name="THREEPART_MOBILE"
                    placeholder="请输入丙方联系电话"
                  />
                </Col>
              </Row>
              : ''
          }
        </Card>
        <Card title={<div className="card-title">合同要素</div>} bordered={false} style={{ marginTop: 24 }}>
          <Row>
            <Col span={6}>
              <ProFormDateRangePicker
                label="合同生效时间"
                name="contractRangeDate"
                // rules={[
                //   {
                //     required: true,
                //     message: '请选择合同生效时间',
                //   },
                // ]}
                fieldProps={{
                  onChange: async (dates) => {
                    if (dates && dates[0] && dates[1]) {
                      const longOfDate = moment.duration(dates[1].diff(dates[0]))
                      const compactDays = longOfDate.asDays()
                      const compactYears = longOfDate.asYears()

                      formRef.current?.setFieldsValue({ DURATIONDAY: compactDays, DURATION: Math.ceil(compactYears) })
                    }
                  }
                }}
              />
            </Col>
            <Col span={6}>
              <ProFormDigit
                label="合同期限"
                name="DURATIONDAY"
                addonAfter='天'

                placeholder="请输入"
              />
            </Col>
            <Col span={6}>
              <ProFormDigit
                label="合同年限"
                addonAfter='年'

                name="DURATION"
                placeholder="请输入"
              />
            </Col>
            <Col span={6}>
              <ProFormDigit
                label="续签年限"
                addonAfter='年'
                name="RENEWAL_YEARS"
                placeholder="请输入"
              />
            </Col>
          </Row>
          <Row>
            <Col span={6}>
              <ProFormDateRangePicker
                label="门店装修日期"
                name="contractDecorateRangeDate"
              // rules={[
              //   {
              //     required:true,
              //     message:'请输入门店装修日期'
              //   }
              // ]}
              />
            </Col>
            <Col span={6}>
              <ProFormDateRangePicker
                label="免租日期"
                name="contractRentrfreeRangeDate"
              />
            </Col>
            <Col span={6}>
              <ProFormDigit
                label="工程保修期限"
                name="REPAIR_TIME"
                addonAfter='天'
                placeholder="请输入工程保修期限"
              />
            </Col>
          </Row>
          <Row>
            <Col span={6}>
              <ProFormDigit
                label="合同金额"
                name="COMPACT_AMOUNT"
                addonAfter="万元"
                placeholder="请输入合同金额"
                rules={[
                  {
                    required: true,
                    message: '请输入合同金额',
                  },
                ]}
              />
            </Col>
            {/* <Col span={6}>
                            <ProFormDatePicker
                                label="应到账日期"
                                name="COMPACT_ACCOUNTDATE"
                                width="md"
                                placeholder="请输入到账日期"
                            />
                        </Col>
                        <Col span={6} />
                    </Row>
                    <Row> */}
            <Col span={6}>
              <ProFormDigit
                label="履约保证金"
                name="SECURITYDEPOSIT"
                addonAfter='万元'
                placeholder="请输入履约保证金"
                rules={[
                  {
                    required: true,
                    message: '请输入履约保证金',
                  },
                ]}
              />
            </Col>
            {/* <Col span={6}>
                            <ProFormDatePicker
                                label="到账日期"
                                name="SECURITYDEPOSIT_STARTDATE"
                                width="md"
                                placeholder="请选择到账日期"
                            />
                        </Col>
                        <Col span={6}>
                            <ProFormDatePicker
                                label="退款日期"
                                name="SECURITYDEPOSIT_ENDDATE"
                                width="md"
                                placeholder="请选择退款日期"
                            />
                        </Col> */}
          </Row>
          <Row>
            <Col span={6}>
              <ProFormSelect
                valueEnum={contractType}
                name="BUSINESS_TYPE"
                label="经营模式"
                placeholder="请选择经营模式"
                rules={[
                  {
                    required: true,
                    message: '请选择经营模式',
                  },
                ]}
              />
            </Col>
            <Col span={6}>
              <ProFormSelect
                name="SETTLEMENT_MODES"
                label="结算模式"
                placeholder="请选择结算模式"
                rules={[
                  {
                    required: true,
                    message: '请选择结算模式',
                  },
                ]}
                request={async () => {
                  const options = session.get("SETTLEMENT_MODESList")

                  return options;
                }}
              />
            </Col>
            <Col span={6}>
              <ProFormSelect
                name="SETTLEMENT_CYCLE"
                label="结算周期"
                placeholder="请选择结算周期"
                request={async () => {
                  const options = session.get("SETTLEMENT_CYCLEList")

                  return options;
                }}
              // rules={[
              //     {
              //         required: true,
              //         message: '请选择结算周期',
              //     },
              // ]}
              />
            </Col>
            <Col span={6}>
              <ProFormSelect
                label="所属区域"
                name="SERVERPARTREGION"
                mode="multiple"
                placeholder="请选择所属区域"
                options={
                  [
                    {
                      value: '15',
                      label: '东区',
                    },
                    {
                      value: '20',
                      label: '南区',
                    },
                    {
                      value: '35',
                      label: '西区',
                    },
                    {
                      value: '40',
                      label: '北区',
                    },
                  ]
                }
              />
            </Col>
          </Row>
          <Row>
            <Col span={6}>
              <ProFormSelect
                valueEnum={severpartType}
                name="SERVERPART_TYPE"
                label="服务区类型"
                placeholder="请选择服务区类型"
                fieldProps={{
                  onChange: (value) => {
                    const coast = calcServiceCoast(value, formRef.current?.getFieldValue('BUSINESS_TRADE'))
                    formRef.current?.setFieldsValue({ PROPERTY_FEE: coast * formRef.current?.getFieldValue('OPERATING_AREA') })
                  }
                }}
                rules={[
                  {
                    required: showDelete,
                    message: '请选择服务区类型',
                  },
                ]}
              />
            </Col>
            <Col span={6}>
              <ProFormSelect
                valueEnum={businessType}
                name="BUSINESS_TRADE"
                label="经营业态"
                placeholder="请选择经营业态"
                fieldProps={{
                  onChange: (value) => {
                    const coast = calcServiceCoast(formRef.current?.getFieldValue('SERVERPART_TYPE'), value)
                    formRef.current?.setFieldsValue({ PROPERTY_FEE: coast * formRef.current?.getFieldValue('OPERATING_AREA') })
                  }
                }}
                rules={[
                  {
                    required: true,
                    message: '请选择经营业态',
                  },
                ]}
              />
            </Col>
            <Col span={6} style={{ display: 'none' }}>
              <ProFormText label="经营品牌" name="BUSINESS_BRAND" />
              {/* <ProFormText
                                label="经营品牌"
                                name="BRAND_NAME"
                                placeholder="请选择经营品牌"
                                addonAfter={<Button type="primary" icon={<FileSearchOutlined />} onClick={() => {
                                    setBrandVisible(true)
                                }}></Button>}
                            /> */}
            </Col>
            <Col span={6}>
              <ProFormDigit
                label="经营面积"
                name="OPERATING_AREA"
                fieldProps={{
                  addonAfter: '㎡',
                  onChange: (value) => {
                    const numberValue = Number(value)
                    const coast = calcServiceCoast(formRef.current?.getFieldValue('SERVERPART_TYPE'), formRef.current?.getFieldValue('BUSINESS_TRADE'))
                    formRef.current?.setFieldsValue({ PROPERTY_FEE: numberValue ? coast * numberValue : 0 })
                  }
                }}
                placeholder="请输入经营面积"
                rules={[
                  {
                    required: showDelete,
                    message: '请输入经营面积',
                  },
                ]}
              />
            </Col>
            <Col span={6}>
              <ProFormDigit
                label="物业费"
                name="PROPERTY_FEE"
                addonAfter='元/月'
                placeholder="请输入物业费"
              />
            </Col>
          </Row>
          <Row>
            <Col span={6}>
              <ProFormDigit
                label="设备押金"
                name="EQUIPMENT_DEPOSIT"
                addonAfter='元'
                placeholder="请输入设备押金"
              />
            </Col>
            <Col span={6}>
              <ProFormDigit
                label="水费"
                name="WATER_CHARGE"
                addonAfter='元/吨'
                placeholder="请输入水费"
              />
            </Col>
            <Col span={6}>
              <ProFormDigit
                label="电费"
                name="ELECTRICITY_FEES"
                addonAfter='元/度'
                placeholder="请输入电费"
              />
            </Col>
            <Col span={6}>
              <ProFormText
                label="其他费用"
                name="OTHER_SCHARGE"
                placeholder="请输入其他费用"
              />

            </Col>
          </Row>

          {/* <Row>
                        <Col span={6}>
                            <ProFormDigit
                                label="安全风险抵押金"
                                name="SAFETYRISKMORTGAGE"
                                addonAfter='万元'

                                placeholder="请输入安全风险抵押金"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入安全风险抵押金',
                                    },
                                ]}
                            />
                        </Col>
                        <Col span={6}>
                            <ProFormDatePicker
                                label="到账日期"
                                name="SAFETYRISKMORTGAGE_STARTDATE"
                                width="md"
                                placeholder="请输入到账日期"
                            />
                        </Col>
                        <Col span={6}>
                            <ProFormDatePicker
                                label="退款日期"
                                name="SAFETYRISKMORTGAGE_ENDDATE"
                                placeholder="请选择退款日期"
                                width="md"
                            />
                        </Col>
                    </Row> */}
        </Card>
        {/* <Card title={<div className="card-title">经营约束</div>} bordered={false} style={{ marginTop: 24 }}> */}
        {/*      */}

        {/* </Card> */}
        <Card title={<div className="card-title">合同说明</div>} style={{ marginTop: 24 }}>
          <Row>
            <Col span={12}>
              <ProFormTextArea
                label="经营范围"
                name="OPERATING_SCOPE"
                fieldProps={{
                  autoSize: { minRows: 1, maxRows: 6 },
                }}
                wrapperCol={{ span: 21 }}
                placeholder="请输入经营范围"
                rules={[
                  {
                    // required: showDelete,
                    required: true,
                    message: '请输入经营范围',
                  },
                ]}
              />
            </Col>
            <Col span={12}>
              <ProFormTextArea
                label="经营场地"
                fieldProps={{
                  autoSize: { minRows: 1, maxRows: 6 },
                }}
                name="OPERATING_SITE"
                wrapperCol={{ span: 21 }}
                placeholder="请输入经营场地"
              // rules={[
              //     {
              //         required: true,
              //         message: '请输入经营场地',
              //     },
              // ]}
              />
            </Col>
          </Row>

          <Row>
            <Col span={12}>
              <ProFormTextArea
                label="合同注意事项"
                name="COMPACT_DPDESC"
                fieldProps={{
                  autoSize: { minRows: 1, maxRows: 6 },
                }}
                placeholder="请输入合同注意事项"
                wrapperCol={{ span: 21 }}
              />
            </Col>
            <Col span={12}>
              <ProFormTextArea
                label="招商依据"
                name="COMPACT_BASIS"
                fieldProps={{
                  autoSize: { minRows: 1, maxRows: 6 },
                }}
                placeholder="请输入招商依据"
                wrapperCol={{ span: 21 }}

              />
            </Col>
            <Col span={6}>
              <ProFormText
                label="操作员"
                name="STAFF_NAME"
                disabled
                placeholder="请输入操作员"
              />
            </Col>
            <Col span={6}>
              <ProFormDateTimePicker
                disabled
                label="更新时间"
                name="OPERATE_DATE"
                placeholder="更新时间"
                width="md"
              />
            </Col>
          </Row>
        </Card>
      </ProForm>

      <Modal visible={visible}
        title="请选择商户"
        width={selectName !== 'FIRSTPART' ? 1224 : 1024}

        onOk={() => {
          setVisible(false)
          const name = `${selectName}_NAME`
          const linkman = `${selectName}_LINKMAN`
          const mobile = `${selectName}_MOBILE`
          const sid = `${selectName}_ID`
          const data = {
            [name]: company?.COOPMERCHANTS_NAME,
            [linkman]: selectName !== 'FIRSTPART' ? company?.COOPMERCHANTS_LINKMAN : company?.LINKER_NAME,
            [mobile]: selectName !== 'FIRSTPART' ? company?.COOPMERCHANTS_MOBILEPHONE : company?.LINKER_MOBILEPHONE,
            [sid]: company?.COOPMERCHANTS_ID
          }

          if (fields) {
            fields[sid] = company?.COOPMERCHANTS_ID
            setFields({ ...fields })
          } else {
            setFields({ ...data })
          }
          formRef.current?.setFieldsValue(data)
        }}
        onCancel={() => setVisible(false)}

        bodyStyle={{ padding: 0 }}
      >
        <Row>
          {!loading && selectName !== 'FIRSTPART' && <Col span={5}>

            <Menu
              mode="inline"
              style={{ height: 610, overflowY: 'auto', overflowX: 'hidden' }}
              onSelect={(item) => {
                searchBusiness(item)
              }}
              selectedKeys={selectedKeys}
            >{getMenuDom(busiessBrand, searchBusiness)}</Menu>
          </Col>
          }
          <Col span={selectName !== 'FIRSTPART' ? 19 : 24}>
            {visible && <ProTable<MerchantModel>
              rowKey={selectName !== "FIRSTPART" ? "RTCOOPMERCHANTS_ID" : "COOPMERCHANTS_ID"}
              size="small"
              columns={[
                {
                  dataIndex: 'COOPMERCHANTS_NAME',
                  title: '商户名称',
                },
                {
                  dataIndex: 'LINKER_NAME',
                  title: '联系人',
                  hideInSearch: true,
                  hideInTable: selectName !== 'FIRSTPART',
                },
                {
                  dataIndex: 'LINKER_MOBILEPHONE',
                  title: '联系方式',
                  hideInSearch: true,
                  hideInTable: selectName !== 'FIRSTPART',
                },
                {
                  dataIndex: 'BUSINESSTRADE_NAME',
                  title: '经营业态',
                  hideInSearch: true,
                  hideInTable: selectName === 'FIRSTPART',
                },
                {
                  dataIndex: 'BRAND_NAME',
                  title: '品牌',
                  hideInSearch: true,
                  hideInTable: selectName === 'FIRSTPART',
                },
                {
                  dataIndex: 'COOPMERCHANTS_LINKMAN',
                  title: '联系人',
                  hideInSearch: true,
                  hideInTable: selectName === 'FIRSTPART',
                },
                {
                  dataIndex: 'COOPMERCHANTS_MOBILEPHONE',
                  title: '联系方式',
                  hideInSearch: true,
                  hideInTable: selectName === 'FIRSTPART',
                },
              ]}

              request={async (params) => {

                if (selectName === 'FIRSTPART') {
                  const data = await getMerchatsList({
                    COOPMERCHANTS_STATE: 1,
                    MERCHANTTYPE_ID: 2000, pagesize: params.pageSize, current: params.current,
                    keyWord: params.COOPMERCHANTS_NAME ? { value: params.COOPMERCHANTS_NAME, key: 'COOPMERCHANTS_NAME' } : null
                  })
                  return data
                }
                if (selectName !== '') {
                  const data = await getBusinessMerchatsList({
                    ...currenMenu, pagesize: params.pageSize, current: params.current,
                    keyWord: params.COOPMERCHANTS_NAME ? { value: params.COOPMERCHANTS_NAME, key: 'COOPMERCHANTS_NAME' } : null
                  })
                  return data
                }

                return { data: [], success: true }
              }}
              defaultData={[]}
              search={{ span: 12 }}
              defaultSize="small"

              pagination={{ defaultPageSize: 10, size: 'small', showSizeChanger: false }}
              onReset={() => {
                setCurrenMenu({})
                compayActionRef.current?.reload()
              }}
              options={false}
              style={{ minHeight: 580 }}
              actionRef={compayActionRef}
              rowSelection={{
                type: "radio",
                onChange: (_, selectedRows) => {
                  // setSelectedRowKeys(selectedRowKeys)

                  setCompany(selectedRows[0])
                }
              }}
              tableAlertRender={false}
            >
            </ProTable>}
          </Col>
        </Row>
      </Modal>
      {/* 选择合同或门店的弹出框 */}
      <Modal visible={contractVisible === 1} // 弹出框状态不为0时，显示弹出框
        title={
          <div
            style={{
              width: '100%',
              cursor: 'move',
            }}
            onMouseOver={() => {
              if (disabled) {
                setDraggleDisabled(false)
              }
            }}
            onMouseOut={() => {
              setDraggleDisabled(true)
            }}

            onFocus={() => { }}
            onBlur={() => { }}
          >
            {contractVisible === 1 ? '请选择合同进行关联' : '请选择门店进行关联'}
          </div>
        }
        destroyOnClose={true}
        width={1400}
        confirmLoading={confirmLoading}
        onOk={async () => { // 弹出框点击确认按钮时的回调方法
          setContractId(contract?.REGISTERCOMPACT_ID)
          setContractVisible(0)
          if (showType === 'add') {
            // 调用合同详情 默认帮选上更多
            handleConfirmLoading(true)
            const data = await handleGetRegisterCompactDetail({ RegisterCompactId: contract?.REGISTERCOMPACT_ID })
            console.log('contract', contract);
            console.log('data', data);
            handleConfirmLoading(false)
            let serverpartList: any = []
            if (contract?.SERVERPART_IDS) {
              let list: any = contract?.SERVERPART_IDS.split(',')
              if (list && list.length > 0) {
                list.forEach((item: any) => {
                  serverpartList.push(Number(item))
                })
              }
            }
            formRef.current?.setFieldsValue({
              serverpartIds: serverpartList,
              COMPACT_CODE: data?.COMPACT_CODE,
              COMPACT_NAME: data?.COMPACT_NAME,
              ORGANIZER_TEL: data?.ORGANIZER_TEL,
              FIRSTPART_NAME: data?.FIRSTPART_NAME,
              FIRSTPART_LINKMAN: data?.FIRSTPART_LINKMAN,
              FIRSTPART_MOBILE: data?.FIRSTPART_MOBILE,
              SECONDPART_NAME: data?.SECONDPART_NAME,
              SECONDPART_LINKMAN: data?.SECONDPART_LINKMAN,
              SECONDPART_MOBILE: data?.SECONDPART_MOBILE,
              THREEPART_NAME: data?.THREEPART_NAME,
              THREEPART_LINKMAN: data?.THREEPART_LINKMAN,
              THREEPART_MOBILE: data?.THREEPART_MOBILE,
              DURATIONDAY: data?.DURATIONDAY,
              DURATION: data?.DURATION,
              RENEWAL_YEARS: data?.RENEWAL_YEARS,
              COMPACT_AMOUNT: data?.COMPACT_AMOUNT,
              SECURITYDEPOSIT: data?.SECURITYDEPOSIT,
              BUSINESS_TYPE: contract?.BUSINESS_TYPE?.toString(),
              SETTLEMENT_MODES: contract?.SETTLEMENT_MODES,
              SETTLEMENT_CYCLE: contract?.SETTLEMENT_CYCLE,
            })
          }
        }}
        onCancel={() => { // 点击弹出框关闭按钮时，重置弹出框弹出状态
          setContractVisible(0)
          // setContract(undefined)
        }}
        afterClose={() => {

        }}
        modalRender={(modal) => {
          return <Draggable
            disabled={disabled}
            bounds={bounds}
            onStart={(event, uiData) => onDraggaleStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        }}
        bodyStyle={{ padding: 0 }}
      >
        {/* contractVisible 为1 时，表示弹出框内容为 合同列表数据 */}
        {contractVisible === 1 && <Row>
          <Col span={5}>
            {/* 弹出框左侧服务区菜单 */}
            {
              !serverPartLoading &&  // 当服务区数据请求完成时渲染 菜单节点集
              <Menu
                mode="inline"
                style={{ height: 605, overflowY: 'auto', overflowX: 'hidden' }}
                selectedKeys={[serverpartId || '']}
                onSelect={async (item) => { // 点击子级菜单时 将菜单id (服务区id) 存起来
                  setShopId(null)
                  if (item.key) {
                    setServerpartId(item.key)
                    const req = {
                      ProvinceCode: '340000',
                      ServerpartId: item.key,
                      ShowWholePower: true
                    }
                    const data = await handleGetServiceShopList(req)
                    setShopList(data.List)
                  } else {
                    setShopList([])
                  }
                }}
              >
                <Menu.Item key="">全部</Menu.Item>{
                  getMenuDomModal(serverpartTree || []) // 函数返回菜单节点集
                }
              </Menu>
            }
          </Col>
          {/* 合同列表 */}
          <Col span={19}>
            <ProTable<ContractListModel> // 合同表格主体
              rowKey="REGISTERCOMPACT_ID"
              size="small"
              columns={compactColumns}
              request={async (params, sorter) => { // 请求表格数据的方法
                const sortstr = Object.keys(sorter).map(n => {
                  const value = sorter[n]
                  return value ? `${n} ${value.replace('end', '')}` : ''

                })
                if (contractVisible) { // 如果是合同选择弹出窗时 请求合同表格数据 ...params,
                  const data = await getContractList({
                    searchParameter: { SERVERPART_IDS: params.SERVERPART_IDS, COMPACT_STATE: 1000, current: 1, SERVERPARTSHOP_IDS: shopId, COMPACT_DETAILS: 1000 },
                    sortstr: sortstr.toString(), pagesize: 999,
                    keyWord: params.COMPACT_NAME ? { value: params.COMPACT_NAME, key: 'COMPACT_NAME' } : null
                  })
                  return data
                }
                return { data: [], success: true }
              }}
              params={{ SERVERPART_IDS: serverpartId || '' }} // 查询合同表格默认参数
              search={{ span: 8 }}
              pagination={{ defaultPageSize: 10, size: 'small' }}
              onReset={() => { // 表格查询栏 点击重置按钮时 清空存储的服务区id并刷新查询表格
                setServerpartId('')
                contractActionRef.current?.reload() // 调用 合同表格操作对象进行刷新
              }}
              options={false}
              style={{ minHeight: 580 }}
              actionRef={contractActionRef}
              formRef={contractFormRef}
              rowSelection={{ // 可选择的表格配置
                type: "radio", // 该表格为单选
                onChange: (selectedRowKeys, selectedRows) => {
                  // 选中行发生改变时，存储选中行的数据
                  setContract(selectedRows[0])
                }
              }}
              tableAlertRender={false} // 关闭 选中行时的弹出提示
            >
            </ProTable>
          </Col>
        </Row>}
      </Modal>




      <Modal visible={brandVisible}
        title="请选择经营业态和品牌"
        width={1024}

        onOk={() => {
          setBrandVisible(false)

          const data = {
            BUSINESS_BRAND: brand?.BRAND_ID,
            BRAND_NAME: brand?.BRAND_NAME,
          }

          formRef.current?.setFieldsValue(data)
        }}
        onCancel={() => {
          setBrandVisible(false)
          setBrand(undefined)
        }}
        afterClose={() => {
          setCurrenMenu({})
          brandActionRef.current?.reset()
        }}
        bodyStyle={{ padding: 0 }}
      >
        <Row>
          <Col span={6}>
            {
              <Menu
                mode="inline"
                style={{ height: 610, overflowY: 'auto', overflowX: 'hidden' }}
                selectedKeys={selectedKeys}
                onSelect={(item) => {
                  searchBrand(item)
                }}
              >{getMenuDom(busiessBrand, searchBrand, true)}
              </Menu>
            }
          </Col>
          <Col span={18}>
            <ProTable<BrandModel>
              rowKey="BRAND_ID"
              size="small"
              columns={[
                {
                  dataIndex: 'BRAND_INTRO',
                  hideInSearch: true,
                  width: 48,
                  render: (_, record) => {
                    return <Avatar src={_} size={24}>{record.BRAND_NAME.substring(0, 1)}</Avatar>
                  },
                  hideInDescriptions: true,
                },
                {
                  dataIndex: 'BRAND_NAME',
                  title: '品牌名称',
                  hideInSearch: true
                },

                {
                  dataIndex: 'keyWord',
                  title: '品牌名称',
                  hideInTable: true
                  // hideInSearch: true
                },

              ]}

              request={async (params) => {
                if (brandVisible) {
                  const data = await getBrandList({
                    ...params,
                    keyWord: params.keyWord ? { value: params.keyWord, key: 'BRAND_NAME' } : null
                  })
                  return data
                }
                return { data: [], success: true }
              }}
              params={currenMenu}
              search={{ span: 12, }}
              pagination={{ defaultPageSize: 10, size: 'small', showSizeChanger: false }}
              onReset={() => {
                setCurrenMenu({})
                brandActionRef.current?.reload()
              }}
              options={false}
              style={{ minHeight: 610 }}
              actionRef={brandActionRef}
              rowSelection={{

                type: "radio",
                onChange: (selectedRowKeys, selectedRows) => {

                  setBrand(selectedRows[0])
                }

              }}
              tableAlertRender={false}
            >

            </ProTable>
          </Col>
        </Row>
      </Modal>
      {/*  关联合同的详情抽屉 */}
      <Drawer
        width="73%"
        visible={showChildDetailDrawer}
        onClose={() => {
          setShowChildDetailDrawer(false)
          setChildrenRow(undefined)
        }}
        destroyOnClose
        title={'关联合同详情'}
        closable={false}
        bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
      >
        <ContractDetail contractId={childrenRow?.REGISTERCOMPACT_ID} />
      </Drawer>
      {/* 显示关联合同附件 */}
      <Modal
        title={'关联合同附件'}
        open={showChildrenFile}
        onCancel={() => {
          setShowChildrenFile(false)
        }}
        footer={() => { }}
      >
        <Upload
          defaultFileList={childrenFile || []}
          showUploadList={{
            showDownloadIcon: false,
            showRemoveIcon: false,
          }}
        />
      </Modal>
    </PageContainer>
  );
};

// export default connect(({ user }: ConnectState) => ({
//     currentUser: user.currentUser
// }))(EditContract);
export default EditContract
