pg_cooperation_contract_repository.go 57.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
package repository

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"github.com/linmadan/egglib-go/utils/snowflake"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/pg/transform"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/log"
	"time"
)

type CooperationContractRepository struct {
	transactionContext *pgTransaction.TransactionContext
	IdWorker           *snowflake.IdWorker
}

func (repository *CooperationContractRepository) nextIdentify() (int64, error) {
	id, err := repository.IdWorker.NextId()
	return id, err
}

func (repository *CooperationContractRepository) Save(cooperationContract *domain.CooperationContract) (*domain.CooperationContract, error) {
	sqlBuildFields := []string{
		"cooperation_contract_id",
		"cooperation_contract_description",
		"cooperation_contract_name",
		"cooperation_contract_number",
		"cooperation_project_number",
		"cooperation_contract_undertaker_types",
		"cooperation_contract_sponsor",
		"cooperation_mode_number",
		"status",
		"org",
		"incentives_type",
		"company",
		"department",
		"operator",
		"operate_time",
		"created_at",
		"deleted_at",
		"updated_at",
	}
	insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
	returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
	updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "cooperationContract_id")
	updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
	tx := repository.transactionContext.PgTx
	if cooperationContract.Identify() == nil {
		cooperationContractId, err := repository.nextIdentify()
		if err != nil {
			return cooperationContract, err
		} else {
			cooperationContract.CooperationContractId = cooperationContractId
		}
		if _, err := tx.QueryOne(
			pg.Scan(
				&cooperationContract.CooperationContractId,
				&cooperationContract.CooperationContractDescription,
				&cooperationContract.CooperationContractName,
				&cooperationContract.CooperationContractNumber,
				&cooperationContract.CooperationProjectNumber,
				pg.Array(&cooperationContract.CooperationContractUndertakerTypes),
				&cooperationContract.CooperationContractSponsor,
				&cooperationContract.CooperationMode.CooperationModeNumber,
				&cooperationContract.Status,
				&cooperationContract.Org,
				&cooperationContract.IncentivesType,
				&cooperationContract.Company,
				&cooperationContract.Department,
				&cooperationContract.Operator,
				&cooperationContract.OperateTime,
				&cooperationContract.CreatedAt,
				&cooperationContract.DeletedAt,
				&cooperationContract.UpdatedAt,
			),
			fmt.Sprintf("INSERT INTO cooperation_contracts (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
			cooperationContract.CooperationContractId,
			cooperationContract.CooperationContractDescription,
			cooperationContract.CooperationContractName,
			cooperationContract.CooperationContractNumber,
			cooperationContract.CooperationProjectNumber,
			pg.Array(cooperationContract.CooperationContractUndertakerTypes),
			cooperationContract.CooperationContractSponsor,
			cooperationContract.CooperationMode.CooperationModeNumber,
			cooperationContract.Status,
			cooperationContract.Org,
			cooperationContract.IncentivesType,
			cooperationContract.Company,
			cooperationContract.Department,
			cooperationContract.Operator,
			cooperationContract.OperateTime,
			cooperationContract.CreatedAt,
			nil,
			cooperationContract.UpdatedAt,
		); err != nil {
			return cooperationContract, err
		}

		// 新增相关人
		var relevantPeopleModel []*models.CooperationContractRelevant
		for _, relevant := range cooperationContract.RelevantPeople {
			if relevant.Identify() == nil {
				orderGoodId, err := repository.nextIdentify()
				if err != nil {
					return nil, err
				} else {
					relevant.RelevantId = orderGoodId
				}
			}
			relevantPeopleModel = append(relevantPeopleModel, &models.CooperationContractRelevant{
				CooperationContractRelevantId: relevant.RelevantId,
				CooperationContractNumber:     cooperationContract.CooperationContractNumber,
				UserId:                        relevant.UserId,
				UserBaseId:                    relevant.UserBaseId,
				Org:                           relevant.Org,
				Orgs:                          relevant.Orgs,
				Department:                    relevant.Department,
				Roles:                         relevant.Roles,
				UserInfo:                      relevant.UserInfo,
				UserType:                      relevant.UserType,
				Status:                        relevant.Status,
				Company:                       relevant.Company,
				UpdatedAt:                     time.Time{},
				DeletedAt:                     time.Time{},
				CreatedAt:                     time.Now(),
			})
		}
		if len(relevantPeopleModel) > 0 {
			log.Logger.Info("新增的相关人", map[string]interface{}{
				"relevantPeopleModel": relevantPeopleModel,
			})
			if _, err := tx.Model(&relevantPeopleModel).Insert(); err != nil {
				return nil, err
			}
		}

		// 新增承接人
		var undertakersModel []*models.CooperationContractUndertaker
		for _, undertaker := range cooperationContract.Undertakers {
			undertakersModel = append(undertakersModel, &models.CooperationContractUndertaker{
				CooperationContractNumber: cooperationContract.CooperationContractNumber,
				UserId:                    undertaker.UserId,
				UserBaseId:                undertaker.UserBaseId,
				Org:                       undertaker.Org,
				Orgs:                      undertaker.Orgs,
				Department:                undertaker.Department,
				Roles:                     undertaker.Roles,
				UserInfo:                  undertaker.UserInfo,
				UserType:                  undertaker.UserType,
				Referrer:                  undertaker.Referrer,
				Salesman:                  undertaker.Salesman,
				Status:                    undertaker.Status,
				Company:                   undertaker.Company,
				ContractAttachment:        undertaker.ContractAttachment,
				CreatedAt:                 time.Time{},
				UpdatedAt:                 time.Time{},
				DeletedAt:                 time.Now(),
			})
		}
		if len(undertakersModel) > 0 {
			log.Logger.Info("新增的承接人", map[string]interface{}{
				"undertakersModel": undertakersModel,
			})
			if _, err := tx.Model(&undertakersModel).Insert(); err != nil {
				return nil, err
			}
		}

		// 新增分红激励规则
		var dividendsIncentivesRulesModel []*models.DividendsIncentivesRule
		for _, rule := range cooperationContract.DividendsIncentivesRules {
			if rule.Identify() == nil {
				ruleId, err := repository.nextIdentify()
				if err != nil {
					return nil, err
				} else {
					rule.DividendsIncentivesRuleId = ruleId
				}
			}
			dividendsIncentivesRulesModel = append(dividendsIncentivesRulesModel, &models.DividendsIncentivesRule{
				DividendsIncentivesRuleId:     rule.DividendsIncentivesRuleId,
				CooperationContractNumber:     cooperationContract.CooperationContractNumber,
				ReferrerPercentage:            rule.ReferrerPercentage,
				SalesmanPercentage:            rule.SalesmanPercentage,
				DividendsIncentivesPercentage: rule.DividendsIncentivesPercentage,
				DividendsIncentivesStage:      rule.DividendsIncentivesStage,
				DividendsIncentivesStageStart: rule.DividendsIncentivesStageStart,
				DividendsIncentivesStageEnd:   rule.DividendsIncentivesStageEnd,
				Org:                           rule.Org,
				Company:                       rule.Company,
				UpdatedAt:                     time.Time{},
				DeletedAt:                     time.Time{},
				CreatedAt:                     time.Now(),
				Remarks:                       rule.Remarks,
			})
		}
		if len(dividendsIncentivesRulesModel) > 0 {
			log.Logger.Info("新增分红激励规则", map[string]interface{}{
				"dividendsIncentivesRulesModel": dividendsIncentivesRulesModel,
			})
			if _, err := tx.Model(&dividendsIncentivesRulesModel).Insert(); err != nil {
				return nil, err
			}
		}

		// 新增金额激励规则
		var moneyIncentivesRulesModel []*models.MoneyIncentivesRule
		for _, rule := range cooperationContract.MoneyIncentivesRules {
			if rule.Identify() == nil {
				ruleId, err := repository.nextIdentify()
				if err != nil {
					return nil, err
				} else {
					rule.MoneyIncentivesRuleId = ruleId
				}
			}
			moneyIncentivesRulesModel = append(moneyIncentivesRulesModel, &models.MoneyIncentivesRule{
				MoneyIncentivesRuleId:     rule.MoneyIncentivesRuleId,
				CooperationContractNumber: cooperationContract.CooperationContractNumber,
				MoneyIncentivesAmount:     rule.MoneyIncentivesAmount,
				MoneyIncentivesStage:      rule.MoneyIncentivesStage,
				MoneyIncentivesStageStart: rule.MoneyIncentivesStageStart,
				MoneyIncentivesStageEnd:   rule.MoneyIncentivesStageEnd,
				MoneyIncentivesTime:       rule.MoneyIncentivesTime,
				ReferrerPercentage:        rule.ReferrerPercentage,
				SalesmanPercentage:        rule.SalesmanPercentage,
				Org:                       rule.Org,
				Company:                   rule.Company,
				UpdatedAt:                 time.Time{},
				DeletedAt:                 time.Time{},
				CreatedAt:                 time.Now(),
				Remarks:                   rule.Remarks,
			})
		}
		if len(moneyIncentivesRulesModel) > 0 {
			log.Logger.Info("新增金额激励规则", map[string]interface{}{
				"moneyIncentivesRulesModel": moneyIncentivesRulesModel,
			})
			if _, err := tx.Model(&moneyIncentivesRulesModel).Insert(); err != nil {
				return nil, err
			}
		}
	} else {
		if _, err := tx.QueryOne(
			pg.Scan(
				&cooperationContract.CooperationContractId,
				&cooperationContract.CooperationContractDescription,
				&cooperationContract.CooperationContractName,
				&cooperationContract.CooperationContractNumber,
				&cooperationContract.CooperationProjectNumber,
				pg.Array(&cooperationContract.CooperationContractUndertakerTypes),
				&cooperationContract.CooperationContractSponsor,
				&cooperationContract.CooperationMode.CooperationModeNumber,
				&cooperationContract.Status,
				&cooperationContract.Org,
				&cooperationContract.IncentivesType,
				&cooperationContract.Company,
				&cooperationContract.Department,
				&cooperationContract.Operator,
				&cooperationContract.OperateTime,
				&cooperationContract.CreatedAt,
				&cooperationContract.DeletedAt,
				&cooperationContract.UpdatedAt,
			),
			fmt.Sprintf("UPDATE cooperation_contracts SET %s WHERE cooperation_contract_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
			cooperationContract.CooperationContractId,
			cooperationContract.CooperationContractDescription,
			cooperationContract.CooperationContractName,
			cooperationContract.CooperationContractNumber,
			cooperationContract.CooperationProjectNumber,
			pg.Array(cooperationContract.CooperationContractUndertakerTypes),
			cooperationContract.CooperationContractSponsor,
			cooperationContract.CooperationMode.CooperationModeNumber,
			cooperationContract.Status,
			cooperationContract.Org,
			cooperationContract.IncentivesType,
			cooperationContract.Company,
			cooperationContract.Department,
			cooperationContract.Operator,
			cooperationContract.OperateTime,
			cooperationContract.CreatedAt,
			nil,
			cooperationContract.UpdatedAt,
			cooperationContract.Identify(),
		); err != nil {
			return cooperationContract, err
		}

		/******************************* 更新相关人 ****************************/
		// 查找相关人列表
		var cooperationContractRelevantModelsFetched []*models.CooperationContractRelevant
		cooperationContractRelevantQuery := tx.Model(&cooperationContractRelevantModelsFetched)
		if err := cooperationContractRelevantQuery.
			Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
			Select(); err != nil {
			return nil, err
		}

		// 提取相关人id
		var cooperationContractRelevantIdsFetched []int64
		for _, cooperationContractRelevant := range cooperationContractRelevantModelsFetched {
			cooperationContractRelevantIdsFetched = append(cooperationContractRelevantIdsFetched, cooperationContractRelevant.CooperationContractRelevantId)
		}

		// 待更新相关人
		var cooperationContractRelevantPeopleToUpdate []*domain.Relevant

		// 待添加相关人
		var cooperationContractRelevantPeopleToAdd []*domain.Relevant
		for _, relevant := range cooperationContract.RelevantPeople {
			if relevant.RelevantId != 0 {
				cooperationContractRelevantPeopleToUpdate = append(cooperationContractRelevantPeopleToUpdate, relevant)
			} else {
				cooperationContractRelevantPeopleToAdd = append(cooperationContractRelevantPeopleToAdd, relevant)
			}
		}

		// 将待添加的相关人领域模型转换为数据模型
		var cooperationContractRelevantPeopleToAddModels []*models.CooperationContractRelevant
		for _, relevantDomain := range cooperationContractRelevantPeopleToAdd {
			if relevantDomain.Identify() == nil {
				relevantId, err := repository.nextIdentify()
				if err != nil {
					return nil, err
				} else {
					relevantDomain.RelevantId = relevantId
				}
			}
			cooperationContractRelevantPeopleToAddModels = append(cooperationContractRelevantPeopleToAddModels, &models.CooperationContractRelevant{
				CooperationContractRelevantId: relevantDomain.RelevantId,
				CooperationContractNumber:     relevantDomain.CooperationContractNumber,
				UserId:                        relevantDomain.UserId,
				UserBaseId:                    relevantDomain.UserBaseId,
				Org:                           relevantDomain.Org,
				Orgs:                          relevantDomain.Orgs,
				Department:                    relevantDomain.Department,
				Roles:                         relevantDomain.Roles,
				UserInfo:                      relevantDomain.UserInfo,
				UserType:                      relevantDomain.UserType,
				Status:                        relevantDomain.Status,
				Company:                       relevantDomain.Company,
				UpdatedAt:                     time.Time{},
				DeletedAt:                     time.Time{},
				CreatedAt:                     time.Now(),
			})
		}

		// 添加相关人
		if len(cooperationContractRelevantPeopleToAddModels) > 0 {
			if _, err := tx.Model(&cooperationContractRelevantPeopleToAddModels).Insert(); err != nil {
				return nil, err
			}
		}

		// 待更新或者删除的ids
		var cooperationContractRelevantPeopleToUpdateOrDeleteIds []int64
		for _, cooperationContractRelevantPersonToUpdate := range cooperationContractRelevantPeopleToUpdate {
			cooperationContractRelevantPeopleToUpdateOrDeleteIds = append(cooperationContractRelevantPeopleToUpdateOrDeleteIds, cooperationContractRelevantPersonToUpdate.RelevantId)
		}

		// 待更新的相关人id
		relevantIdsToUpdate := utils.Intersect(cooperationContractRelevantIdsFetched, cooperationContractRelevantPeopleToUpdateOrDeleteIds)
		var relevantModelsToUpdate []*models.CooperationContractRelevant
		for _, id := range relevantIdsToUpdate {
			for _, relevantModel := range cooperationContractRelevantModelsFetched {
				if relevantModel.CooperationContractRelevantId == id {
					relevantModelsToUpdate = append(relevantModelsToUpdate, relevantModel)
				}
			}
		}
		if len(relevantModelsToUpdate) > 0 {
			if _, err := tx.Model(&relevantModelsToUpdate).WherePK().Update(); err != nil {
				return nil, err
			}
		}

		// 待删除的相关人id
		relevantIdsToDelete := utils.Difference(cooperationContractRelevantIdsFetched, cooperationContractRelevantPeopleToUpdateOrDeleteIds)
		var relevantModelsToDelete []*models.CooperationContractRelevant
		for _, id := range relevantIdsToDelete {
			for _, relevantModel := range cooperationContractRelevantModelsFetched {
				if relevantModel.CooperationContractRelevantId == id {
					relevantModelsToDelete = append(relevantModelsToDelete, relevantModel)
				}
			}
		}
		log.Logger.Info("待删除的相关人", map[string]interface{}{
			"待删除的相关人": relevantModelsToDelete,
		})
		if len(relevantModelsToDelete) > 0 {
			if _, err := tx.Model(&relevantModelsToDelete).Delete(); err != nil {
				return nil, err
			}
		}

		/************************* 更新承接人 ****************************/
		// 获取承接人列表
		var cooperationContractUndertakersModelsFetched []*models.CooperationContractUndertaker
		cooperationContractUndertakerQuery := tx.Model(&cooperationContractUndertakersModelsFetched)
		if err := cooperationContractUndertakerQuery.
			Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
			Select(); err != nil {
			return nil, err
		}

		// 提取承接人id
		var cooperationContractUndertakersIdsFetched []int64
		for _, cooperationContractUndertaker := range cooperationContractUndertakersModelsFetched {
			cooperationContractUndertakersIdsFetched = append(cooperationContractUndertakersIdsFetched, cooperationContractUndertaker.CooperationContractUndertakerId)
		}

		// 待更新相关人
		var cooperationContractUndertakersToUpdate []*domain.Undertaker
		// 待添加相关人
		var cooperationContractUndertakersToAdd []*domain.Undertaker
		for _, undertaker := range cooperationContract.Undertakers {
			if undertaker.UndertakerId != 0 {
				cooperationContractUndertakersToUpdate = append(cooperationContractUndertakersToUpdate, undertaker)
			} else {
				cooperationContractUndertakersToAdd = append(cooperationContractUndertakersToAdd, undertaker)
			}
		}

		// 将待添加的相关人领域模型转换为数据模型
		var cooperationContractUndertakersToAddModels []*models.CooperationContractUndertaker
		for _, undertakerDomain := range cooperationContractUndertakersToAdd {
			if undertakerDomain.Identify() == nil {
				undertakerId, err := repository.nextIdentify()
				if err != nil {
					return nil, err
				} else {
					undertakerDomain.UndertakerId = undertakerId
				}
			}
			cooperationContractUndertakersToAddModels = append(cooperationContractUndertakersToAddModels, &models.CooperationContractUndertaker{
				CooperationContractUndertakerId: undertakerDomain.UndertakerId,
				CooperationContractNumber:       undertakerDomain.CooperationContractNumber,
				UserId:                          undertakerDomain.UserId,
				UserBaseId:                      undertakerDomain.UserBaseId,
				Org:                             undertakerDomain.Org,
				Orgs:                            undertakerDomain.Orgs,
				Department:                      undertakerDomain.Department,
				Roles:                           undertakerDomain.Roles,
				UserInfo:                        undertakerDomain.UserInfo,
				UserType:                        undertakerDomain.UserType,
				Referrer:                        undertakerDomain.Referrer,
				Salesman:                        undertakerDomain.Salesman,
				Status:                          undertakerDomain.Status,
				Company:                         undertakerDomain.Company,
				ContractAttachment:              undertakerDomain.ContractAttachment,
				UpdatedAt:                       time.Time{},
				DeletedAt:                       time.Time{},
				CreatedAt:                       time.Now(),
			})
		}
		log.Logger.Info("待添加的承接人", map[string]interface{}{
			"待添加的承接人": cooperationContractUndertakersToAddModels,
		})
		// 添加承接人
		if len(cooperationContractUndertakersToAddModels) > 0 {
			if _, err := tx.Model(&cooperationContractUndertakersToAddModels).Insert(); err != nil {
				return nil, err
			}
		}

		// 待更新或者删除的ids
		var cooperationContractUndertakersToUpdateOrDeleteIds []int64
		for _, cooperationContractUndertakerToUpdate := range cooperationContractUndertakersToUpdate {
			cooperationContractUndertakersToUpdateOrDeleteIds = append(cooperationContractUndertakersToUpdateOrDeleteIds, cooperationContractUndertakerToUpdate.UndertakerId)
		}

		// 待更新的承接人id
		undertakerIdsToUpdate := utils.Intersect(cooperationContractUndertakersIdsFetched, cooperationContractUndertakersToUpdateOrDeleteIds)
		var undertakerModelsToUpdate []*models.CooperationContractUndertaker
		for _, id := range undertakerIdsToUpdate {
			for _, undertakerModel := range cooperationContractUndertakersModelsFetched {
				if undertakerModel.CooperationContractUndertakerId == id {
					undertakerModelsToUpdate = append(undertakerModelsToUpdate, undertakerModel)
				}
			}
		}
		log.Logger.Info("待更新的承接人", map[string]interface{}{
			"待更新的承接人": undertakerModelsToUpdate,
		})
		for i, undertakerModelToUpdate := range undertakerModelsToUpdate {
			for _, undertaker := range cooperationContract.Undertakers {
				if undertaker.UndertakerId == undertakerModelToUpdate.CooperationContractUndertakerId {
					undertakerModelsToUpdate[i] = &models.CooperationContractUndertaker{
						CooperationContractUndertakerId: undertaker.UndertakerId,
						CooperationContractNumber:       undertaker.CooperationContractNumber,
						UserId:                          undertaker.UserId,
						UserBaseId:                      undertaker.UserBaseId,
						Org:                             undertaker.Org,
						Orgs:                            undertaker.Orgs,
						Department:                      undertaker.Department,
						Roles:                           undertaker.Roles,
						UserInfo:                        undertaker.UserInfo,
						UserType:                        undertaker.UserType,
						Referrer:                        undertaker.Referrer,
						Salesman:                        undertaker.Salesman,
						Status:                          undertaker.Status,
						Company:                         undertaker.Company,
						ContractAttachment:              undertaker.ContractAttachment,
						CreatedAt:                       undertakerModelToUpdate.CreatedAt,
						UpdatedAt:                       time.Now(),
						DeletedAt:                       undertakerModelToUpdate.DeletedAt,
					}
				}
			}
		}
		if len(undertakerModelsToUpdate) > 0 {
			if _, err := tx.Model(&undertakerModelsToUpdate).WherePK().Update(); err != nil {
				return nil, err
			}
		}

		// 待删除的承接人id
		undertakerIdsToDelete := utils.Difference(cooperationContractUndertakersIdsFetched, cooperationContractUndertakersToUpdateOrDeleteIds)
		var undertakerModelsToDelete []*models.CooperationContractUndertaker
		for _, id := range undertakerIdsToDelete {
			for _, undertakerModel := range cooperationContractUndertakersModelsFetched {
				if undertakerModel.CooperationContractUndertakerId == id {
					undertakerModelsToDelete = append(undertakerModelsToDelete, undertakerModel)
				}
			}
		}
		log.Logger.Info("待删除的承接人", map[string]interface{}{
			"待删除的承接人": undertakerModelsToDelete,
		})
		if len(undertakerModelsToDelete) > 0 {
			if _, err := tx.Model(&undertakerModelsToDelete).Delete(); err != nil {
				return nil, err
			}
		}

		/************************ 更新分红激励规则 **************************/
		// 获取分红激励规则列表
		var dividendsIncentivesRulesFetched []*models.DividendsIncentivesRule
		dividendsIncentivesRuleQuery := tx.Model(&dividendsIncentivesRulesFetched)
		if err := dividendsIncentivesRuleQuery.
			Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
			Select(); err != nil {
			return nil, err
		}

		// 提取分红激励规则id
		var dividendsIncentivesRuleIdsFetched []int64
		for _, dividendsIncentivesRule := range dividendsIncentivesRulesFetched {
			dividendsIncentivesRuleIdsFetched = append(dividendsIncentivesRuleIdsFetched, dividendsIncentivesRule.DividendsIncentivesRuleId)
		}

		// 待更新分红激励规则
		var dividendsIncentivesRulesToUpdate []*domain.DividendsIncentivesRule
		// 待添加分红激励规则
		var dividendsIncentivesRulesToAdd []*domain.DividendsIncentivesRule
		for _, dividendsIncentivesRule := range cooperationContract.DividendsIncentivesRules {
			if dividendsIncentivesRule.DividendsIncentivesRuleId != 0 {
				dividendsIncentivesRulesToUpdate = append(dividendsIncentivesRulesToUpdate, dividendsIncentivesRule)
			} else {
				dividendsIncentivesRulesToAdd = append(dividendsIncentivesRulesToAdd, dividendsIncentivesRule)
			}
		}

		// 将待添加的分红激励规则领域模型转换为数据模型
		var dividendsIncentivesRulesToAddModels []*models.DividendsIncentivesRule
		for _, dividendsIncentivesRuleDomain := range dividendsIncentivesRulesToAdd {
			if dividendsIncentivesRuleDomain.Identify() == nil {
				ruleId, err := repository.nextIdentify()
				if err != nil {
					return nil, err
				} else {
					dividendsIncentivesRuleDomain.DividendsIncentivesRuleId = ruleId
				}
			}
			dividendsIncentivesRulesToAddModels = append(dividendsIncentivesRulesToAddModels, &models.DividendsIncentivesRule{
				DividendsIncentivesRuleId:     dividendsIncentivesRuleDomain.DividendsIncentivesRuleId,
				CooperationContractNumber:     dividendsIncentivesRuleDomain.CooperationContractNumber,
				ReferrerPercentage:            dividendsIncentivesRuleDomain.ReferrerPercentage,
				SalesmanPercentage:            dividendsIncentivesRuleDomain.SalesmanPercentage,
				DividendsIncentivesPercentage: dividendsIncentivesRuleDomain.DividendsIncentivesPercentage,
				DividendsIncentivesStage:      dividendsIncentivesRuleDomain.DividendsIncentivesStage,
				DividendsIncentivesStageEnd:   dividendsIncentivesRuleDomain.DividendsIncentivesStageEnd,
				DividendsIncentivesStageStart: dividendsIncentivesRuleDomain.DividendsIncentivesStageStart,
				Remarks:                       dividendsIncentivesRuleDomain.Remarks,
				Org:                           dividendsIncentivesRuleDomain.Org,
				Company:                       dividendsIncentivesRuleDomain.Company,
				UpdatedAt:                     time.Time{},
				DeletedAt:                     time.Time{},
				CreatedAt:                     time.Now(),
			})
		}
		// 添加分红激励规则
		log.Logger.Info("待添加的分红激励规则", map[string]interface{}{
			"dividendsIncentivesRulesToAddModels": dividendsIncentivesRulesToAddModels,
		})
		if len(dividendsIncentivesRulesToAddModels) > 0 {
			if _, err := tx.Model(&dividendsIncentivesRulesToAddModels).Insert(); err != nil {
				return nil, err
			}
		}

		// 待更新或者删除的ids
		var dividendsIncentivesRulesToUpdateOrDeleteIds []int64
		for _, dividendsIncentivesRuleToUpdate := range dividendsIncentivesRulesToUpdate {
			dividendsIncentivesRulesToUpdateOrDeleteIds = append(dividendsIncentivesRulesToUpdateOrDeleteIds, dividendsIncentivesRuleToUpdate.DividendsIncentivesRuleId)
		}

		// 待更新的分红激励规则id
		dividendsRuleIdsToUpdate := utils.Intersect(dividendsIncentivesRuleIdsFetched, dividendsIncentivesRulesToUpdateOrDeleteIds)
		var dividendsRuleModelsToUpdate []*models.DividendsIncentivesRule
		for _, id := range dividendsRuleIdsToUpdate {
			for _, dividendsIncentivesRuleModel := range dividendsIncentivesRulesFetched {
				if dividendsIncentivesRuleModel.DividendsIncentivesRuleId == id {
					dividendsRuleModelsToUpdate = append(dividendsRuleModelsToUpdate, dividendsIncentivesRuleModel)
				}
			}
		}
		log.Logger.Info("待更新的分红激励规则", map[string]interface{}{
			"dividendsRuleModelsToUpdate": dividendsRuleModelsToUpdate,
		})

		if len(dividendsRuleModelsToUpdate) > 0 {
			for i, dividendsRuleModelToUpdate := range dividendsRuleModelsToUpdate {
				for _, dividendsRule := range cooperationContract.DividendsIncentivesRules {
					if dividendsRule.DividendsIncentivesRuleId == dividendsRuleModelToUpdate.DividendsIncentivesRuleId {
						dividendsRuleModelsToUpdate[i] = &models.DividendsIncentivesRule{
							DividendsIncentivesRuleId:     dividendsRuleModelToUpdate.DividendsIncentivesRuleId,
							CooperationContractNumber:     dividendsRuleModelToUpdate.CooperationContractNumber,
							ReferrerPercentage:            dividendsRuleModelToUpdate.ReferrerPercentage,
							SalesmanPercentage:            dividendsRuleModelToUpdate.SalesmanPercentage,
							DividendsIncentivesPercentage: dividendsRuleModelToUpdate.DividendsIncentivesPercentage,
							DividendsIncentivesStage:      dividendsRuleModelToUpdate.DividendsIncentivesStage,
							DividendsIncentivesStageEnd:   dividendsRuleModelToUpdate.DividendsIncentivesStageEnd,
							DividendsIncentivesStageStart: dividendsRuleModelToUpdate.DividendsIncentivesStageStart,
							Remarks:                       dividendsRuleModelToUpdate.Remarks,
							Org:                           dividendsRuleModelToUpdate.Org,
							Company:                       dividendsRuleModelToUpdate.Company,
							UpdatedAt:                     time.Now(),
							DeletedAt:                     dividendsRuleModelToUpdate.DeletedAt,
							CreatedAt:                     dividendsRuleModelToUpdate.CreatedAt,
						}
					}
				}
			}
			if _, err := tx.Model(&dividendsRuleModelsToUpdate).WherePK().Update(); err != nil {
				return nil, err
			}
		}

		// 待删除的分红激励规则id
		dividendsIncentivesRuleIdsToDelete := utils.Difference(dividendsIncentivesRuleIdsFetched, dividendsIncentivesRulesToUpdateOrDeleteIds)
		var dividendsIncentivesRuleModelsToDelete []*models.DividendsIncentivesRule
		for _, id := range dividendsIncentivesRuleIdsToDelete {
			for _, dividendsIncentivesRuleModel := range dividendsIncentivesRulesFetched {
				if dividendsIncentivesRuleModel.DividendsIncentivesRuleId == id {
					dividendsIncentivesRuleModelsToDelete = append(dividendsIncentivesRuleModelsToDelete, dividendsIncentivesRuleModel)
				}
			}
		}
		log.Logger.Info("待删除的分红激励规则", map[string]interface{}{})
		if len(dividendsIncentivesRuleModelsToDelete) > 0 {
			if _, err := tx.Model(&dividendsIncentivesRuleModelsToDelete).WherePK().Delete(); err != nil {
				return nil, err
			}
		}

		/********************** 更新金额激励规则 **************************/
		var moneyIncentivesRulesFetched []*models.MoneyIncentivesRule
		moneyIncentivesRuleQuery := tx.Model(&moneyIncentivesRulesFetched)
		if err := moneyIncentivesRuleQuery.
			Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
			Select(); err != nil {
			return nil, err
		}

		// 提取金额激励规则id
		var moneyIncentivesRuleIdsFetched []int64
		for _, moneyIncentivesRule := range moneyIncentivesRulesFetched {
			moneyIncentivesRuleIdsFetched = append(moneyIncentivesRuleIdsFetched, moneyIncentivesRule.MoneyIncentivesRuleId)
		}

		// 待更新金额激励规则
		var moneyIncentivesRulesToUpdate []*domain.MoneyIncentivesRule
		// 待添加金额激励规则
		var moneyIncentivesRulesToAdd []*domain.MoneyIncentivesRule
		for _, moneyIncentivesRule := range cooperationContract.MoneyIncentivesRules {
			if moneyIncentivesRule.MoneyIncentivesRuleId != 0 {
				moneyIncentivesRulesToUpdate = append(moneyIncentivesRulesToUpdate, moneyIncentivesRule)
			} else {
				moneyIncentivesRulesToAdd = append(moneyIncentivesRulesToAdd, moneyIncentivesRule)
			}
		}

		// 将待添加的金额激励规则领域模型转换为数据模型
		var moneyIncentivesRulesToAddModels []*models.MoneyIncentivesRule
		for _, moneyIncentivesRuleDomain := range moneyIncentivesRulesToAdd {
			if moneyIncentivesRuleDomain.Identify() == nil {
				ruleId, err := repository.nextIdentify()
				if err != nil {
					return nil, err
				} else {
					moneyIncentivesRuleDomain.MoneyIncentivesRuleId = ruleId
				}
			}
			moneyIncentivesRulesToAddModels = append(moneyIncentivesRulesToAddModels, &models.MoneyIncentivesRule{
				MoneyIncentivesRuleId:     moneyIncentivesRuleDomain.MoneyIncentivesRuleId,
				CooperationContractNumber: moneyIncentivesRuleDomain.CooperationContractNumber,
				MoneyIncentivesAmount:     moneyIncentivesRuleDomain.MoneyIncentivesAmount,
				MoneyIncentivesStage:      moneyIncentivesRuleDomain.MoneyIncentivesStage,
				MoneyIncentivesStageEnd:   moneyIncentivesRuleDomain.MoneyIncentivesStageEnd,
				MoneyIncentivesStageStart: moneyIncentivesRuleDomain.MoneyIncentivesStageStart,
				MoneyIncentivesTime:       moneyIncentivesRuleDomain.MoneyIncentivesTime,
				ReferrerPercentage:        moneyIncentivesRuleDomain.ReferrerPercentage,
				SalesmanPercentage:        moneyIncentivesRuleDomain.SalesmanPercentage,
				Remarks:                   moneyIncentivesRuleDomain.Remarks,
				Org:                       moneyIncentivesRuleDomain.Org,
				Company:                   moneyIncentivesRuleDomain.Company,
				UpdatedAt:                 time.Time{},
				DeletedAt:                 time.Time{},
				CreatedAt:                 time.Now(),
			})
		}
		// 添加金额激励规则
		log.Logger.Info("待添加的金额激励规则", map[string]interface{}{
			"moneyIncentivesRulesToAddModels": moneyIncentivesRulesToAddModels,
		})
		if len(moneyIncentivesRulesToAddModels) > 0 {
			if _, err := tx.Model(&moneyIncentivesRulesToAddModels).Insert(); err != nil {
				return nil, err
			}
		}

		// 待更新或者删除的ids
		var moneyIncentivesRulesToUpdateOrDeleteIds []int64
		for _, moneyIncentivesRuleToUpdate := range moneyIncentivesRulesToUpdate {
			moneyIncentivesRulesToUpdateOrDeleteIds = append(moneyIncentivesRulesToUpdateOrDeleteIds, moneyIncentivesRuleToUpdate.MoneyIncentivesRuleId)
		}

		// 待更新的金额激励规则id
		moneyRuleIdsToUpdate := utils.Intersect(moneyIncentivesRuleIdsFetched, moneyIncentivesRulesToUpdateOrDeleteIds)
		var moneyRuleModelsToUpdate []*models.MoneyIncentivesRule
		for _, id := range moneyRuleIdsToUpdate {
			for _, moneyIncentivesRuleModel := range moneyIncentivesRulesFetched {
				if moneyIncentivesRuleModel.MoneyIncentivesRuleId == id {
					moneyRuleModelsToUpdate = append(moneyRuleModelsToUpdate, moneyIncentivesRuleModel)
				}
			}
		}
		log.Logger.Info("待更新的金额激励规则", map[string]interface{}{
			"moneyRuleModelsToUpdate": moneyRuleModelsToUpdate,
		})
		if len(moneyRuleModelsToUpdate) > 0 {
			for i, moneyRuleModelToUpdate := range moneyRuleModelsToUpdate {
				for _, moneyRule := range cooperationContract.MoneyIncentivesRules {
					if moneyRule.MoneyIncentivesRuleId == moneyRuleModelToUpdate.MoneyIncentivesRuleId {
						moneyRuleModelsToUpdate[i] = &models.MoneyIncentivesRule{
							MoneyIncentivesRuleId:     moneyRule.MoneyIncentivesRuleId,
							CooperationContractNumber: moneyRule.CooperationContractNumber,
							MoneyIncentivesAmount:     moneyRule.MoneyIncentivesAmount,
							MoneyIncentivesStage:      moneyRule.MoneyIncentivesStage,
							MoneyIncentivesStageEnd:   moneyRule.MoneyIncentivesStageEnd,
							MoneyIncentivesStageStart: moneyRule.MoneyIncentivesStageStart,
							MoneyIncentivesTime:       moneyRule.MoneyIncentivesTime,
							ReferrerPercentage:        moneyRule.MoneyIncentivesAmount,
							SalesmanPercentage:        moneyRule.MoneyIncentivesAmount,
							Remarks:                   moneyRule.Remarks,
							Org:                       moneyRule.Org,
							Company:                   moneyRule.Company,
							UpdatedAt:                 time.Now(),
							DeletedAt:                 moneyRuleModelToUpdate.DeletedAt,
							CreatedAt:                 moneyRuleModelToUpdate.CreatedAt,
						}
					}
				}
			}
			if _, err := tx.Model(&moneyRuleModelsToUpdate).WherePK().Update(); err != nil {
				return nil, err
			}
		}

		// 待删除的金额激励规则id
		moneyIncentivesRuleIdsToDelete := utils.Difference(moneyIncentivesRuleIdsFetched, moneyIncentivesRulesToUpdateOrDeleteIds)
		var moneyIncentivesRuleModelsToDelete []*models.MoneyIncentivesRule
		for _, id := range moneyIncentivesRuleIdsToDelete {
			for _, moneyIncentivesRuleModel := range moneyIncentivesRulesFetched {
				if moneyIncentivesRuleModel.MoneyIncentivesRuleId == id {
					moneyIncentivesRuleModelsToDelete = append(moneyIncentivesRuleModelsToDelete, moneyIncentivesRuleModel)
				}
			}
		}
		log.Logger.Info("待删除的金额激励规则", map[string]interface{}{
			"moneyIncentivesRuleModelsToDelete": moneyIncentivesRuleModelsToDelete,
		})
		if len(moneyIncentivesRuleModelsToDelete) > 0 {
			if _, err := tx.Model(&moneyIncentivesRuleModelsToDelete).WherePK().Delete(); err != nil {
				return nil, err
			}
		}
	}
	// 返回新增的合约
	cooperationContractSaved, err := repository.FindOne(map[string]interface{}{
		"cooperationContractId": cooperationContract.CooperationContractId,
	})
	if err != nil {
		return nil, err
	}
	return cooperationContractSaved, nil
}

func (repository *CooperationContractRepository) UpdateOne(cooperationContract *domain.CooperationContract) (*domain.CooperationContract, error) {
	tx := repository.transactionContext.PgTx
	cooperationContractModel := new(models.CooperationContract)
	cooperationContractModel = &models.CooperationContract{
		CooperationContractId:              cooperationContract.CooperationContractId,
		CooperationContractDescription:     cooperationContract.CooperationContractDescription,
		CooperationContractName:            cooperationContract.CooperationContractName,
		CooperationContractNumber:          cooperationContract.CooperationContractNumber,
		CooperationProjectNumber:           cooperationContract.CooperationProjectNumber,
		CooperationContractUndertakerTypes: cooperationContract.CooperationContractUndertakerTypes,
		CooperationContractSponsor:         cooperationContract.CooperationContractSponsor,
		CooperationModeNumber:              cooperationContract.CooperationMode.CooperationModeNumber,
		Status:                             cooperationContract.Status,
		Org:                                cooperationContract.Org,
		IncentivesType:                     cooperationContract.IncentivesType,
		Company:                            cooperationContract.Company,
		Department:                         cooperationContract.Department,
		Operator:                           cooperationContract.Operator,
		OperateTime:                        cooperationContract.OperateTime,
		CreatedAt:                          cooperationContract.CreatedAt,
		DeletedAt:                          cooperationContract.DeletedAt,
		UpdatedAt:                          time.Now(),
	}
	if _, err := tx.Model(cooperationContractModel).WherePK().Update(); err != nil {
		return nil, err
	}
	return cooperationContract, nil
}

func (repository *CooperationContractRepository) UpdateMany(cooperationContracts []*domain.CooperationContract) ([]*domain.CooperationContract, error) {
	tx := repository.transactionContext.PgTx
	var cooperationContractModels []*models.CooperationContract
	for _, cooperationContract := range cooperationContracts {
		cooperationContractModels = append(cooperationContractModels, &models.CooperationContract{
			CooperationContractId:              cooperationContract.CooperationContractId,
			CooperationContractDescription:     cooperationContract.CooperationContractDescription,
			CooperationContractName:            cooperationContract.CooperationContractName,
			CooperationContractNumber:          cooperationContract.CooperationContractNumber,
			CooperationProjectNumber:           cooperationContract.CooperationProjectNumber,
			CooperationContractUndertakerTypes: cooperationContract.CooperationContractUndertakerTypes,
			CooperationContractSponsor:         cooperationContract.CooperationContractSponsor,
			CooperationModeNumber:              cooperationContract.CooperationMode.CooperationModeNumber,
			Status:                             cooperationContract.Status,
			Org:                                cooperationContract.Org,
			IncentivesType:                     cooperationContract.IncentivesType,
			Company:                            cooperationContract.Company,
			Department:                         cooperationContract.Department,
			Operator:                           cooperationContract.Operator,
			OperateTime:                        cooperationContract.OperateTime,
			CreatedAt:                          cooperationContract.CreatedAt,
			DeletedAt:                          cooperationContract.DeletedAt,
			UpdatedAt:                          time.Now(),
		})
	}
	if _, err := tx.Model(&cooperationContractModels).WherePK().Update(); err != nil {
		return nil, err
	}
	return cooperationContracts, nil
}

func (repository *CooperationContractRepository) Remove(cooperationContract *domain.CooperationContract) (*domain.CooperationContract, error) {
	tx := repository.transactionContext.PgTx
	cooperationContractModel := new(models.CooperationContract)
	cooperationContractModel.CooperationContractId = cooperationContract.Identify().(int64)
	if _, err := tx.Model(cooperationContractModel).WherePK().Delete(); err != nil {
		return cooperationContract, err
	} else {
		// 获取分红激励规则列表
		var dividendsIncentivesRuleModels []*models.DividendsIncentivesRule
		dividendsIncentivesRuleQuery := tx.Model(&dividendsIncentivesRuleModels)
		if err := dividendsIncentivesRuleQuery.
			Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
			Select(); err != nil {
			return nil, err
		} else {
			if len(dividendsIncentivesRuleModels) > 0 {
				if _, err := tx.Model(&dividendsIncentivesRuleModels).WherePK().Delete(); err != nil {
					return nil, err
				}
			}
		}
		// 获取金额激励规则列表
		var moneyIncentivesRuleModels []*models.MoneyIncentivesRule
		moneyIncentivesRuleQuery := tx.Model(&moneyIncentivesRuleModels)
		if err := moneyIncentivesRuleQuery.
			Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
			Select(); err != nil {
			return nil, err
		} else {
			if len(moneyIncentivesRuleModels) > 0 {
				if _, err := tx.Model(&moneyIncentivesRuleModels).WherePK().Delete(); err != nil {
					return nil, err
				}
			}
		}
		// 获取承接人列表
		var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
		cooperationContractUndertakerQuery := tx.Model(&cooperationContractUndertakerModels)
		if err := cooperationContractUndertakerQuery.
			Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
			Select(); err != nil {
			return nil, err
		} else {
			if _, err := tx.Model(&cooperationContractUndertakerModels).WherePK().Delete(); err != nil {
				return nil, err
			}
		}
		// 获取相关人列表
		var cooperationContractRelevantModels []*models.CooperationContractRelevant
		cooperationContractRelevantQuery := tx.Model(&cooperationContractRelevantModels)
		if err := cooperationContractRelevantQuery.
			Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
			Select(); err != nil {
			return nil, err
		} else {
			if len(cooperationContractRelevantModels) > 0 {
				if _, err := tx.Model(&cooperationContractRelevantModels).WherePK().Delete(); err != nil {
					return nil, err
				}
			}
		}
	}
	return cooperationContract, nil
}

// BatchRemove 批量删除
func (repository *CooperationContractRepository) BatchRemove(cooperationContracts []*domain.CooperationContract) ([]*domain.CooperationContract, error) {
	tx := repository.transactionContext.PgTx
	var cooperationContractModels []*models.CooperationContract
	for _, cooperationContract := range cooperationContracts {
		cooperationContractModels = append(cooperationContractModels, &models.CooperationContract{
			CooperationContractId: cooperationContract.Identify().(int64),
		})
	}
	if _, err := tx.Model(&cooperationContractModels).WherePK().Delete(); err != nil {
		return cooperationContracts, err
	} else {
		for _, cooperationContract := range cooperationContracts {
			// 获取分红激励规则列表
			var dividendsIncentivesRuleModels []*models.DividendsIncentivesRule
			dividendsIncentivesRuleQuery := tx.Model(&dividendsIncentivesRuleModels)
			if err := dividendsIncentivesRuleQuery.
				Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
				Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
				Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
				Select(); err != nil {
				return nil, fmt.Errorf("分红激励规则不存在:" + err.Error())
			} else {
				if len(dividendsIncentivesRuleModels) > 0 {
					if _, err := tx.Model(&dividendsIncentivesRuleModels).WherePK().Delete(); err != nil {
						return nil, err
					}
				}
			}
			// 获取金额激励规则列表
			var moneyIncentivesRuleModels []*models.MoneyIncentivesRule
			moneyIncentivesRuleQuery := tx.Model(&moneyIncentivesRuleModels)
			if err := moneyIncentivesRuleQuery.
				Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
				Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
				Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
				Select(); err != nil {
				return nil, fmt.Errorf("金额激励规则列表不存在:" + err.Error())
			} else {
				if len(moneyIncentivesRuleModels) > 0 {
					if _, err := tx.Model(&moneyIncentivesRuleModels).WherePK().Delete(); err != nil {
						return nil, err
					}
				}
			}
			// 获取承接人列表
			var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
			cooperationContractUndertakerQuery := tx.Model(&cooperationContractUndertakerModels)
			if err := cooperationContractUndertakerQuery.
				Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
				Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
				Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
				Select(); err != nil {
				return nil, fmt.Errorf("合约承接人不存在:" + err.Error())
			} else {
				if len(cooperationContractUndertakerModels) > 0 {
					if _, err := tx.Model(&cooperationContractUndertakerModels).WherePK().Delete(); err != nil {
						return nil, err
					}
				}
			}
			// 获取相关人列表
			var cooperationContractRelevantModels []*models.CooperationContractRelevant
			cooperationContractRelevantQuery := tx.Model(&cooperationContractRelevantModels)
			if err := cooperationContractRelevantQuery.
				Where("company->>'companyId' = '?'", cooperationContract.Company.CompanyId).
				Where("org->>'orgId' = '?'", cooperationContract.Org.OrgId).
				Where("cooperation_contract_number = ?", cooperationContract.CooperationContractNumber).
				Select(); err != nil {
				return nil, fmt.Errorf("合约相关人存在:" + err.Error())
			} else {
				if len(cooperationContractRelevantModels) > 0 {
					if _, err := tx.Model(&cooperationContractRelevantModels).WherePK().Delete(); err != nil {
						return nil, err
					}
				}
			}
		}
	}
	return cooperationContracts, nil
}

func (repository *CooperationContractRepository) FindOne(queryOptions map[string]interface{}) (*domain.CooperationContract, error) {
	tx := repository.transactionContext.PgTx
	cooperationContractModel := new(models.CooperationContract)
	query := sqlbuilder.BuildQuery(tx.Model(cooperationContractModel), queryOptions)
	query.SetWhereByQueryOption("cooperation_contract.cooperation_contract_id = ?", "cooperationContractId")
	query.SetWhereByQueryOption("cooperation_contract.cooperation_contract_number = ?", "cooperationContractNumber")
	if err := query.First(); err != nil {
		if err.Error() == "pg: no rows in result set" {
			return nil, fmt.Errorf("共创合约不存在")
		} else {
			return nil, err
		}
	}
	if cooperationContractModel.CooperationContractId == 0 {
		return nil, nil
	} else {
		// 获取共创模式
		cooperationModeModels := new(models.CooperationMode)
		cooperationModeQuery := tx.Model(cooperationModeModels)
		if err := cooperationModeQuery.
			Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
			Where("cooperation_mode_number = ?", cooperationContractModel.CooperationModeNumber).
			First(); err != nil {
			return nil, fmt.Errorf("共创合约关联的共创模式不存在")
		}
		// 获取分红激励规则列表
		var dividendsIncentivesRuleModels []*models.DividendsIncentivesRule
		dividendsIncentivesRuleQuery := tx.Model(&dividendsIncentivesRuleModels)
		if err := dividendsIncentivesRuleQuery.
			Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).
			Select(); err != nil {
			return nil, fmt.Errorf("共创合约关联的分红激励规则不存在")
		}
		// 获取金额激励规则列表
		var moneyIncentivesRuleModels []*models.MoneyIncentivesRule
		moneyIncentivesRuleQuery := tx.Model(&moneyIncentivesRuleModels)
		if err := moneyIncentivesRuleQuery.
			Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).
			Select(); err != nil {
			return nil, fmt.Errorf("共创合约关联的金额激励规则不存在")
		}
		// 获取承接人列表
		var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
		cooperationContractUndertakerQuery := tx.Model(&cooperationContractUndertakerModels)
		if err := cooperationContractUndertakerQuery.
			Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).
			Select(); err != nil {
			return nil, fmt.Errorf("合约承接人不存在")
		}
		// 获取相关人列表
		var cooperationContractRelevantModels []*models.CooperationContractRelevant
		cooperationContractRelevantQuery := tx.Model(&cooperationContractRelevantModels)
		if err := cooperationContractRelevantQuery.
			Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
			Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
			Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).
			Select(); err != nil {
			return nil, fmt.Errorf("合约相关人不存在")
		}
		return transform.TransformToCooperationContractDomainModelFromPgModels(
			cooperationContractModel,
			cooperationModeModels,
			dividendsIncentivesRuleModels,
			moneyIncentivesRuleModels,
			cooperationContractRelevantModels,
			cooperationContractUndertakerModels)
	}
}

