<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nbport.zgwl.contractlaunch.mapper.ContractLaunchMapper">

    <resultMap id="ContractLaunchResult" type="com.nbport.zgwl.contractlaunch.dto.ContractLaunchDto">
        <id property="id" column="ID"/>
        <result property="contractSysId" column="CONTRACT_SYS_ID"/>
        <result property="contractCode" column="CONTRACT_CODE"/>
        <result property="lawContractCode" column="LAW_CONTRACT_CODE"/>
        <result property="lawContractId" column="LAW_CONTRACT_ID"/>
        <result property="contractName" column="CONTRACT_NAME"/>
        <result property="contractType" column="CONTRACT_TYPE"/>
        <result property="contractTypeCode" column="CONTRACT_TYPE_CODE"/>
        <result property="contractSource" column="CONTRACT_SOURCE"/>
        <result property="creationMode" column="CREATION_MODE"/>
        <result property="templateId" column="TEMPLATE_ID"/>
        <result property="templateCode" column="TEMPLATE_CODE"/>
        <result property="templateName" column="TEMPLATE_NAME"/>
        <result property="status" column="STATUS"/>
        <result property="approveStatus" column="APPROVE_STATUS"/>
        <result property="approveMessage" column="APPROVE_MESSAGE"/>
        <result property="sealContractId" column="SEAL_CONTRACT_ID"/>
        <result property="sealContractStatus" column="SEAL_CONTRACT_STATUS"/>
        <result property="contractAmount" column="CONTRACT_AMOUNT"/>
        <result property="currencyName" column="CURRENCY_NAME"/>
        <result property="contractPeriodType" column="CONTRACT_PERIOD_TYPE"/>
        <result property="periodExplain" column="PERIOD_EXPLAIN"/>
        <result property="effectiveStart" column="EFFECTIVE_START"/>
        <result property="effectiveEnd" column="EFFECTIVE_END"/>
        <result property="paymentMethod" column="PAYMENT_METHOD"/>
        <result property="primaryContent" column="PRIMARY_CONTENT"/>
        <result property="amountExplain" column="AMOUNT_EXPLAIN"/>
        <result property="valuationMode" column="VALUATION_MODE"/>
        <result property="needAmendments" column="NEED_AMENDMENTS"/>
        <result property="estimatedAmount" column="ESTIMATED_AMOUNT"/>
        <result property="sealType" column="SEAL_TYPE"/>
        <result property="sealQuantity" column="SEAL_QUANTITY"/>
        <result property="textSource" column="TEXT_SOURCE"/>
        <result property="mandateType" column="MANDATE_TYPE"/>
        <result property="cargoType" column="CARGO_TYPE"/>
        <result property="assistDepartmentName" column="ASSIST_DEPARTMENT_NAME"/>
        <result property="executorAccount" column="EXECUTOR_ACCOUNT"/>
        <result property="creatorPhone" column="CREATOR_PHONE"/>
        <result property="selfCode" column="SELF_CODE"/>
        <result property="mainContractCode" column="MAIN_CONTRACT_CODE"/>
        <result property="signingSubjectCode" column="SIGNING_SUBJECT_CODE"/>
        <result property="dateType" column="DATE_TYPE"/>
        <result property="isAddit" column="IS_ADDIT"/>
        <result property="isElectron" column="IS_ELECTRON"/>
        <result property="paymentDirection" column="PAYMENT_DIRECTION"/>
        <result property="pushUrl" column="PUSH_URL"/>
        <result property="isMajorContract" column="IS_MAJOR_CONTRACT"/>
        <result property="isOpenBidding" column="IS_OPEN_BIDDING"/>
        <result property="isYearBudget" column="IS_YEAR_BUDGET"/>
        <result property="isShare" column="IS_SHARE"/>
        <result property="contractNature" column="CONTRACT_NATURE"/>
        <result property="isSgat" column="IS_SGAT"/>
        <result property="isNormal" column="IS_NORMAL"/>
        <result property="isTerminated" column="IS_TERMINATED"/>
        <result property="isSingleAgreement" column="IS_SINGLE_AGREEMENT"/>
        <result property="biddingNo" column="BIDDING_NO"/>
        <result property="openBiddingRemark" column="OPEN_BIDDING_REMARK"/>
        <result property="contractGistRemark" column="CONTRACT_GIST_REMARK"/>
        <result property="ewAmountType" column="EW_AMOUNT_TYPE"/>
        <result property="djAmount" column="DJ_AMOUNT"/>
        <result property="yjAmount" column="YJ_AMOUNT"/>
        <result property="yfkAmount" column="YFK_AMOUNT"/>
        <result property="bzjAmount" column="BZJ_AMOUNT"/>
        <result property="bodySummary" column="BODY_SUMMARY"/>
        <result property="templateFieldValuesJson" column="TEMPLATE_FIELD_VALUES_JSON"/>
        <result property="contractTextFileName" column="CONTRACT_TEXT_FILE_NAME"/>
        <result property="contractTextFilePath" column="CONTRACT_TEXT_FILE_PATH"/>
        <result property="contractTextFileType" column="CONTRACT_TEXT_FILE_TYPE"/>
        <result property="contractTextFileSize" column="CONTRACT_TEXT_FILE_SIZE"/>
        <result property="signedFileName" column="SIGNED_FILE_NAME"/>
        <result property="signedFilePath" column="SIGNED_FILE_PATH"/>
        <result property="signedFileType" column="SIGNED_FILE_TYPE"/>
        <result property="signedFileSize" column="SIGNED_FILE_SIZE"/>
        <result property="signedFileUrl" column="SIGNED_FILE_URL"/>
        <result property="signedOfflineReason" column="SIGNED_OFFLINE_REASON"/>
        <result property="signDate" column="SIGN_DATE"/>
        <result property="sealDate" column="SEAL_DATE"/>
        <result property="sealIsSeal" column="SEAL_IS_SEAL"/>
        <result property="sealApproveSame" column="SEAL_APPROVE_SAME"/>
        <result property="activeDate" column="ACTIVE_DATE"/>
        <result property="archiveDate" column="ARCHIVE_DATE"/>
        <result property="archiveReceiveDept" column="ARCHIVE_RECEIVE_DEPT"/>
        <result property="archiveTransferor" column="ARCHIVE_TRANSFEROR"/>
        <result property="archiveKeeper" column="ARCHIVE_KEEPER"/>
        <result property="archiveKeeperUnit" column="ARCHIVE_KEEPER_UNIT"/>
        <result property="archiveKeeperUnitCode" column="ARCHIVE_KEEPER_UNIT_CODE"/>
        <result property="invoiceDate" column="INVOICE_DATE"/>
        <result property="receiveDate" column="RECEIVE_DATE"/>
        <result property="remindDays" column="REMIND_DAYS"/>
        <result property="initiator" column="INITIATOR"/>
        <result property="initiatorDept" column="INITIATOR_DEPT"/>
        <result property="companyName" column="COMPANY_NAME"/>
        <result property="orgId" column="ORG_ID"/>
        <result property="queryScope" column="QUERY_SCOPE"/>
        <result property="createBy" column="CREATE_BY"/>
        <result property="createTime" column="CREATE_TIME"/>
        <result property="updateBy" column="UPDATE_BY"/>
        <result property="updateTime" column="UPDATE_TIME"/>
        <result property="isDeleted" column="IS_DELETED"/>
        <result property="remark" column="REMARK"/>
    </resultMap>

    <resultMap id="PartyResult" type="com.nbport.zgwl.contractlaunch.dto.ContractLaunchPartyDto">
        <id property="id" column="ID"/>
        <result property="contractId" column="CONTRACT_ID"/>
        <result property="roleCode" column="ROLE_CODE"/>
        <result property="roleName" column="ROLE_NAME"/>
        <result property="subjectCode" column="SUBJECT_CODE"/>
        <result property="sortOrder" column="SORT_ORDER"/>
        <result property="partnerId" column="PARTNER_ID"/>
        <result property="oppositeId" column="OPPOSITE_ID"/>
        <result property="companyName" column="COMPANY_NAME"/>
        <result property="companyType" column="COMPANY_TYPE"/>
        <result property="oppositeCharacter" column="OPPOSITE_CHARACTER"/>
        <result property="contactName" column="CONTACT_NAME"/>
        <result property="contactPhone" column="CONTACT_PHONE"/>
        <result property="contactEmail" column="CONTACT_EMAIL"/>
        <result property="contactAddress" column="CONTACT_ADDRESS"/>
        <result property="registeredAddress" column="REGISTERED_ADDRESS"/>
        <result property="legalRepresentative" column="LEGAL_REPRESENTATIVE"/>
        <result property="creditCode" column="CREDIT_CODE"/>
        <result property="bankName" column="BANK_NAME"/>
        <result property="bankAccount" column="BANK_ACCOUNT"/>
        <result property="naturalPersonIdType" column="NATURAL_PERSON_ID_TYPE"/>
        <result property="naturalPersonIdNumber" column="NATURAL_PERSON_ID_NUMBER"/>
        <result property="isGroupInternal" column="IS_GROUP_INTERNAL"/>
        <result property="isHongKongMacaoTaiwan" column="IS_HONG_KONG_MACAO_TAIWAN"/>
        <result property="remark" column="REMARK"/>
    </resultMap>

    <resultMap id="FileResult" type="com.nbport.zgwl.contractlaunch.dto.ContractLaunchFileDto">
        <id property="id" column="ID"/>
        <result property="contractId" column="CONTRACT_ID"/>
        <result property="fileCategory" column="FILE_CATEGORY"/>
        <result property="archiveEleId" column="ARCHIVE_ELE_ID"/>
        <result property="fileName" column="FILE_NAME"/>
        <result property="filePath" column="FILE_PATH"/>
        <result property="legalFileUrl" column="LEGAL_FILE_URL"/>
        <result property="fileType" column="FILE_TYPE"/>
        <result property="fileSize" column="FILE_SIZE"/>
        <result property="sortOrder" column="SORT_ORDER"/>
        <result property="remark" column="REMARK"/>
    </resultMap>

    <resultMap id="ArchivePaperResult" type="com.nbport.zgwl.contractlaunch.dto.ContractLaunchArchivePaperDto">
        <id property="id" column="ID"/>
        <result property="contractId" column="CONTRACT_ID"/>
        <result property="archivesName" column="ARCHIVES_NAME"/>
        <result property="archivesNum" column="ARCHIVES_NUM"/>
        <result property="archivesTime" column="ARCHIVES_TIME"/>
        <result property="sortOrder" column="SORT_ORDER"/>
        <result property="remark" column="REMARK"/>
    </resultMap>

    <resultMap id="ArchiveEleResult" type="com.nbport.zgwl.contractlaunch.dto.ContractLaunchArchiveEleDto">
        <id property="id" column="ID"/>
        <result property="contractId" column="CONTRACT_ID"/>
        <result property="archivesName" column="ARCHIVES_NAME"/>
        <result property="sortOrder" column="SORT_ORDER"/>
        <result property="remark" column="REMARK"/>
    </resultMap>

    <resultMap id="PlanResult" type="com.nbport.zgwl.contractlaunch.dto.ContractLaunchPlanDto">
        <id property="id" column="ID"/>
        <result property="contractId" column="CONTRACT_ID"/>
        <result property="planMatter" column="PLAN_MATTER"/>
        <result property="planWhere" column="PLAN_WHERE"/>
        <result property="planTime" column="PLAN_TIME"/>
        <result property="planDay" column="PLAN_DAY"/>
        <result property="planMoney" column="PLAN_MONEY"/>
        <result property="planSubjectCode" column="PLAN_SUBJECT_CODE"/>
        <result property="planSubjectName" column="PLAN_SUBJECT_NAME"/>
        <result property="planDetail" column="PLAN_DETAIL"/>
        <result property="planStatus" column="PLAN_STATUS"/>
        <result property="remark" column="REMARK"/>
    </resultMap>

    <resultMap id="LogResult" type="com.nbport.zgwl.contractlaunch.dto.ContractLaunchLogDto">
        <id property="id" column="ID"/>
        <result property="contractId" column="CONTRACT_ID"/>
        <result property="actionType" column="ACTION_TYPE"/>
        <result property="actionName" column="ACTION_NAME"/>
        <result property="actionStatus" column="ACTION_STATUS"/>
        <result property="operatorName" column="OPERATOR_NAME"/>
        <result property="operatorPhone" column="OPERATOR_PHONE"/>
        <result property="actionTime" column="ACTION_TIME"/>
        <result property="actionContent" column="ACTION_CONTENT"/>
        <result property="callbackPayload" column="CALLBACK_PAYLOAD"/>
        <result property="remark" column="REMARK"/>
    </resultMap>

    <sql id="mainColumns">
        select ID, CONTRACT_SYS_ID, CONTRACT_CODE, LAW_CONTRACT_CODE, LAW_CONTRACT_ID,
               CONTRACT_NAME, CONTRACT_TYPE, CONTRACT_TYPE_CODE, CONTRACT_SOURCE, CREATION_MODE,
               TEMPLATE_ID, TEMPLATE_CODE, TEMPLATE_NAME, STATUS, APPROVE_STATUS, APPROVE_MESSAGE,
               SEAL_CONTRACT_ID, SEAL_CONTRACT_STATUS, CONTRACT_AMOUNT, CURRENCY_NAME,
               CONTRACT_PERIOD_TYPE, PERIOD_EXPLAIN, EFFECTIVE_START, EFFECTIVE_END,
               PAYMENT_METHOD, PRIMARY_CONTENT, AMOUNT_EXPLAIN, VALUATION_MODE, NEED_AMENDMENTS, ESTIMATED_AMOUNT, SEAL_TYPE, SEAL_QUANTITY,
               TEXT_SOURCE, MANDATE_TYPE, CARGO_TYPE, ASSIST_DEPARTMENT_NAME, EXECUTOR_ACCOUNT,
               CREATOR_PHONE, SELF_CODE, MAIN_CONTRACT_CODE, SIGNING_SUBJECT_CODE, DATE_TYPE, IS_ADDIT, IS_ELECTRON,
               PAYMENT_DIRECTION, PUSH_URL, IS_MAJOR_CONTRACT, IS_OPEN_BIDDING, IS_YEAR_BUDGET, IS_SHARE,
               CONTRACT_NATURE, IS_SGAT, IS_NORMAL, IS_TERMINATED, IS_SINGLE_AGREEMENT,
               BIDDING_NO, OPEN_BIDDING_REMARK, CONTRACT_GIST_REMARK,
               EW_AMOUNT_TYPE, DJ_AMOUNT, YJ_AMOUNT, YFK_AMOUNT, BZJ_AMOUNT, BODY_SUMMARY,
               CONTRACT_TEXT_FILE_NAME, CONTRACT_TEXT_FILE_PATH, CONTRACT_TEXT_FILE_TYPE, CONTRACT_TEXT_FILE_SIZE,
               SIGNED_FILE_NAME, SIGNED_FILE_PATH, SIGNED_FILE_TYPE, SIGNED_FILE_SIZE, SIGNED_FILE_URL, SIGNED_OFFLINE_REASON,
               SIGN_DATE, SEAL_DATE, SEAL_IS_SEAL, SEAL_APPROVE_SAME, ACTIVE_DATE, ARCHIVE_DATE, ARCHIVE_RECEIVE_DEPT, ARCHIVE_TRANSFEROR, ARCHIVE_KEEPER, ARCHIVE_KEEPER_UNIT,
               ARCHIVE_KEEPER_UNIT_CODE, INVOICE_DATE, RECEIVE_DATE, REMIND_DAYS,
               INITIATOR, INITIATOR_DEPT, COMPANY_NAME, ORG_ID, QUERY_SCOPE,
               CREATE_BY, CREATE_TIME, UPDATE_BY, UPDATE_TIME, IS_DELETED, REMARK
        from SEAL_CONTRACT_LAUNCH_MAIN
    </sql>

    <select id="selectMainSeqNextVal" resultType="java.lang.Long" useCache="false" flushCache="true">
        select SEQ_SEAL_CONTRACT_LAUNCH_MAIN.NEXTVAL from dual
    </select>
    <select id="selectPartySeqNextVal" resultType="java.lang.Long" useCache="false" flushCache="true">
        select SEQ_SEAL_CONTRACT_LAUNCH_PARTY.NEXTVAL from dual
    </select>
    <select id="selectFileSeqNextVal" resultType="java.lang.Long" useCache="false" flushCache="true">
        select SEQ_SEAL_CONTRACT_LAUNCH_FILE.NEXTVAL from dual
    </select>
    <select id="selectPlanSeqNextVal" resultType="java.lang.Long" useCache="false" flushCache="true">
        select SEQ_SEAL_CONTRACT_LAUNCH_PLAN.NEXTVAL from dual
    </select>
    <select id="selectLogSeqNextVal" resultType="java.lang.Long" useCache="false" flushCache="true">
        select SEQ_SEAL_CONTRACT_LAUNCH_LOG.NEXTVAL from dual
    </select>
    <select id="selectArchivePaperSeqNextVal" resultType="java.lang.Long" useCache="false" flushCache="true">
        select SEQ_SC_AR_PAPER.NEXTVAL from dual
    </select>
    <select id="selectArchiveEleSeqNextVal" resultType="java.lang.Long" useCache="false" flushCache="true">
        select SEQ_SC_AR_ELE.NEXTVAL from dual
    </select>

    <!--
        权限过滤说明（对应需求文档"使用角色与权限"章节）：
        - admin：不过滤，看所有合同
        - personal：自己发起的(CREATE_BY) OR 我方主体命中(SIGNING_SUBJECT_CODE包含当前orgId) OR 相对方命中(party关联partner.LINKED_ORG_ID=当前orgId)
        - department：本部门(INITIATOR_DEPT) OR 我方主体命中 OR 相对方命中
        - company：本公司(ORG_ID) OR 我方主体命中 OR 相对方命中

        "多个我方 + 多个相对方都能看到合同"的闭环：
        - 我方：主表 SIGNING_SUBJECT_CODE 存多个我方主体编码(逗号分割)，当前用户 orgId 命中即可见
        - 相对方：party 子表 PARTNER_ID 关联 ILDM_FEE_CUSTOMER_INFO.LINKED_ORG_ID，命中即可见
          (政府/外部客户无 linkedOrgId，不参与本地权限，仅在签章平台签署)

        类型说明：ORG_ID 为 VARCHAR，LINKED_ORG_ID 为 NUMBER，比较时用 TO_CHAR 统一。
        我方主体编码逗号分割匹配用 INSTR，避免拆分。
    -->
    <select id="selectContractPage" resultMap="ContractLaunchResult">
        <include refid="mainColumns"/>
        <where>
            IS_DELETED = 'N'
            <if test="query.contractName != null and query.contractName != ''">
                and CONTRACT_NAME like CONCAT(CONCAT('%', #{query.contractName}), '%')
            </if>
            <if test="query.contractCode != null and query.contractCode != ''">
                and CONTRACT_CODE like CONCAT(CONCAT('%', #{query.contractCode}), '%')
            </if>
            <if test="query.contractType != null and query.contractType != ''">
                and CONTRACT_TYPE_CODE = #{query.contractType}
            </if>
            <if test="query.status != null and query.status != ''">
                and STATUS = #{query.status}
            </if>
            <if test="query.dateStart != null and query.dateStart != ''">
                and CREATE_TIME >= TO_DATE(#{query.dateStart} || ' 00:00:00', 'YYYY-MM-DD HH24:MI:SS')
            </if>
            <if test="query.dateEnd != null and query.dateEnd != ''">
                and CREATE_TIME &lt;= TO_DATE(#{query.dateEnd} || ' 23:59:59', 'YYYY-MM-DD HH24:MI:SS')
            </if>
            <!-- 权限范围过滤：admin 不过滤；其余范围按"自己/部门/公司 + 我方主体命中 + 相对方命中"取并集 -->
            <if test="query.queryScope != null and query.queryScope != '' and query.queryScope != 'admin'">
                and (
                    <!-- 个人级：自己发起的合同 -->
                    <choose>
                        <when test="query.queryScope == 'personal'">
                            CREATE_BY = #{query.currentUserId}
                        </when>
                        <when test="query.queryScope == 'department'">
                            INITIATOR_DEPT = #{query.currentDeptName}
                        </when>
                        <when test="query.queryScope == 'company'">
                            ORG_ID = #{query.currentOrgId}
                        </when>
                    </choose>
                    <!-- 我方主体命中：当前用户组织编码在 SIGNING_SUBJECT_CODE 逗号分割列表中 -->
                    <if test="query.currentOrgId != null and query.currentOrgId != ''">
                        or INSTR(',' || SIGNING_SUBJECT_CODE || ',', ',' || #{query.currentOrgId} || ',') &gt; 0
                    </if>
                    <!-- 相对方命中：合同方子表关联的相对方 linked_org_id = 当前用户组织ID -->
                    <if test="query.currentOrgId != null and query.currentOrgId != ''">
                        or ID in (
                            select p.CONTRACT_ID
                            from SEAL_CONTRACT_LAUNCH_PARTY p
                            inner join ILDM_FEE_CUSTOMER_INFO c on p.PARTNER_ID = c.CUSTOMER_SYSID
                            where p.IS_DELETED = 'N'
                              and p.ROLE_CODE = 'OPPOSITE'
                              and c.LINKED_ORG_ID is not null
                              and TO_CHAR(c.LINKED_ORG_ID) = #{query.currentOrgId}
                        )
                    </if>
                )
            </if>
        </where>
        order by CREATE_TIME desc, ID desc
    </select>

    <select id="selectContractById" resultMap="ContractLaunchResult">
        <include refid="mainColumns"/>
        where ID = #{id}
          and IS_DELETED = 'N'
    </select>

    <select id="selectContractByIdWithScope" resultMap="ContractLaunchResult">
        <include refid="mainColumns"/>
        <where>
            ID = #{id}
            and IS_DELETED = 'N'
            <if test="query.queryScope != null and query.queryScope != '' and query.queryScope != 'admin'">
                and (
                    <choose>
                        <when test="query.queryScope == 'personal'">
                            CREATE_BY = #{query.currentUserId}
                        </when>
                        <when test="query.queryScope == 'department'">
                            INITIATOR_DEPT = #{query.currentDeptName}
                        </when>
                        <when test="query.queryScope == 'company'">
                            ORG_ID = #{query.currentOrgId}
                        </when>
                    </choose>
                    <if test="query.currentOrgId != null and query.currentOrgId != ''">
                        or INSTR(',' || SIGNING_SUBJECT_CODE || ',', ',' || #{query.currentOrgId} || ',') &gt; 0
                    </if>
                    <if test="query.currentOrgId != null and query.currentOrgId != ''">
                        or ID in (
                            select p.CONTRACT_ID
                            from SEAL_CONTRACT_LAUNCH_PARTY p
                            inner join ILDM_FEE_CUSTOMER_INFO c on p.PARTNER_ID = c.CUSTOMER_SYSID
                            where p.IS_DELETED = 'N'
                              and p.ROLE_CODE = 'OPPOSITE'
                              and c.LINKED_ORG_ID is not null
                              and TO_CHAR(c.LINKED_ORG_ID) = #{query.currentOrgId}
                        )
                    </if>
                )
            </if>
        </where>
    </select>

    <select id="selectContractByContractSysId" resultMap="ContractLaunchResult">
        <include refid="mainColumns"/>
        where CONTRACT_SYS_ID = #{contractSysId}
          and IS_DELETED = 'N'
    </select>

    <select id="selectContractBySealContractId" resultMap="ContractLaunchResult">
        <include refid="mainColumns"/>
        where SEAL_CONTRACT_ID = #{sealContractId}
          and IS_DELETED = 'N'
    </select>

    <insert id="insertContract" parameterType="com.nbport.zgwl.contractlaunch.dto.ContractLaunchDto">
        insert into SEAL_CONTRACT_LAUNCH_MAIN (
            ID, CONTRACT_SYS_ID, CONTRACT_CODE, LAW_CONTRACT_CODE, LAW_CONTRACT_ID,
            CONTRACT_NAME, CONTRACT_TYPE, CONTRACT_TYPE_CODE, CONTRACT_SOURCE, CREATION_MODE,
            TEMPLATE_ID, TEMPLATE_CODE, TEMPLATE_NAME, STATUS, APPROVE_STATUS, APPROVE_MESSAGE,
            SEAL_CONTRACT_ID, SEAL_CONTRACT_STATUS, CONTRACT_AMOUNT, CURRENCY_NAME,
            CONTRACT_PERIOD_TYPE, PERIOD_EXPLAIN, EFFECTIVE_START, EFFECTIVE_END,
            PAYMENT_METHOD, PRIMARY_CONTENT, AMOUNT_EXPLAIN, VALUATION_MODE, NEED_AMENDMENTS, ESTIMATED_AMOUNT, SEAL_TYPE, SEAL_QUANTITY,
            TEXT_SOURCE, MANDATE_TYPE, CARGO_TYPE, ASSIST_DEPARTMENT_NAME, EXECUTOR_ACCOUNT,
            CREATOR_PHONE, SELF_CODE, MAIN_CONTRACT_CODE, SIGNING_SUBJECT_CODE, DATE_TYPE, IS_ADDIT, IS_ELECTRON,
            PAYMENT_DIRECTION, PUSH_URL, IS_MAJOR_CONTRACT, IS_OPEN_BIDDING, IS_YEAR_BUDGET, IS_SHARE,
            CONTRACT_NATURE, IS_SGAT, IS_NORMAL, IS_TERMINATED, IS_SINGLE_AGREEMENT,
            BIDDING_NO, OPEN_BIDDING_REMARK, CONTRACT_GIST_REMARK,
            EW_AMOUNT_TYPE, DJ_AMOUNT, YJ_AMOUNT, YFK_AMOUNT, BZJ_AMOUNT, BODY_SUMMARY,
            TEMPLATE_FIELD_VALUES_JSON,
            CONTRACT_TEXT_FILE_NAME, CONTRACT_TEXT_FILE_PATH, CONTRACT_TEXT_FILE_TYPE, CONTRACT_TEXT_FILE_SIZE,
            SIGNED_FILE_NAME, SIGNED_FILE_PATH, SIGNED_FILE_TYPE, SIGNED_FILE_SIZE, SIGNED_FILE_URL, SIGNED_OFFLINE_REASON,
            SIGN_DATE, SEAL_DATE, SEAL_IS_SEAL, SEAL_APPROVE_SAME, ACTIVE_DATE, ARCHIVE_DATE, ARCHIVE_RECEIVE_DEPT, ARCHIVE_TRANSFEROR, ARCHIVE_KEEPER, ARCHIVE_KEEPER_UNIT,
            ARCHIVE_KEEPER_UNIT_CODE, INVOICE_DATE, RECEIVE_DATE, REMIND_DAYS,
            INITIATOR, INITIATOR_DEPT, COMPANY_NAME, ORG_ID, QUERY_SCOPE,
            CREATE_BY, CREATE_TIME, UPDATE_BY, UPDATE_TIME, IS_DELETED, REMARK
        ) values (
            #{id}, #{contractSysId}, #{contractCode}, #{lawContractCode}, #{lawContractId},
            #{contractName}, #{contractType}, #{contractTypeCode}, #{contractSource}, #{creationMode},
            #{templateId}, #{templateCode}, #{templateName}, #{status}, #{approveStatus}, #{approveMessage},
            #{sealContractId}, #{sealContractStatus}, #{contractAmount}, #{currencyName},
            #{contractPeriodType}, #{periodExplain}, #{effectiveStart}, #{effectiveEnd},
            #{paymentMethod}, #{primaryContent}, #{amountExplain}, #{valuationMode}, #{needAmendments}, #{estimatedAmount}, #{sealType}, #{sealQuantity},
            #{textSource}, #{mandateType}, #{cargoType}, #{assistDepartmentName}, #{executorAccount},
            #{creatorPhone}, #{selfCode}, #{mainContractCode}, #{signingSubjectCode}, #{dateType}, #{isAddit}, #{isElectron},
            #{paymentDirection}, #{pushUrl}, #{isMajorContract}, #{isOpenBidding}, #{isYearBudget}, #{isShare},
            #{contractNature}, #{isSgat}, #{isNormal}, #{isTerminated}, #{isSingleAgreement},
            #{biddingNo}, #{openBiddingRemark}, #{contractGistRemark},
            #{ewAmountType}, #{djAmount}, #{yjAmount}, #{yfkAmount}, #{bzjAmount}, #{bodySummary},
            #{templateFieldValuesJson},
            #{contractTextFileName}, #{contractTextFilePath}, #{contractTextFileType}, #{contractTextFileSize},
            #{signedFileName}, #{signedFilePath}, #{signedFileType}, #{signedFileSize}, #{signedFileUrl}, #{signedOfflineReason},
            #{signDate}, #{sealDate}, #{sealIsSeal}, #{sealApproveSame}, #{activeDate}, #{archiveDate}, #{archiveReceiveDept}, #{archiveTransferor}, #{archiveKeeper}, #{archiveKeeperUnit},
            #{archiveKeeperUnitCode}, #{invoiceDate}, #{receiveDate}, #{remindDays},
            #{initiator}, #{initiatorDept}, #{companyName}, #{orgId}, #{queryScope},
            #{createBy}, #{createTime}, #{updateBy}, #{updateTime}, #{isDeleted}, #{remark}
        )
    </insert>

    <update id="updateContract" parameterType="com.nbport.zgwl.contractlaunch.dto.ContractLaunchDto">
        update SEAL_CONTRACT_LAUNCH_MAIN
        <trim prefix="set" suffixOverrides=",">
            LAW_CONTRACT_CODE = #{lawContractCode},
            LAW_CONTRACT_ID = #{lawContractId},
            CONTRACT_NAME = #{contractName},
            CONTRACT_TYPE = #{contractType},
            CONTRACT_TYPE_CODE = #{contractTypeCode},
            CONTRACT_SOURCE = #{contractSource},
            CREATION_MODE = #{creationMode},
            TEMPLATE_ID = #{templateId},
            TEMPLATE_CODE = #{templateCode},
            TEMPLATE_NAME = #{templateName},
            STATUS = #{status},
            APPROVE_STATUS = #{approveStatus},
            APPROVE_MESSAGE = #{approveMessage},
            SEAL_CONTRACT_ID = #{sealContractId},
            SEAL_CONTRACT_STATUS = #{sealContractStatus},
            CONTRACT_AMOUNT = #{contractAmount},
            CURRENCY_NAME = #{currencyName},
            CONTRACT_PERIOD_TYPE = #{contractPeriodType},
            PERIOD_EXPLAIN = #{periodExplain},
            EFFECTIVE_START = #{effectiveStart},
            EFFECTIVE_END = #{effectiveEnd},
            PAYMENT_METHOD = #{paymentMethod},
            PRIMARY_CONTENT = #{primaryContent},
            AMOUNT_EXPLAIN = #{amountExplain},
            VALUATION_MODE = #{valuationMode},
            NEED_AMENDMENTS = #{needAmendments},
            ESTIMATED_AMOUNT = #{estimatedAmount},
            SEAL_TYPE = #{sealType},
            SEAL_QUANTITY = #{sealQuantity},
            TEXT_SOURCE = #{textSource},
            MANDATE_TYPE = #{mandateType},
            CARGO_TYPE = #{cargoType},
            ASSIST_DEPARTMENT_NAME = #{assistDepartmentName},
            EXECUTOR_ACCOUNT = #{executorAccount},
            CREATOR_PHONE = #{creatorPhone},
            SELF_CODE = #{selfCode},
            MAIN_CONTRACT_CODE = #{mainContractCode},
            SIGNING_SUBJECT_CODE = #{signingSubjectCode},
            DATE_TYPE = #{dateType},
            IS_ADDIT = #{isAddit},
            IS_ELECTRON = #{isElectron},
            PAYMENT_DIRECTION = #{paymentDirection},
            PUSH_URL = #{pushUrl},
            IS_MAJOR_CONTRACT = #{isMajorContract},
            IS_OPEN_BIDDING = #{isOpenBidding},
            IS_YEAR_BUDGET = #{isYearBudget},
            IS_SHARE = #{isShare},
            CONTRACT_NATURE = #{contractNature},
            IS_SGAT = #{isSgat},
            IS_NORMAL = #{isNormal},
            IS_TERMINATED = #{isTerminated},
            IS_SINGLE_AGREEMENT = #{isSingleAgreement},
            BIDDING_NO = #{biddingNo},
            OPEN_BIDDING_REMARK = #{openBiddingRemark},
            CONTRACT_GIST_REMARK = #{contractGistRemark},
            EW_AMOUNT_TYPE = #{ewAmountType},
            DJ_AMOUNT = #{djAmount},
            YJ_AMOUNT = #{yjAmount},
            YFK_AMOUNT = #{yfkAmount},
            BZJ_AMOUNT = #{bzjAmount},
            BODY_SUMMARY = #{bodySummary},
            TEMPLATE_FIELD_VALUES_JSON = #{templateFieldValuesJson},
            CONTRACT_TEXT_FILE_NAME = #{contractTextFileName},
            CONTRACT_TEXT_FILE_PATH = #{contractTextFilePath},
            CONTRACT_TEXT_FILE_TYPE = #{contractTextFileType},
            CONTRACT_TEXT_FILE_SIZE = #{contractTextFileSize},
            SIGNED_FILE_NAME = #{signedFileName},
            SIGNED_FILE_PATH = #{signedFilePath},
            SIGNED_FILE_TYPE = #{signedFileType},
            SIGNED_FILE_SIZE = #{signedFileSize},
            SIGNED_FILE_URL = #{signedFileUrl},
            SIGNED_OFFLINE_REASON = #{signedOfflineReason},
            SIGN_DATE = #{signDate},
            SEAL_DATE = #{sealDate},
            SEAL_IS_SEAL = #{sealIsSeal},
            SEAL_APPROVE_SAME = #{sealApproveSame},
            ACTIVE_DATE = #{activeDate},
            ARCHIVE_DATE = #{archiveDate},
            ARCHIVE_RECEIVE_DEPT = #{archiveReceiveDept},
            ARCHIVE_TRANSFEROR = #{archiveTransferor},
            ARCHIVE_KEEPER = #{archiveKeeper},
            ARCHIVE_KEEPER_UNIT = #{archiveKeeperUnit},
            ARCHIVE_KEEPER_UNIT_CODE = #{archiveKeeperUnitCode},
            INVOICE_DATE = #{invoiceDate},
            RECEIVE_DATE = #{receiveDate},
            REMIND_DAYS = #{remindDays},
            INITIATOR = #{initiator},
            INITIATOR_DEPT = #{initiatorDept},
            COMPANY_NAME = #{companyName},
            ORG_ID = #{orgId},
            QUERY_SCOPE = #{queryScope},
            UPDATE_BY = #{updateBy},
            UPDATE_TIME = #{updateTime},
            IS_DELETED = #{isDeleted},
            REMARK = #{remark},
        </trim>
        where ID = #{id}
          and IS_DELETED = 'N'
    </update>

    <update id="deleteContract">
        update SEAL_CONTRACT_LAUNCH_MAIN
        set IS_DELETED = 'Y',
            UPDATE_BY = #{updateBy},
            UPDATE_TIME = SYSDATE
        where ID = #{id}
          and IS_DELETED = 'N'
    </update>

    <insert id="batchInsertParty">
        INSERT ALL
        <foreach collection="list" item="item">
            INTO SEAL_CONTRACT_LAUNCH_PARTY (
                ID, CONTRACT_ID, ROLE_CODE, ROLE_NAME, SUBJECT_CODE, SORT_ORDER, PARTNER_ID, OPPOSITE_ID,
                COMPANY_NAME, COMPANY_TYPE, OPPOSITE_CHARACTER, CONTACT_NAME, CONTACT_PHONE,
                CONTACT_EMAIL, CONTACT_ADDRESS, REGISTERED_ADDRESS, LEGAL_REPRESENTATIVE,
                CREDIT_CODE, BANK_NAME, BANK_ACCOUNT, NATURAL_PERSON_ID_TYPE, NATURAL_PERSON_ID_NUMBER,
                IS_GROUP_INTERNAL, IS_HONG_KONG_MACAO_TAIWAN, CREATE_BY, CREATE_TIME, UPDATE_BY, UPDATE_TIME, IS_DELETED, REMARK
            ) VALUES (
                #{item.id}, #{item.contractId}, #{item.roleCode}, #{item.roleName}, #{item.subjectCode}, #{item.sortOrder}, #{item.partnerId}, #{item.oppositeId},
                #{item.companyName}, #{item.companyType}, #{item.oppositeCharacter}, #{item.contactName}, #{item.contactPhone},
                #{item.contactEmail}, #{item.contactAddress}, #{item.registeredAddress}, #{item.legalRepresentative},
                #{item.creditCode}, #{item.bankName}, #{item.bankAccount}, #{item.naturalPersonIdType}, #{item.naturalPersonIdNumber},
                #{item.isGroupInternal}, #{item.isHongKongMacaoTaiwan}, #{createBy}, SYSDATE, #{updateBy}, SYSDATE, 'N', #{item.remark}
            )
        </foreach>
        SELECT 1 FROM DUAL
    </insert>

    <insert id="batchInsertFile">
        INSERT ALL
        <foreach collection="list" item="item">
            INTO SEAL_CONTRACT_LAUNCH_FILE (
                ID, CONTRACT_ID, FILE_CATEGORY, ARCHIVE_ELE_ID, FILE_NAME, FILE_PATH, LEGAL_FILE_URL, FILE_TYPE, FILE_SIZE,
                SORT_ORDER, CREATE_BY, CREATE_TIME, UPDATE_BY, UPDATE_TIME, IS_DELETED, REMARK
            ) VALUES (
                #{item.id}, #{item.contractId}, #{item.fileCategory}, #{item.archiveEleId}, #{item.fileName}, #{item.filePath}, #{item.legalFileUrl}, #{item.fileType}, #{item.fileSize},
                #{item.sortOrder}, #{createBy}, SYSDATE, #{updateBy}, SYSDATE, 'N', #{item.remark}
            )
        </foreach>
        SELECT 1 FROM DUAL
    </insert>

    <insert id="batchInsertPlan">
        INSERT ALL
        <foreach collection="list" item="item">
            INTO SEAL_CONTRACT_LAUNCH_PLAN (
                ID, CONTRACT_ID, PLAN_MATTER, PLAN_WHERE, PLAN_TIME, PLAN_DAY, PLAN_MONEY,
                PLAN_SUBJECT_CODE, PLAN_SUBJECT_NAME, PLAN_DETAIL, PLAN_STATUS,
                CREATE_BY, CREATE_TIME, UPDATE_BY, UPDATE_TIME, IS_DELETED, REMARK
            ) VALUES (
                #{item.id}, #{item.contractId}, #{item.planMatter}, #{item.planWhere}, #{item.planTime}, #{item.planDay}, #{item.planMoney},
                #{item.planSubjectCode}, #{item.planSubjectName}, #{item.planDetail}, #{item.planStatus},
                #{createBy}, SYSDATE, #{updateBy}, SYSDATE, 'N', #{item.remark}
            )
        </foreach>
        SELECT 1 FROM DUAL
    </insert>

    <insert id="batchInsertArchivePaper">
        INSERT ALL
        <foreach collection="list" item="item">
            INTO SEAL_CONTRACT_LAUNCH_AR_PAPER (
                ID, CONTRACT_ID, ARCHIVES_NAME, ARCHIVES_NUM, ARCHIVES_TIME, SORT_ORDER,
                CREATE_BY, CREATE_TIME, UPDATE_BY, UPDATE_TIME, IS_DELETED, REMARK
            ) VALUES (
                #{item.id}, #{item.contractId}, #{item.archivesName}, #{item.archivesNum}, #{item.archivesTime}, #{item.sortOrder},
                #{createBy}, SYSDATE, #{updateBy}, SYSDATE, 'N', #{item.remark}
            )
        </foreach>
        SELECT 1 FROM DUAL
    </insert>

    <insert id="batchInsertArchiveEle">
        INSERT ALL
        <foreach collection="list" item="item">
            INTO SEAL_CONTRACT_LAUNCH_AR_ELE (
                ID, CONTRACT_ID, ARCHIVES_NAME, SORT_ORDER,
                CREATE_BY, CREATE_TIME, UPDATE_BY, UPDATE_TIME, IS_DELETED, REMARK
            ) VALUES (
                #{item.id}, #{item.contractId}, #{item.archivesName}, #{item.sortOrder},
                #{createBy}, SYSDATE, #{updateBy}, SYSDATE, 'N', #{item.remark}
            )
        </foreach>
        SELECT 1 FROM DUAL
    </insert>

    <insert id="insertLog" parameterType="com.nbport.zgwl.contractlaunch.dto.ContractLaunchLogDto">
        insert into SEAL_CONTRACT_LAUNCH_LOG (
            ID, CONTRACT_ID, ACTION_TYPE, ACTION_NAME, ACTION_STATUS, OPERATOR_NAME, OPERATOR_PHONE,
            ACTION_TIME, ACTION_CONTENT, CALLBACK_PAYLOAD, REMARK
        ) values (
            #{id}, #{contractId}, #{actionType}, #{actionName}, #{actionStatus}, #{operatorName}, #{operatorPhone},
            #{actionTime}, #{actionContent}, #{callbackPayload}, #{remark}
        )
    </insert>

    <update id="deletePartyByContractId">
        update SEAL_CONTRACT_LAUNCH_PARTY
        set IS_DELETED = 'Y',
            UPDATE_BY = #{updateBy},
            UPDATE_TIME = SYSDATE
        where CONTRACT_ID = #{contractId}
          and IS_DELETED = 'N'
    </update>

    <update id="deleteFileByContractId">
        update SEAL_CONTRACT_LAUNCH_FILE
        set IS_DELETED = 'Y',
            UPDATE_BY = #{updateBy},
            UPDATE_TIME = SYSDATE
        where CONTRACT_ID = #{contractId}
          and IS_DELETED = 'N'
    </update>

    <update id="deleteFileByContractIdAndCategory">
        update SEAL_CONTRACT_LAUNCH_FILE
        set IS_DELETED = 'Y',
            UPDATE_BY = #{updateBy},
            UPDATE_TIME = SYSDATE
        where CONTRACT_ID = #{contractId}
            and FILE_CATEGORY = #{fileCategory}
            and IS_DELETED = 'N'
    </update>

    <update id="updateFileLegalUrl">
        update SEAL_CONTRACT_LAUNCH_FILE
        set LEGAL_FILE_URL = #{legalFileUrl},
            UPDATE_BY = #{updateBy},
            UPDATE_TIME = SYSDATE
        where ID = #{id}
          and IS_DELETED = 'N'
    </update>

    <update id="deletePlanByContractId">
        update SEAL_CONTRACT_LAUNCH_PLAN
        set IS_DELETED = 'Y',
            UPDATE_BY = #{updateBy},
            UPDATE_TIME = SYSDATE
        where CONTRACT_ID = #{contractId}
          and IS_DELETED = 'N'
    </update>

    <update id="deleteArchivePaperByContractId">
        update SEAL_CONTRACT_LAUNCH_AR_PAPER
        set IS_DELETED = 'Y',
            UPDATE_BY = #{updateBy},
            UPDATE_TIME = SYSDATE
        where CONTRACT_ID = #{contractId}
          and IS_DELETED = 'N'
    </update>

    <update id="deleteArchiveEleByContractId">
        update SEAL_CONTRACT_LAUNCH_AR_ELE
        set IS_DELETED = 'Y',
            UPDATE_BY = #{updateBy},
            UPDATE_TIME = SYSDATE
        where CONTRACT_ID = #{contractId}
          and IS_DELETED = 'N'
    </update>

    <select id="selectPartyByContractIds" resultMap="PartyResult">
        select ID, CONTRACT_ID, ROLE_CODE, ROLE_NAME, SUBJECT_CODE, SORT_ORDER, PARTNER_ID, OPPOSITE_ID,
               COMPANY_NAME, COMPANY_TYPE, OPPOSITE_CHARACTER, CONTACT_NAME, CONTACT_PHONE,
               CONTACT_EMAIL, CONTACT_ADDRESS, REGISTERED_ADDRESS, LEGAL_REPRESENTATIVE,
               CREDIT_CODE, BANK_NAME, BANK_ACCOUNT, NATURAL_PERSON_ID_TYPE, NATURAL_PERSON_ID_NUMBER,
               IS_GROUP_INTERNAL, IS_HONG_KONG_MACAO_TAIWAN, REMARK
        from SEAL_CONTRACT_LAUNCH_PARTY
        where IS_DELETED = 'N'
          and CONTRACT_ID in
        <foreach collection="contractIds" item="contractId" open="(" separator="," close=")">
            #{contractId}
        </foreach>
        order by CONTRACT_ID asc, SORT_ORDER asc, ID asc
    </select>

    <select id="selectFileByContractIds" resultMap="FileResult">
        select ID, CONTRACT_ID, FILE_CATEGORY, ARCHIVE_ELE_ID, FILE_NAME, FILE_PATH, LEGAL_FILE_URL, FILE_TYPE, FILE_SIZE, SORT_ORDER, REMARK
        from SEAL_CONTRACT_LAUNCH_FILE
        where IS_DELETED = 'N'
          and CONTRACT_ID in
        <foreach collection="contractIds" item="contractId" open="(" separator="," close=")">
            #{contractId}
        </foreach>
        order by CONTRACT_ID asc, SORT_ORDER asc, ID asc
    </select>

    <select id="selectPlanByContractIds" resultMap="PlanResult">
        select ID, CONTRACT_ID, PLAN_MATTER, PLAN_WHERE, PLAN_TIME, PLAN_DAY, PLAN_MONEY,
               PLAN_SUBJECT_CODE, PLAN_SUBJECT_NAME, PLAN_DETAIL, PLAN_STATUS, REMARK
        from SEAL_CONTRACT_LAUNCH_PLAN
        where IS_DELETED = 'N'
          and CONTRACT_ID in
        <foreach collection="contractIds" item="contractId" open="(" separator="," close=")">
            #{contractId}
        </foreach>
        order by CONTRACT_ID asc, PLAN_TIME asc, ID asc
    </select>

    <select id="selectArchivePaperByContractIds" resultMap="ArchivePaperResult">
        select ID, CONTRACT_ID, ARCHIVES_NAME, ARCHIVES_NUM, ARCHIVES_TIME, SORT_ORDER, REMARK
        from SEAL_CONTRACT_LAUNCH_AR_PAPER
        where IS_DELETED = 'N'
          and CONTRACT_ID in
        <foreach collection="contractIds" item="contractId" open="(" separator="," close=")">
            #{contractId}
        </foreach>
        order by CONTRACT_ID asc, SORT_ORDER asc, ID asc
    </select>

    <select id="selectArchiveEleByContractIds" resultMap="ArchiveEleResult">
        select ID, CONTRACT_ID, ARCHIVES_NAME, SORT_ORDER, REMARK
        from SEAL_CONTRACT_LAUNCH_AR_ELE
        where IS_DELETED = 'N'
          and CONTRACT_ID in
        <foreach collection="contractIds" item="contractId" open="(" separator="," close=")">
            #{contractId}
        </foreach>
        order by CONTRACT_ID asc, SORT_ORDER asc, ID asc
    </select>

    <select id="selectLogByContractIds" resultMap="LogResult">
        select ID, CONTRACT_ID, ACTION_TYPE, ACTION_NAME, ACTION_STATUS, OPERATOR_NAME, OPERATOR_PHONE,
               ACTION_TIME, ACTION_CONTENT, CALLBACK_PAYLOAD, REMARK
        from SEAL_CONTRACT_LAUNCH_LOG
        where CONTRACT_ID in
        <foreach collection="contractIds" item="contractId" open="(" separator="," close=")">
            #{contractId}
        </foreach>
        order by CONTRACT_ID asc, ACTION_TIME desc, ID desc
    </select>

</mapper>
