pg_cooperation_statistics_service.go 26.8 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
package domain_service

import (
	"fmt"
	"github.com/go-pg/pg/v10"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"github.com/linmadan/egglib-go/utils/tool_funs"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/dao"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/repository"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/utils"
	"time"
)

const (
	// 合约分红列表查询
	SearchContractDividends = "SearchContractDividends"
	// 获取分红合约详情
	GetContractDividends = "GetContractDividends"
	// 分红统计(分红明细)
	DividendsStatistics = "DividendsStatistics"

	// 企业-商品统计
	CooperationGoodsStatistics = "cooperationGoodsStatistics"
	// 企业-共创模式统计
	CooperationModeStatistics = "CooperationModeStatistics"
	// 企业-分红统计
	CompanyDividendsStatistics = "CompanyDividendsStatistics"
	// 企业、个人 - 分红预算列表
	SearchDividendsEstimates = "SearchDividendsEstimates"
	// 公司 - 共创用户统计
	CompanyCooperationUsersStatistics = "CompanyCooperationUsersStatistics"
	//公司 - 共创用户模式统计
	CooperationUserModeStatistics = "CooperationUserModeStatistics"
	// 公司 - 共创用户分红支付统计
	CompanyPaymentHistoryStatistics = "CompanyPaymentHistoryStatistics"
	// 企业共创项目 - 合约列表
	CompanyCooperationProjectContracts = "CompanyCooperationProjectContracts"

	// 个人 - 共创企业统计
	CooperationCompanyStatistics = "CooperationCompanyStatistics"
	// 个人 - 用户合约统计
	PersonCooperationContractStatistics = "PersonCooperationContractStatistics"
	// 个人 - 企业支付统计
	PersonCompanyPaymentHistoryStatistics = "PersonCompanyPaymentHistoryStatistics"
	// 个人 - 共创项目共享信息数据
	PersonCooperationProjectSharedInfo = "PersonCooperationProjectSharedInfo"
	// 个人 - 共创项目共享信息数据 - 附件
	PersonCooperationProjectSharedInfoAttachment = "PersonCooperationProjectSharedInfoAttachment"
	// 个人 - 共创企业
	PersonCooperationCompany = "PersonCooperationCompany"

	// 账期结算单统计
	CreditAccountStatistics = "CreditAccountStatistics"
	// 公司/个人 - 支付历史统计直方图
	PaymentHistoryHistogramStatistics = "PaymentHistoryHistogramStatistics"
	// 用户相关的项目合约编号列表查询
	RelevantCooperationContractNumbers = "RelevantCooperationContractNumbers"
)

//  CooperationStatisticsService 共创统计服务
type CooperationStatisticsService struct {
	transactionContext *pgTransaction.TransactionContext
}

func NewCooperationStatisticsService(transactionContext *pgTransaction.TransactionContext) (*CooperationStatisticsService, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &CooperationStatisticsService{
			transactionContext: transactionContext,
		}, nil
	}
}

/*****   1.合约分红模块  *****/

/*1.1 分红合约搜索*/