func (repository *CooperationContractRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.CooperationContract, error) {
	tx := repository.transactionContext.PgTx
	var cooperationContractModels []*models.CooperationContract
	cooperationContracts := make([]*domain.CooperationContract, 0)
	query := sqlbuilder.BuildQuery(tx.Model(&cooperationContractModels), queryOptions)
	if cooperationContractNumber, ok := queryOptions["cooperationContractNumber"]; ok && cooperationContractNumber != "" {
		query.Where("cooperation_contract_number ilike ?", fmt.Sprintf("%%%s%%", cooperationContractNumber))
	}
	if cooperationContractName, ok := queryOptions["cooperationContactName"]; ok && cooperationContractName != "" {
		query.Where("cooperation_contract_name like ?", fmt.Sprintf("%%%s%%", cooperationContractName))
	}
	if departmentName, ok := queryOptions["departmentName"]; ok && departmentName != "" {
		query.Where(`(cooperation_contract.department->>'departmentName')::test LIKE ?`, fmt.Sprintf("%%%s%%", departmentName))
	}
	if sponsorName, ok := queryOptions["sponsorName"]; ok && sponsorName != "" {
		query.Where(`(cooperation_contract.cooperation_contract_sponsor->>'userName')::text LIKE ?`, fmt.Sprintf("%%%s%%", sponsorName))
	}
	if cooperationContractIds, ok := queryOptions["cooperationContractIds"]; ok && len(cooperationContractIds.([]int64)) != 0 {
		query.Where("cooperation_contract_id in (?)", pg.In(cooperationContractIds))
	}
	if companyId, ok := queryOptions["companyId"]; ok && companyId.(int64) != 0 {
		query.Where("company->>'companyId' = '?'", companyId)
	}
	if orgId, ok := queryOptions["orgId"]; ok && orgId.(int64) != 0 {
		query.Where("org->>'orgId' = '?'", orgId)
	}
	if orgIds, ok := queryOptions["orgIds"]; ok && len(orgIds.([]int64)) > 0 {
		newOrgIds := utils.SliceItoa(orgIds.([]int64))
		query.Where("org->>'orgId' in (?)", pg.In(newOrgIds))
	}
	if incentivesType, ok := queryOptions["incentivesType"]; ok && incentivesType.(int32) != 0 {
		query.Where("incentives_type = ?", incentivesType)
	}
	offsetLimitFlag := true
	if offsetLimit, ok := queryOptions["offsetLimit"]; ok {
		offsetLimitFlag = offsetLimit.(bool)
	}
	if offsetLimitFlag {
		query.SetOffsetAndLimit(20)
	}
	query.SetOrderDirect("cooperation_contract_id", "DESC")
	if count, err := query.SelectAndCount(); err != nil {
		return 0, cooperationContracts, err
	} else {
		if count > 0 {
			for _, cooperationContractModel := range cooperationContractModels {
				// 获取共创模式
				var cooperationModeModels []*models.CooperationMode
				cooperationModeQuery := tx.Model(&cooperationModeModels)
				if countMode, err := cooperationModeQuery.
					Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
					Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
					Where("cooperation_mode_number = ?", cooperationContractModel.CooperationModeNumber).
					Limit(1).
					SelectAndCount(); err != nil {
					log.Logger.Error("合约关联的共创模式不存在", map[string]interface{}{
						"cooperationContractModel": cooperationContractModel,
					})
				} else {
					if countMode > 0 {
						// 获取分红激励规则列表
						var dividendsIncentivesRuleModels []*models.DividendsIncentivesRule
						dividendsIncentivesRuleQuery := tx.Model(&dividendsIncentivesRuleModels)
						if err := dividendsIncentivesRuleQuery.
							Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
							Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
							Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).
							Select(); err != nil {
							return 0, nil, fmt.Errorf("合约关联的分红激励规则列表不存在")
						}
						// 获取金额激励规则列表
						var moneyIncentivesRuleModels []*models.MoneyIncentivesRule
						moneyIncentivesRuleQuery := tx.Model(&moneyIncentivesRuleModels)
						if err := moneyIncentivesRuleQuery.
							Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
							Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
							Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).
							Select(); err != nil {
							return 0, nil, fmt.Errorf("合约关联的金额激励规则列表不存在")
						}
						// 获取承接人列表
						var cooperationContractUndertakerModels []*models.CooperationContractUndertaker
						cooperationContractUndertakerQuery := tx.Model(&cooperationContractUndertakerModels)
						if err := cooperationContractUndertakerQuery.
							Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
							Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
							Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).
							Select(); err != nil {
							return 0, nil, fmt.Errorf("合约相关的承接人列表不存在")
						}
						// 获取相关人列表
						var cooperationContractRelevantModels []*models.CooperationContractRelevant
						cooperationContractRelevantQuery := tx.Model(&cooperationContractRelevantModels)
						if err := cooperationContractRelevantQuery.
							Where("company->>'companyId' = '?'", cooperationContractModel.Company.CompanyId).
							Where("org->>'orgId' = '?'", cooperationContractModel.Org.OrgId).
							Where("cooperation_contract_number = ?", cooperationContractModel.CooperationContractNumber).
							Select(); err != nil {
							return 0, nil, fmt.Errorf("合约相关的相关人列表不存在")
						}
						if cooperationContract, err := transform.TransformToCooperationContractDomainModelFromPgModels(
							cooperationContractModel,
							cooperationModeModels[0],
							dividendsIncentivesRuleModels,
							moneyIncentivesRuleModels,
							cooperationContractRelevantModels,
							cooperationContractUndertakerModels); err != nil {
							return 0, cooperationContracts, err
						} else {
							cooperationContracts = append(cooperationContracts, cooperationContract)
						}
					}
				}
			}
		}
		return int64(count), cooperationContracts, nil
	}
}

func NewCooperationContractRepository(transactionContext *pgTransaction.TransactionContext) (*CooperationContractRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		idWorker, err := snowflake.NewIdWorker(1)
		if err != nil {
			return nil, err
		}
		return &CooperationContractRepository{
			transactionContext: transactionContext,
			IdWorker:           idWorker,
		}, nil
	}
}