// 分红合约搜索
//
// queryOptions 查询参数
func (ptr *CooperationStatisticsService) SearchContractDividends(queryOptions map[string]interface{}) (interface{}, error) {
	var request = struct {
		//企业
		CompanyId int64 `json:"companyId"`
		OrgId     int64 `json:"orgId"`
		UserId    int64 `json:"userId"`
		//个人
		UserBaseId int64 `json:"userBaseId"`
		Offset     int   `json:"offset"`
		Limit      int   `json:"limit"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	// 1.根据个人、企业查询合约列表
	var contracts []*domain.CooperationContract
	var err error
	if request.UserBaseId > 0 {
		contracts, err = ptr.getUserContracts(request.OrgId, request.UserBaseId, queryOptions)
	} else if request.OrgId > 0 {
		queryOptions["orgId"] = request.OrgId
		contracts, err = ptr.getCompanyContracts(request.OrgId, request.UserId, queryOptions)
	}
	if err != nil {
		return nil, err
	}

	// 1.1 个人返回合约对应的项目

	var mapProject = make(map[int64]*domain.CooperationProject)
	var projectIds = domain.CooperationContractsToProjectIds(contracts)
	if request.UserBaseId > 0 && len(projectIds) > 0 {
		cooperationProjectRepository, _ := repository.NewCooperationProjectRepository(ptr.transactionContext)
		mapProject, err = domain.CooperationProjectsToMap(map[string]interface{}{"cooperationProjectIds": projectIds}, cooperationProjectRepository.Find)
		if err != nil {
			return nil, err
		}
	}

	// 2.根据合约查询分红预算
	orderGoodDao, _ := dao.NewDividendsOrderDao(ptr.transactionContext)
	dividendsEstimateDao, _ := dao.NewDividendsEstimateDao(ptr.transactionContext)
	var numbers []string
	var results = make([]*searchContractDividendsResult, 0)
	for i := range contracts {
		item := contracts[i]
		resultItem := &searchContractDividendsResult{
			CooperationContractId:     item.CooperationContractId,
			CooperationContractName:   item.CooperationContractName,
			CooperationContractNumber: item.CooperationContractNumber,
			Status:                    item.Status,
			CreatedAt:                 item.CreatedAt.Unix() * 1000,
		}
		resultItem.DividendsOrderAmount, _ = orderGoodDao.CalculateGoodOrderAmount(map[string]interface{}{"orgId": request.OrgId, "cooperationContractNumbers": []string{item.CooperationContractNumber}})
		resultItem.DividendsAmount, _ = dividendsEstimateDao.CountDividendsEstimateDividendsAmount(map[string]interface{}{"orgId": request.OrgId, "userBaseId": request.UserBaseId, "cooperationContractNumbers": []string{item.CooperationContractNumber}})
		if v, ok := mapProject[item.CooperationProjectId]; ok {
			resultItem.Project = v.CloneSimple()
		}
		results = append(results, resultItem)
		numbers = append(numbers, item.CooperationContractNumber)
	}
	return results, nil
}

// getUserContracts  获取用户的合约列表
//
// p1 p1_desc
func (ptr *CooperationStatisticsService) getUserContracts(orgId, userBaseId int64, queryOptions map[string]interface{}) ([]*domain.CooperationContract, error) {
	var contracts = make([]*domain.CooperationContract, 0)
	if userBaseId == 0 {
		return contracts, nil
	}
	contractNumbers, err := ptr.getUnderTakerContracts(map[string]interface{}{"orgId": orgId, "userBaseId": userBaseId})
	if len(contractNumbers) == 0 {
		return contracts, nil
	}
	if err != nil {
		return contracts, err
	}
	queryOptions["cooperationContractNumbers"] = contractNumbers
	contractRepository, _ := dao.NewCooperationContractDao(ptr.transactionContext)
	_, contracts, err = contractRepository.Find(queryOptions)
	return contracts, err
}

// getCompanyContracts  获取组织合约列表
//
// p1 p1_desc
func (ptr *CooperationStatisticsService) getCompanyContracts(orgId, userId int64, queryOptions map[string]interface{}) ([]*domain.CooperationContract, error) {
	var contracts = make([]*domain.CooperationContract, 0)
	if userId == 0 {
		return contracts, nil
	}
	contractNumbers, err := ptr.getRelevantContracts(map[string]interface{}{"orgId": orgId, "userId": userId})
	if len(contractNumbers) == 0 {
		return contracts, nil
	}
	if err != nil {
		return contracts, err
	}
	queryOptions["cooperationContractNumbers"] = contractNumbers
	contractRepository, _ := dao.NewCooperationContractDao(ptr.transactionContext)
	_, contracts, err = contractRepository.Find(queryOptions)
	return contracts, err
}

//  getUnderTakerContracts 获取承接人的合约
func (ptr *CooperationStatisticsService) getUnderTakerContracts(queryOptions map[string]interface{}) ([]string, error) {
	undertakerRepository, _ := dao.NewCooperationContractUndertakerDao(ptr.transactionContext)
	_, undertakers, err := undertakerRepository.Find(queryOptions)
	var numbers []string
	for i := range undertakers {
		numbers = append(numbers, undertakers[i].CooperationContractNumber)
	}
	if len(numbers) == 0 {
		return []string{}, nil
	}
	return numbers, err
}

//getRelevantContracts  获取相关人的合约
func (ptr *CooperationStatisticsService) getRelevantContracts(queryOptions map[string]interface{}) ([]string, error) {
	undertakerRepository, _ := repository.NewCooperationContractRelevantRepository(ptr.transactionContext)
	_, undertakers, err := undertakerRepository.Find(queryOptions)
	var numbers []string
	for i := range undertakers {
		numbers = append(numbers, undertakers[i].CooperationContractNumber)
	}
	if len(numbers) == 0 {
		return []string{}, nil
	}
	return numbers, err
}

// getContractsDividendsEstimate 合约分红预算
func (ptr *CooperationStatisticsService) getContractsDividendsEstimate(numbers []string) (map[string]*domain.DividendsEstimate, error) {
	var estimates []*domain.DividendsEstimate
	var resMap = make(map[string]*domain.DividendsEstimate)
	if len(numbers) == 0 {
		return resMap, nil
	}
	_, err := ptr.transactionContext.PgDd.Query(&estimates, `select cooperation_contract_number,sum(dividends_amount) dividends_amount from dividends_estimates 
where cooperation_contract_number in (?)
group by cooperation_contract_number
`, pg.In(numbers))
	if err != nil {
		return nil, err
	}

	for i := range estimates {
		resMap[estimates[i].CooperationContractNumber] = estimates[i]
	}
	return resMap, nil
}

// getContractsDividendsEstimate 合约分红预算 TODO:合约编号
func (ptr *CooperationStatisticsService) getContractsCreditAccount(numbers []string) (map[string]*domain.CreditAccount, error) {
	var creditAccounts []*domain.CreditAccount
	var resMap = make(map[string]*domain.CreditAccount)
	if len(numbers) == 0 {
		return resMap, nil
	}
	var creditAccount = new(domain.CreditAccount)

	query := ptr.transactionContext.PgDd.Model(creditAccount)
	query.Column("cooperation_contract_number")
	query.ColumnExpr("sum(good_amount_count) good_amount_count")
	query.ColumnExpr("sum(settlement_amount) settlement_amount")
	query.Where("cooperation_contract_number in (?)", pg.In(numbers))
	query.Where("deleted_at is null")
	query.Group("cooperation_contract_number")
	err := query.Select(&creditAccounts)
	if err != nil {
		return nil, err
	}

	for i := range creditAccounts {
		resMap[creditAccounts[i].CooperationContractNumber] = creditAccounts[i]
	}
	return resMap, nil
}

type searchContractDividendsResult struct {
	// 共创合约ID
	CooperationContractId int64 `json:"cooperationContractId,string"`
	// 共创合约名称
	CooperationContractName string `json:"cooperationContractName"`
	// 共创合约编号
	CooperationContractNumber string `json:"cooperationContractNumber"`
	// 合约状态,1恢复,2暂停
	Status int32 `json:"cooperationContractStatus"`
	// 分红预算
	DividendsAmount float64 `json:"dividendsAmount"`
	// 分红订单金额
	DividendsOrderAmount float64 `json:"dividendsOrderAmount"`
	// 创建时间
	CreatedAt int64 `json:"createdAt"`
	// 共创项目数据
	Project interface{} `json:"project"`
}

/*1.2 分红合约详情*/

//GetContractDividends 分红合约详情
//
// queryOptions 查询参数
func (ptr *CooperationStatisticsService) GetContractDividends(queryOptions map[string]interface{}) (interface{}, error) {
	var request = struct {
		//企业
		CompanyId int64 `json:"companyId" `
		//OrgId     int64 `json:"orgId"`
		//UserId    int64 `json:"userId"`
		//个人
		UserBaseId int64 `json:"userBaseId"`
		//Offset     int   `json:"offset"`
		//Limit      int   `json:"limit"`
		ContractId int `json:"contractId" valid:"Required"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)
	// 1.合约详情
	contractRepository, _ := dao.NewCooperationContractDao(ptr.transactionContext)
	if _, ok := queryOptions["contractId"]; !ok {
		return nil, fmt.Errorf("合约ID(contractId)不能为空")
	}
	var res = make(map[string]interface{})
	contract, err := contractRepository.FindOne(map[string]interface{}{"cooperationContractId": queryOptions["contractId"]})
	if err != nil {
		return nil, err
	}
	mapContract := map[string]interface{}{
		"cooperationContractDescription": contract.CooperationContractDescription,
		"cooperationContractId":          contract.CooperationContractId,
		"cooperationContractName":        contract.CooperationContractName,
		"cooperationContractNumber":      contract.CooperationContractNumber,
		"createdAt":                      contract.CreatedAt.Unix() * 1000,
		"status":                         contract.Status,
	}
	if request.UserBaseId > 0 {
		// 1.1.合约第一条合同的附件
		undertakerRepository, _ := repository.NewCooperationContractUndertakerRepository(ptr.transactionContext)
		_, undertakers, err := undertakerRepository.Find(map[string]interface{}{"cooperationContractId": contract.CooperationContractId, "userBaseId": request.UserBaseId, "companyId": contract.Company.CompanyId, "orgId": contract.Org.OrgId, "offsetLimit": false})
		if err != nil {
			return nil, err
		}
		for i := range undertakers {
			if len(undertakers[i].Undertaker.ContractAttachment) > 0 && len(undertakers[i].Undertaker.ContractAttachment[0].Url) > 0 {
				mapContract["contractAttachment"] = undertakers[i].Undertaker.ContractAttachment[0]
			}
		}
	}

	res["cooperationContract"] = mapContract

	// 2.合约分红列表
	dividendsEstimateRepository, _ := repository.NewDividendsEstimateRepository(ptr.transactionContext)
	queryOptions["cooperationContractNumber"] = contract.CooperationContractNumber
	queryOptions["orgId"] = contract.Org.OrgId
	queryOptions["isCanceled"] = false
	_, dividendsEstimates, err := dividendsEstimateRepository.Find(queryOptions)
	if err != nil {
		return res, err
	}

	// 3.取订单商品列表
	var orderGoodIds []int64
	for i := range dividendsEstimates {
		a := dividendsEstimates[i]
		orderGoodIds = append(orderGoodIds, a.OrderGoodId)
	}
	var mapOrderGoods = make(map[int64]*domain.OrderGood)
	if len(orderGoodIds) > 0 {
		orderGoodRepository, _ := repository.NewOrderGoodRepository(ptr.transactionContext)
		_, orderGoods, err := orderGoodRepository.Find(map[string]interface{}{"orderGoodIds": orderGoodIds})
		if err != nil {
			return res, err
		}
		for i := range orderGoods {
			mapOrderGoods[orderGoods[i].OrderGoodId] = orderGoods[i]
		}
	}

	var dividends = make([]interface{}, 0)
	for i := range dividendsEstimates {
		a := dividendsEstimates[i]
		// 个人查看的时候只查看自己的分红明细
		//if request.UserBaseId!=0 && a.DividendsUser.UserBaseId!=request.UserBaseId{
		//	continue
		//}
		item := map[string]interface{}{
			"dividendsEstimateId": a.DividendsEstimateId,
			"orderGoodName":       "",
			"dividendsType":       a.DividendsType,
			"dividendsRatio":      0,
			"dividendsAmount":     a.DividendsAmount,
			"dividendsUser": map[string]interface{}{
				"userInfo": a.DividendsUser.UserInfo,
				"userId":   a.DividendsUser.UserId,
			},
			"dividendsParticipateType": a.DividendsParticipateType,
			"dividendsAccountStatus":   a.DividendsAccountStatus,
			"dividendsEstimateTime":    a.CreatedAt.Unix() * 1000,
			"orderOrReturnedOrderNum":  a.DividendsEstimateOrderNumber,
			"creditAccountId":          a.CreditAccountId,
		}
		if a.PaymentStatus == 2 {
			item["dividendsAccountStatus"] = 3
		}
		if v, ok := mapOrderGoods[a.OrderGoodId]; ok {
			item["orderGoodName"] = v.OrderGoodName
			if v.OrderGoodAmount > 0 {
				item["dividendsRatio"] = utils.Round(a.DividendsAmount/v.OrderGoodAmount*100, 2)
			}
		}
		if a.DividendsPercentage > 0 {
			item["dividendsRatio"] = a.DividendsPercentage
		}
		// 金额激励承接人分红比例百分百,业务员 推荐人按设定的比例
		if a.DividendsType == 3 && a.DividendsPercentage == 0 {
			item["dividendsRatio"] = 100
		}
		dividends = append(dividends, item)
	}
	res["dividends"] = dividends
	return res, nil
}

// 分红明细
func (ptr *CooperationStatisticsService) DividendsStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		//企业
		CompanyId int64 `json:"companyId"`
		OrgId     int64 `json:"orgId"`
		UserId    int64 `json:"userId"`
		//个人
		UserBaseId int64 `json:"userBaseId"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	type response struct {
		Total      float64 `json:"total"`
		Accounting float64 `json:"accounting"`
		Accounted  float64 `json:"accounted"`
		Paid       float64 `json:"paid"`
	}
	creditAccountDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)
	var contractNumbers []string
	var err error
	if request.OrgId > 0 && request.UserId > 0 {
		contractNumbers, err = ptr.getRelevantContracts(map[string]interface{}{"orgId": request.OrgId, "userId": request.UserId, "offsetLimit": false})
		if err != nil {
			return struct{}{}, err
		}
	} else if request.UserBaseId > 0 {
		contractNumbers, err = ptr.getUnderTakerContracts(map[string]interface{}{"orgId": request.OrgId, "userBaseId": request.UserBaseId, "offsetLimit": false})
		if err != nil {
			return struct{}{}, err
		}
	}

	queryOptions["cooperationContractNumbers"] = contractNumbers

	var allDividendsEstimate = &CreditAccountStatisticsResponse{}
	var annualDividendsEstimate = &CreditAccountStatisticsResponse{}
	var quarterDividendsEstimate = &CreditAccountStatisticsResponse{}
	var allDividends = &CreditAccountStatisticsResponse{}
	var annualDividends = &CreditAccountStatisticsResponse{}
	var quarterDividends = &CreditAccountStatisticsResponse{}

	dividendsEstimateDao, _ := dao.NewDividendsEstimateDao(ptr.transactionContext)
	if len(contractNumbers) > 0 {
		if err := dividendsEstimateDao.DividendsEstimateStatistics(queryOptions, allDividendsEstimate); err != nil {
			return nil, err
		}
		if err := creditAccountDao.DividendsStatistics(map[string]interface{}{
			"companyId":                  request.CompanyId,
			"orgId":                      request.OrgId,
			"userBaseId":                 request.UserBaseId,
			"cooperationContractNumbers": contractNumbers,
		}, allDividends); err != nil {
			return nil, err
		}
		allDividendsEstimate.Paid = allDividends.Paid

		queryOptions["beginTime"] = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Local)
		queryOptions["endTime"] = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Local).AddDate(1, 0, 0)
		if err := dividendsEstimateDao.DividendsEstimateStatistics(queryOptions, annualDividendsEstimate); err != nil {
			return nil, err
		}
		if err := creditAccountDao.DividendsStatistics(map[string]interface{}{
			"companyId":                  request.CompanyId,
			"orgId":                      request.OrgId,
			"userBaseId":                 request.UserBaseId,
			"paymentBeginTime":           queryOptions["beginTime"],
			"paymentEndTime":             queryOptions["endTime"],
			"cooperationContractNumbers": contractNumbers,
		}, annualDividends); err != nil {
			return nil, err
		}
		annualDividendsEstimate.Paid = annualDividends.Paid

		queryOptions["beginTime"], queryOptions["endTime"] = quarterBeginEnd()
		if err := dividendsEstimateDao.DividendsEstimateStatistics(queryOptions, quarterDividendsEstimate); err != nil {
			return nil, err
		}
		if err := creditAccountDao.DividendsStatistics(map[string]interface{}{
			"companyId":                  request.CompanyId,
			"orgId":                      request.OrgId,
			"userBaseId":                 request.UserBaseId,
			"paymentBeginTime":           queryOptions["beginTime"],
			"paymentEndTime":             queryOptions["endTime"],
			"cooperationContractNumbers": contractNumbers,
		}, quarterDividends); err != nil {
			return nil, err
		}
		quarterDividendsEstimate.Paid = quarterDividends.Paid
	}

	ret := map[string]interface{}{
		"allDividends":     allDividendsEstimate.Round(2),
		"annualDividends":  annualDividendsEstimate.Round(2),
		"quarterDividends": quarterDividendsEstimate.Round(2),
	}
	return ret, nil
}

func quarterBeginEnd() (time.Time, time.Time) {
	y := time.Now().Year()
	m := time.Now().Month()
	var mBegin, mEnd int
	var begin, end time.Time
	switch m {
	case 4, 5, 6:
		mBegin = 4
		mEnd = 6
	case 7, 8, 9:
		mBegin = 7
		mEnd = 9
	case 10, 11, 12:
		mBegin = 10
		mEnd = 12
	case 1, 2, 3:
		mBegin = 1
		mEnd = 3
	}
	begin = time.Date(y, time.Month(mBegin), 1, 0, 0, 0, 0, time.Local)
	end = time.Date(y, time.Month(mEnd), 1, 0, 0, 0, 0, time.Local).AddDate(0, 1, 0)
	return begin, end
}

// 分红预算列表
func (ptr *CooperationStatisticsService) SearchDividendsEstimates(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		CompanyId int64 `json:"companyId"`
		OrgId     int64 `json:"orgId"`
		UserId    int64 `json:"userId"`

		UserBaseId             int64 `json:"userBaseId"`
		DividendsAccountStatus int32 `json:"dividendsAccountStatus"` // 分红结算状态 未结算:1,已结算:2,已支付:3
		Offset                 int64 `json:"offset"`
		Limit                  int64 `json:"limit"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)
	//if request.DividendsAccountStatus == 2 {
	//	queryOptions["paymentStatus"] = int32(1)
	//}
	if request.DividendsAccountStatus == 3 {
		queryOptions["dividendsAccountStatus"] = int32(2)
		queryOptions["paymentStatus"] = int32(2)
	}
	var contractNumbers []string
	var err error
	if request.OrgId > 0 && request.UserId > 0 {
		contractNumbers, err = ptr.getRelevantContracts(map[string]interface{}{"orgId": request.OrgId, "userId": request.UserId, "offsetLimit": false})
		if err != nil {
			return struct{}{}, err
		}
	} else if request.UserBaseId > 0 {
		contractNumbers, err = ptr.getUnderTakerContracts(map[string]interface{}{"orgId": request.OrgId, "userBaseId": request.UserBaseId, "offsetLimit": false})
		if err != nil {
			return struct{}{}, err
		}
	}
	type response struct {
		// 承接人分红预算记录ID
		DividendsEstimateId int64 `json:"dividendsEstimateId,string"`
		// 分红结算状态,1待结算,2已结算
		DividendsAccountStatus int32 `json:"dividendsAccountStatus"`
		// 分红金额
		DividendsAmount float64 `json:"dividendsAmount"`
		// 参与分红类型,1承接人,2推荐人,3关联业务员
		DividendsParticipateType int32 `json:"dividendsParticipateType"`
		// 分红类型,1订单分红,2退货冲销,3金额激励
		DividendsType int32 `json:"dividendsType"`
		// 分红用户(共创参与)
		DividendsUser *domain.User `json:"dividendsUser"`
		// 分红订单金额
		DividendsOrderAmount float64 `json:"dividendsOrderAmount"`
		//OrderGoodName string `json:"orderGoodName"`
		CustomerName string `json:"customerName"`
	}
	var results = make([]response, 0)
	if len(contractNumbers) == 0 {
		return results, nil
	}

	queryOptions["cooperationContractNumbers"] = contractNumbers

	dividendsEstimateRepository, _ := repository.NewDividendsEstimateRepository(ptr.transactionContext)
	queryOptions["isCanceled"] = false
	_, estimates, err := dividendsEstimateRepository.Find(queryOptions)
	if err != nil {
		return nil, err
	}

	dividendsOrderRepository, _ := repository.NewDividendsOrderRepository(ptr.transactionContext)
	dividendsReturnedOrderRepository, _ := repository.NewDividendsReturnedOrderRepository(ptr.transactionContext)
	for i := range estimates {
		item := estimates[i]
		result := response{
			DividendsEstimateId:      item.DividendsEstimateId,
			DividendsAccountStatus:   item.DividendsAccountStatus,
			DividendsAmount:          item.DividendsAmount,
			DividendsParticipateType: item.DividendsParticipateType,
			DividendsType:            item.DividendsType,
			DividendsUser:            item.DividendsUser,
		}
		// 1.全部列表、已支付列表的分红状态显示为已分红
		// 2.已结算列表的分红状态还是显示已结算
		if item.PaymentStatus == 2 && (request.DividendsAccountStatus == 3 || request.DividendsAccountStatus == 0) {
			result.DividendsAccountStatus = 3
		}
		// TODO:优化查询 统一查询到map里面、或者冗余数据
		if item.DividendsType == 1 {
			order, err := dividendsOrderRepository.FindOne(map[string]interface{}{
				"dividendsOrderNumber": item.OrderOrReturnedOrderNum,
				"orgId":                request.OrgId,
			})
			if err != nil {
				return nil, err
			}
			result.DividendsOrderAmount = order.DividendsOrderAmount
			result.CustomerName = order.CustomerName
		} else if item.DividendsType == 2 {
			order, err := dividendsReturnedOrderRepository.FindOne(map[string]interface{}{
				"dividendsReturnedOrderNumber": item.OrderOrReturnedOrderNum,
				"orgId":                        request.OrgId,
			})
			if err != nil {
				return nil, err
			}
			result.DividendsOrderAmount = order.DividendsReturnedOrderRefund
			result.CustomerName = order.DividendsReturnedCustomerName
		}
		results = append(results, result)
	}
	return results, nil
}

// 账期结算单统计
func (ptr *CooperationStatisticsService) CreditAccountStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		OrgId      int64     `json:"orgId"`
		UserBaseId int64     `json:"userBaseId"`
		BeginTime  time.Time `json:"beginTime"`
		EndTime    time.Time `json:"endTime"`
		// 支付开始时间
		PaymentBeginTime time.Time `json:"paymentBeginTime"`
		// 支付结束时间
		PaymentEndTime time.Time `json:"paymentEndTime"`
		// 合约编号列表
		CooperationContractNumbers []string `json:"cooperationContractNumbers"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	creditAccountDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)

	var allDividends = &CreditAccountStatisticsResponse{}
	if err := creditAccountDao.DividendsStatistics(queryOptions, allDividends); err != nil {
		return nil, err
	}
	allDividends.Accounting = allDividends.Total - allDividends.Accounted
	return allDividends, nil
}

type CreditAccountStatisticsResponse struct {
	Total      float64 `json:"total"`
	Accounting float64 `json:"accounting"`
	Accounted  float64 `json:"accounted"`
	Paid       float64 `json:"paid"`
	Unpaid     float64 `json:"unpaid"`
}

func (credit *CreditAccountStatisticsResponse) Round(places int) *CreditAccountStatisticsResponse {
	credit.Total = utils.Round(credit.Total, int32(places))
	credit.Accounting = utils.Round(credit.Accounting, int32(places))
	credit.Accounted = utils.Round(credit.Accounted, int32(places))
	credit.Paid = utils.Round(credit.Paid, int32(places))
	credit.Unpaid = utils.Round(credit.Unpaid, int32(places))
	return credit
}

//getRelevantContracts  获取相关人的合约
func (ptr *CooperationStatisticsService) RelevantCooperationContractNumbers(queryOptions map[string]interface{}) (interface{}, error) {
	var request = struct {
		//企业
		CompanyId int64 `json:"companyId" valid:"Required"`
		OrgId     int64 `json:"orgId" valid:"Required"`
		UserId    int64 `json:"userId" valid:"Required"`
		//个人
		//UserBaseId int64 `json:"userBaseId"`
		//Offset     int   `json:"offset"`
		//Limit      int   `json:"limit"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)
	queryOptions["limit"] = 999
	contractNumbers, err := ptr.getRelevantContracts(queryOptions)
	return contractNumbers, err
}