pg_cooperation_company_statistics_service.go 28.4 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
package domain_service

import (
	"fmt"
	"github.com/beego/beego/v2/core/validation"
	"github.com/linmadan/egglib-go/utils/json"
	"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"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/log"
	"math"
	"time"
)

// totalOrganizationUser 统计组织用户

// rankType 排行榜类型,1月榜,2年榜 3总榜,默认展示年榜
// top      排名前n个
func (ptr *CooperationStatisticsService) CooperationGoodsStatistics(queryOptions map[string]interface{}) ([]*domain.CooperationGoodsStatisticsDto, error) {
	orderGoodDao, _ := dao.NewOrderGoodDao(ptr.transactionContext)
	// 参数验证
	var request = struct {
		CompanyId int64 `json:"companyId" valid:"Required"`
		OrgId     int64 `json:"orgId" valid:"Required"`
		RankType  int   `json:"rankType" valid:"Required"`
		Top       int   `json:"top" valid:"Required"`
		Offset    int   `json:"offset"`
		Limit     int   `json:"limit"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	y := time.Now().Year()
	m := time.Now().Month()
	var beginTime, endTime time.Time
	if request.RankType == 1 { //1月榜
		beginTime = time.Date(y, m, 1, 0, 0, 0, 0, time.Local)
		endTime = beginTime.AddDate(0, 1, 0)
		queryOptions["beginTime"] = beginTime.Format(time.RFC3339)
		queryOptions["endTime"] = endTime.Format(time.RFC3339)
	} else if request.RankType == 2 { //2年榜
		beginTime = time.Date(y, 1, 1, 0, 0, 0, 0, time.Local)
		endTime = beginTime.AddDate(1, 0, 0)
		queryOptions["beginTime"] = beginTime.Format(time.RFC3339)
		queryOptions["endTime"] = endTime.Format(time.RFC3339)
	}
	if request.Top > 0 {
		queryOptions["limit"] = request.Top
	}
	if request.Limit > 0 {
		queryOptions["limit"] = request.Limit
	}
	if request.Offset > 0 {
		queryOptions["offset"] = request.Offset
	}
	goods, err := orderGoodDao.CooperationGoodsStatistics(queryOptions)
	if err != nil {
		return nil, err
	}
	if len(goods) == 0 {
		goods = make([]*domain.CooperationGoodsStatisticsDto, 0)
	}

	// 2.计算百分比
	var totalAmount float64
	for i := range goods {
		goods[i].Rank = int32(i+1) + int32(request.Offset)
		totalAmount += goods[i].GoodAmount
	}
	for i := range goods {
		if totalAmount == 0 {
			goods[i].GoodRatio = 0
			continue
		}
		goods[i].GoodRatio = utils.Round((goods[i].GoodAmount/totalAmount)*100, 0)
	}
	return goods, nil
}

// CooperationModeStatistics  企业-共创模式统计
//
// p1 p1_desc
func (ptr *CooperationStatisticsService) CooperationModeStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	orderGoodDao, _ := dao.NewOrderGoodDao(ptr.transactionContext)
	// 参数验证
	var request = struct {
		CompanyId int64 `json:"companyId" valid:"Required"`
		OrgId     int64 `json:"orgId" valid:"Required"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	modeStatistics, err := orderGoodDao.CooperationCompanyModeStatistics(queryOptions)
	if err != nil {
		return nil, err
	}
	if len(modeStatistics) == 0 {
		modeStatistics = make([]*domain.CooperationModeStatisticsDto, 0)
	}

	modeStatistics = make([]*domain.CooperationModeStatisticsDto, 0)
	// 1.当前企业有效的模式(不包含禁用、删除)
	cooperationModeRepository, _ := repository.NewCooperationModeRepository(ptr.transactionContext)
	_, models, err := cooperationModeRepository.Find(map[string]interface{}{"companyId": request.CompanyId, "orgId": request.OrgId, "status": int32(1)})
	if err != nil {
		return nil, err
	}
	if len(models) == 0 {
		return nil, nil
	}

	// 2.遍历模式  当前模式包含的合约列表
	// 2.1 根据合约查询订单金额,已分红预算的订单
	// 2.2 根据合约查询分红预算的金额
	// 2.3 根据合约去重参与的共创人数
	cooperationContractRepository, _ := dao.NewCooperationContractDao(ptr.transactionContext)
	var totalContracts []*domain.CooperationContract
	var cooperationModes = make([]map[string]interface{}, 0)
	for i := range models {
		_, contracts, err := cooperationContractRepository.Find(map[string]interface{}{"companyId": request.CompanyId, "orgId": request.OrgId, "cooperationModeNumber": models[i].CooperationModeNumber})
		if err != nil {
			return nil, err
		}
		result, err := ptr.cooperationModeStatistics(models[i], contracts, request.CompanyId, request.OrgId)
		if err != nil {
			return nil, err
		}
		modeStatistics = append(modeStatistics, result)
		totalContracts = append(totalContracts, contracts...)
		cooperationModes = append(cooperationModes, map[string]interface{}{
			"cooperationModeId":     models[i].CooperationModeId,
			"cooperationModeName":   models[i].CooperationModeName,
			"cooperationModeNumber": models[i].CooperationModeNumber,
		})
	}
	totalModeStatistics, err := ptr.cooperationModeStatistics(&domain.CooperationMode{}, totalContracts, request.CompanyId, request.OrgId)
	if err != nil {
		return nil, err
	}
	return map[string]interface{}{
		"cooperationModeStatistics":      modeStatistics,
		"totalCooperationModeStatistics": totalModeStatistics,
		"cooperationModes":               cooperationModes,
	}, nil
}

func (ptr *CooperationStatisticsService) cooperationModeStatistics(mode *domain.CooperationMode, contracts []*domain.CooperationContract, companyId, orgId int64) (*domain.CooperationModeStatisticsDto, error) {
	initStatistic := &domain.CooperationModeStatisticsDto{
		CooperationPeople:     0,
		DividendsEstimate:     0,
		OrderAmount:           0,
		CooperationModeNumber: mode.CooperationModeNumber,
		SettlementAmount:      0,
	}
	var err error
	var undertakers []*domain.CooperationContractUndertaker
	var mapUndertakers = make(map[int64]int64)
	if len(contracts) == 0 {
		return initStatistic, nil
	}
	var contractNumbers = make([]string, 0)
	for i := range contracts {
		contractNumbers = append(contractNumbers, contracts[i].CooperationContractNumber)
	}
	dividendsOrderDao, _ := dao.NewDividendsOrderDao(ptr.transactionContext)
	initStatistic.OrderAmount, err = dividendsOrderDao.CalculateGoodOrderAmount(map[string]interface{}{"companyId": companyId, "orgId": orgId, "cooperationContractNumbers": contractNumbers})
	if err != nil {
		return initStatistic, err
	}
	dividendsEstimateDao, _ := dao.NewDividendsEstimateDao(ptr.transactionContext)
	initStatistic.DividendsEstimate, err = dividendsEstimateDao.CountDividendsEstimateDividendsAmount(map[string]interface{}{"companyId": companyId, "orgId": orgId, "cooperationContractNumbers": contractNumbers})
	if err != nil {
		return initStatistic, err
	}
	undertakerRepository, _ := repository.NewCooperationContractUndertakerRepository(ptr.transactionContext)
	if _, undertakers, err = undertakerRepository.Find(map[string]interface{}{"companyId": companyId, "orgId": orgId, "cooperationContractNumbers": contractNumbers}); err != nil {
		return initStatistic, err
	}
	for i := range undertakers {
		undertaker := undertakers[i]
		if undertaker.Undertaker != nil && undertaker.Undertaker.UserId != 0 {
			u1 := undertaker.Undertaker
			mapUndertakers[u1.UserId] = u1.UserId
			if u1.Referrer != nil && u1.Referrer.UserId != 0 {
				mapUndertakers[u1.Referrer.UserId] = u1.Referrer.UserId
			}
			if u1.Salesman != nil && u1.Salesman.UserId != 0 {
				mapUndertakers[u1.Salesman.UserId] = u1.Salesman.UserId
			}
		}
	}
	initStatistic.OrderAmount = utils.Round(initStatistic.OrderAmount, 1)
	initStatistic.DividendsEstimate = utils.Round(initStatistic.DividendsEstimate, 1)
	initStatistic.CooperationPeople = len(mapUndertakers)
	return initStatistic, nil
}

// DividendsStatistics  分红统计
//
// action 1:当前月
func (ptr *CooperationStatisticsService) CompanyDividendsStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		CompanyId int64 `json:"companyId" valid:"Required"`
		OrgId     int64 `json:"orgId" valid:"Required"`
		Action    int   `json:"action" valid:"Required"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	var beginTime, endTime time.Time
	var res = make(map[string]interface{})
	if request.Action == 1 {
		y := time.Now().Year()
		m := time.Now().Month()
		beginTime = time.Date(y, m, 1, 0, 0, 0, 0, time.Local)
		endTime = beginTime.AddDate(0, 1, 0)
		queryOptions["beginTime"] = beginTime
		queryOptions["endTime"] = endTime
	}

	dividendsEstimateDao, _ := dao.NewDividendsEstimateDao(ptr.transactionContext)
	dividendsEstimate, err := dividendsEstimateDao.CountDividendsEstimateDividendsAmount(queryOptions)
	if err != nil {
		return nil, err
	}
	queryOptions["paymentStatus"] = 2
	var dividends = &CreditAccountStatisticsResponse{}
	orderGoodDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)
	if err := orderGoodDao.DividendsStatistics(map[string]interface{}{
		"paymentBeginTime": beginTime,
		"paymentEndTime":   endTime,
		"paymentStatus":    2,
		"orgId":            request.OrgId,
		"companyId":        request.CompanyId,
	}, dividends); err != nil {
		return nil, err
	}
	orderAmount := ptr.CalculateOrderAmount(queryOptions)

	res["creditAccount"] = dividends.Paid                        // 本月账期结算统计
	res["orderAmount"] = orderAmount                             // 订单金额统计
	res["dividendsEstimate"] = utils.Round(dividendsEstimate, 1) // 分红预算统计
	return res, nil
}

// CalculateOrderAmount 计算订单总金额
// 订单总金额 = 订单总金额 - 退货总金额
func (ptr *CooperationStatisticsService) CalculateOrderAmount(queryOption map[string]interface{}) float64 {
	orderDao, err := dao.NewDividendsOrderDao(ptr.transactionContext)
	if err != nil {
		log.Logger.Error(err.Error())
	}
	amount, err := orderDao.CalculateDividendsOrderAmount(queryOption)
	if err != nil {
		log.Logger.Error(err.Error())
	}
	returnedOrderDao, _ := dao.NewDividendsReturnedOrderDao(ptr.transactionContext)
	returnedAmount, _ := returnedOrderDao.CalculateDividendsReturnedOrderAmount(queryOption)
	//if math.Abs(returnedAmount) > math.Abs(amount) {
	//	return 0
	//}
	return utils.Round(math.Abs(amount)-math.Abs(returnedAmount), 1)
}

func LoadQueryOptions(queryOption map[string]interface{}, keys ...string) (map[string]interface{}, error) {
	var res = make(map[string]interface{})
	for i := 0; i < len(keys); i++ {
		k := keys[i]
		if v, ok := queryOption[k]; ok {
			res[k] = v
		} else {
			return nil, fmt.Errorf("参数 %v 不存在", k)
		}
	}
	return res, nil
}

func LoadQueryObject(queryOption map[string]interface{}, obj interface{}) error {
	json.UnmarshalFromString(json.MarshalToString(queryOption), obj)
	validation := validation.Validation{}
	_, err := validation.Valid(obj)
	return err
}

type item struct {
	key string
	val interface{}
}

// 公司 - 共创用户统计
func (ptr *CooperationStatisticsService) CompanyCooperationUsersStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		Limit                    int   `json:"limit" valid:"Required"`
		Offset                   int   `json:"offset"`
		OrgId                    int64 `json:"orgId" valid:"Required"`
		SortByActuallyPaidAmount int   `json:"sortByActuallyPaidAmount" valid:"Required"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	var responses []usersStatisticsResponse
	creditAccountDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)
	if err := creditAccountDao.CooperationUsersDividendsStatistics(queryOptions, &responses); err != nil {
		return nil, err
	}

	userService, _ := NewUserService()

	contractUndertakerDao, _ := dao.NewCooperationContractUndertakerDao(ptr.transactionContext)
	dividendsOrderDao, _ := dao.NewDividendsOrderDao(ptr.transactionContext)
	var retMap = make([]interface{}, 0)
	for i := range responses {
		responses[i].CooperationTime = time.Now().Unix() * 1000

		item := map[string]interface{}{
			"dividendsOrderAmount": 0,
			"actuallyPaidAmount":   responses[i].ActuallyPaidAmount,
			"unPaidAmount":         responses[i].UnPaidAmount,
			"cooperationTime":      time.Now().Unix() * 1000,
			"participator": map[string]interface{}{
				"userId": responses[i].UserId,
				"userInfo": map[string]interface{}{
					"userName": responses[i].UserName,
				},
			},
		}
		if user, e := userService.UserFrom(0, 0, responses[i].UserId); e == nil && user != nil {
			item["cooperationTime"] = user.CreatedAt.Unix() * 1000
			item["participator"] = map[string]interface{}{
				"userId": user.UserId,
				"userInfo": map[string]interface{}{
					"userName": user.UserName,
				},
			}
		}
		// 订单金额
		_, contracts, _ := contractUndertakerDao.Find(map[string]interface{}{"orgId": request.OrgId, "userId": responses[i].UserId})
		var contractsNumbers []string
		for i := range contracts {
			contractsNumbers = append(contractsNumbers, contracts[i].CooperationContractNumber)
		}
		if len(contractsNumbers) > 0 {
			item["dividendsOrderAmount"], _ = dividendsOrderDao.CalculateGoodOrderAmount(map[string]interface{}{"orgId": request.OrgId, "cooperationContractNumbers": contractsNumbers})
		}

		retMap = append(retMap, item)
	}

	return retMap, nil
}

type usersStatisticsResponse struct {
	CooperationTime      int64   `json:"cooperationTime"`
	DividendsOrderAmount float64 `json:"dividendsOrderAmount"`
	DividesAmount        float64 `json:"dividesAmount"`      // 分红金额
	ActuallyPaidAmount   float64 `json:"actuallyPaidAmount"` // 已支付金额
	UnPaidAmount         float64 `json:"unPaidAmount"`       // 未支付金额
	UserId               int64   `json:"userId,string"`
	UserName             string  `json:"userName"`

	Participator interface{} `json:"participator"`
}

// 公司 - 共创用户模式统计
func (ptr *CooperationStatisticsService) CooperationUserModeStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		UserId int64 `json:"userId" valid:"Required"`
		OrgId  int64 `json:"orgId" valid:"Required"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	contractUndertakerDao, _ := dao.NewCooperationContractUndertakerDao(ptr.transactionContext)
	contractDao, _ := dao.NewCooperationContractDao(ptr.transactionContext)
	cooperationModeRepository, _ := repository.NewCooperationModeRepository(ptr.transactionContext)

	// 1.查询承接的合约
	_, contractUndertakers, _ := contractUndertakerDao.Find(map[string]interface{}{"orgId": request.OrgId, "userId": request.UserId})
	var contractsNumbers []string
	for i := range contractUndertakers {
		contractsNumbers = append(contractsNumbers, contractUndertakers[i].CooperationContractNumber)
	}
	if len(contractsNumbers) == 0 {
		return struct{}{}, nil
	}
	_, contracts, _ := contractDao.Find(map[string]interface{}{"orgId": request.OrgId, "cooperationContractNumbers": contractsNumbers})
	if len(contracts) == 0 {
		return struct{}{}, nil
	}

	var modeNumbers []string
	for i := range contracts {
		modeNumbers = append(modeNumbers, contracts[i].CooperationMode.CooperationModeNumber)
	}
	// 2.查询模式
	_, modes, _ := cooperationModeRepository.Find(map[string]interface{}{"orgId": request.OrgId, "cooperationModeNumbers": modeNumbers})
	if len(modes) == 0 {
		return struct{}{}, nil
	}
	var mapMode = make(map[string]*domain.CooperationMode)
	var mapModeContracts = make(map[string][]string)
	var cooperationTypes []interface{}
	for i := range modes {
		mapMode[modes[i].CooperationModeNumber] = modes[i]
		mapModeContracts[modes[i].CooperationModeNumber] = make([]string, 0)
		cooperationTypes = append(cooperationTypes, map[string]interface{}{
			"cooperationModeId":     modes[i].CooperationModeId,
			"cooperationModeName":   modes[i].CooperationModeName,
			"cooperationModeNumber": modes[i].CooperationModeNumber,
		})
	}
	for i := range contracts {
		key := contracts[i].CooperationMode.CooperationModeNumber
		if _, ok := mapMode[key]; ok {
			mapModeContracts[key] = append(mapModeContracts[key], contracts[i].CooperationContractNumber)
		}
	}

	// 3.分红支出
	dividendsDetails, err := ptr.userModeDividend(request.UserId, request.OrgId, mapMode, mapModeContracts)
	if err != nil {
		return nil, err
	}
	// 4.成交订单
	orderDetails, err := ptr.userModeOrder(request.OrgId, mapMode, mapModeContracts)
	if err != nil {
		return nil, err
	}
	return map[string]interface{}{
		"cooperationTypes": cooperationTypes,
		"dividendsDetails": dividendsDetails,
		"orderDetails":     orderDetails,
	}, nil
}

// 用户模式分红
func (ptr *CooperationStatisticsService) userModeDividend(userId, orgId int64, mapMode map[string]*domain.CooperationMode, mapModeContracts map[string][]string) (interface{}, error) {
	creditAccountDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)
	var dividends dividendsExpenseByTypes = make([]dividendsExpenseByType, 0)
	var total float64 = 0
	for _, v := range mapMode {
		numbers := mapModeContracts[v.CooperationModeNumber]
		var dividendsEstimate = &CreditAccountStatisticsResponse{}
		err := creditAccountDao.DividendsStatistics(map[string]interface{}{"userId": userId, "orgId": orgId, "cooperationContractNumbers": numbers}, dividendsEstimate)
		if err != nil {
			return nil, err
		}
		dividends = append(dividends, dividendsExpenseByType{
			DividendsTypeName: v.CooperationModeName + "分红支出",
			DividendsExpense:  dividendsEstimate.Paid, //实际已支付金额
		})
		total += dividendsEstimate.Paid
	}
	return map[string]interface{}{
		"dividendsExpense":        total,
		"dividendsExpenseByTypes": dividends,
	}, nil
}

// 用户模式订单
func (ptr *CooperationStatisticsService) userModeOrder(orgId int64, mapMode map[string]*domain.CooperationMode, mapModeContracts map[string][]string) (interface{}, error) {
	creditAccountDao, _ := dao.NewDividendsOrderDao(ptr.transactionContext)
	var dividends orderAmountByTypes = make([]orderAmountByType, 0)
	var total float64 = 0
	for _, v := range mapMode {
		numbers := mapModeContracts[v.CooperationModeNumber]
		amount, err := creditAccountDao.CalculateGoodOrderAmount(map[string]interface{}{"orgId": orgId, "cooperationContractNumbers": numbers})
		if err != nil {
			return nil, err
		}
		dividends = append(dividends, orderAmountByType{
			OrderAmount:   amount,
			OrderTypeName: v.CooperationModeName + "成交订单",
		})
		total += amount
	}
	return map[string]interface{}{
		"orderAmount":        total,
		"orderAmountByTypes": dividends,
	}, nil
}

// 公司 - 共创用户模式统计
func (ptr *CooperationStatisticsService) CooperationUserModeStatisticsBak(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	//var request = struct {
	//	UserId int64 `json:"userId" valid:"Required"`
	//	OrgId  int64 `json:"orgId" valid:"Required"`
	//}{}
	//if err := LoadQueryObject(queryOptions, &request); err != nil {
	//	return nil, err
	//}
	//queryOptions = tool_funs.SimpleStructToMap(&request)
	//
	//orderGoodDao, _ := dao.NewOrderGoodDao(ptr.transactionContext)
	//modeStatistics, err := orderGoodDao.CooperationUserModeStatistics(queryOptions)
	//if err != nil {
	//	return nil, err
	//}
	//if len(modeStatistics) == 0 {
	//	return struct{}{}, nil
	//}
	//
	//var modeNumbers []string
	//var mapModeStatistics = make(map[string]*domain.CooperationModeStatisticsDto)
	//for i := range modeStatistics {
	//	mapModeStatistics[modeStatistics[i].CooperationModeNumber] = modeStatistics[i]
	//	modeNumbers = append(modeNumbers, modeStatistics[i].CooperationModeNumber)
	//}
	//
	//cooperationModeRepository, _ := repository.NewCooperationModeRepository(ptr.transactionContext)
	//_, cooperModes, err := cooperationModeRepository.Find(map[string]interface{}{"cooperationModeNumbers": modeNumbers, "orgId": request.OrgId})
	//if err != nil {
	//	return nil, err
	//}
	//var cooperationTypes, dividendsExpenseByTypes, orderAmountByTypes []interface{}
	//var totalOrderAmount float64
	//var totalDividendAmount float64
	//for i := range cooperModes {
	//	m := cooperModes[i]
	//	if modeStatistics, ok := mapModeStatistics[m.CooperationModeNumber]; ok {
	//		totalOrderAmount += modeStatistics.OrderAmount
	//		totalDividendAmount += modeStatistics.DividendsEstimate
	//		dividendsExpenseByTypes = append(dividendsExpenseByTypes, map[string]interface{}{
	//			"dividendsTypeName": m.CooperationModeName + "分红支出",
	//			"dividendsExpense":  modeStatistics.DividendsEstimate, //实际已支付金额
	//		})
	//		orderAmountByTypes = append(orderAmountByTypes, map[string]interface{}{
	//			"orderAmount":   modeStatistics.OrderAmount,
	//			"orderTypeName": m.CooperationModeName + "成交订单",
	//		})
	//	}
	//	cooperationTypes = append(cooperationTypes, map[string]interface{}{
	//		"cooperationModeId":     m.CooperationModeId,
	//		"cooperationModeName":   m.CooperationModeName,
	//		"cooperationModeNumber": m.CooperationModeNumber,
	//	})
	//}
	//return map[string]interface{}{
	//	"cooperationTypes": cooperationTypes,
	//	"dividendsDetails": map[string]interface{}{
	//		"dividendsExpense":        totalDividendAmount,
	//		"dividendsExpenseByTypes": dividendsExpenseByTypes,
	//	},
	//	"orderDetails": map[string]interface{}{
	//		"orderAmount":        totalOrderAmount,
	//		"orderAmountByTypes": orderAmountByTypes,
	//	},
	//}, nil
	return nil, nil
}

type dividendsExpenseByType struct {
	DividendsTypeName string  `json:"dividendsTypeName"`
	DividendsExpense  float64 `json:"dividendsExpense"`
}
type orderAmountByType struct {
	OrderTypeName string  `json:"orderTypeName"`
	OrderAmount   float64 `json:"orderAmount"`
}
type dividendsExpenseByTypes []dividendsExpenseByType

func (s dividendsExpenseByTypes) Len() int { return len(s) }
func (s dividendsExpenseByTypes) Less(i, j int) bool {
	return s[i].DividendsExpense < s[j].DividendsExpense
}
func (s dividendsExpenseByTypes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

type orderAmountByTypes []orderAmountByType

func (s orderAmountByTypes) Len() int           { return len(s) }
func (s orderAmountByTypes) Less(i, j int) bool { return s[i].OrderAmount < s[j].OrderAmount }
func (s orderAmountByTypes) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

// 公司 - 共创用户分红支付统计
func (ptr *CooperationStatisticsService) CompanyPaymentHistoryStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	// 参数验证
	var request = struct {
		Limit                    int       `json:"limit" valid:"Required"`
		Offset                   int       `json:"offset"`
		OrgId                    int64     `json:"orgId" valid:"Required"`
		UserId                   int64     `json:"userId" valid:"Required"`
		SortByActuallyPaidAmount int       `json:"sortByActuallyPaidAmount" valid:"Required"`
		PaymentBeginTime         time.Time `json:"paymentBeginTime"`
		PaymentEndTime           time.Time `json:"paymentEndTime"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	// 按关联相关人过滤
	var retMap = make([]interface{}, 0)
	contractNumbers, err := ptr.getRelevantContracts(map[string]interface{}{"userId": request.UserId})
	if len(contractNumbers) == 0 {
		return retMap, nil
	}
	if err != nil {
		return retMap, err
	}
	queryOptions["cooperationContractNumbers"] = contractNumbers

	var responses []usersStatisticsResponse
	creditAccountDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)
	if err := creditAccountDao.CooperationUsersDividendsStatistics(queryOptions, &responses); err != nil {
		return nil, err
	}

	for i := range responses {
		retMap = append(retMap, map[string]interface{}{
			"paymentAmount": responses[i].ActuallyPaidAmount,
			"user": map[string]interface{}{
				"userId": responses[i].UserId,
				"userInfo": map[string]interface{}{
					"userName": responses[i].UserName,
				},
			},
		})
	}

	return retMap, nil
}

// 公司/个人 - 支付历史统计直方图
func (ptr *CooperationStatisticsService) PaymentHistoryHistogramStatistics(queryOptions map[string]interface{}) (interface{}, error) {
	creditAccountDao, _ := dao.NewCreditAccountDao(ptr.transactionContext)

	var request = struct {
		OrgId            int64     `json:"orgId"`
		UserId           int64     `json:"userId"`
		UserBaseId       int64     `json:"userBaseId"`
		PaymentBeginTime time.Time `json:"beginTime"`
		PaymentEndTime   time.Time `json:"endTime"`
	}{}
	if err := LoadQueryObject(queryOptions, &request); err != nil {
		return nil, err
	}
	queryOptions = tool_funs.SimpleStructToMap(&request)

	// 按关联相关人过滤
	var contractNumbers []string
	var err error
	var retMap = map[string]interface{}{
		"xAxis": map[string]interface{}{
			"data": []string{},
		},
		"source": map[string]interface{}{
			"value": []float64{},
		},
	}
	if request.UserBaseId > 0 {

		contractNumbers, err = ptr.getUnderTakerContracts(map[string]interface{}{"userId": request.UserId})
		if len(contractNumbers) == 0 {
			return retMap, nil
		}
		if err != nil {
			return retMap, err
		}
		queryOptions["cooperationContractNumbers"] = contractNumbers
	} else if request.UserId > 0 && request.OrgId > 0 {
		contractNumbers, err = ptr.getRelevantContracts(map[string]interface{}{"userId": request.UserId})
		if len(contractNumbers) == 0 {
			return retMap, nil
		}
		if err != nil {
			return retMap, err
		}
		queryOptions["cooperationContractNumbers"] = contractNumbers
	}

	var dividends = &CreditAccountStatisticsResponse{}
	var xAxisData []string
	var values []float64
	var queryItems []queryItem
	if !request.PaymentBeginTime.IsZero() && request.PaymentBeginTime.AddDate(0, 3, 0).Before(request.PaymentEndTime) {
		queryItems, xAxisData = histogramStatisticsByYear(request.PaymentBeginTime)
	} else {
		queryItems, xAxisData = histogramStatisticsByMonth(request.PaymentBeginTime)
	}
	for i := range queryItems {
		item := queryItems[i]
		if len(contractNumbers) == 0 && request.UserId > 0 { //没有相关的合约 查看分红预算单为空
			continue
		}
		queryOptions["paymentBeginTime"] = item.BeginTime
		queryOptions["paymentEndTime"] = item.EndTime
		if err := creditAccountDao.DividendsStatistics(map[string]interface{}{
			"orgId":                      request.OrgId,
			"userBaseId":                 request.UserBaseId,
			"cooperationContractNumbers": contractNumbers,
			"paymentBeginTime":           item.BeginTime,
			"paymentEndTime":             item.EndTime,
		}, dividends); err != nil {
			return nil, err
		}
		values = append(values, dividends.Paid)
	}
	return map[string]interface{}{
		"xAxis": map[string]interface{}{
			"data": xAxisData,
		},
		"source": map[string]interface{}{
			"value": values,
		},
	}, nil
}

type queryItem struct {
	BeginTime time.Time
	EndTime   time.Time
}

func histogramStatisticsByMonth(start time.Time) ([]queryItem, []string) {
	ret := make([]queryItem, 0)
	year, month := start.Year(), start.Month()
	var beginTime = time.Date(year, month, 1, 0, 0, 0, 0, time.Local)
	var endTime time.Time
	var increaseDay = 5
	var monthEnd = time.Date(year, month+1, 1, 0, 0, 0, 0, time.Local).Add(-time.Second)
	var xAxisData []string
	for {
		currentIncreaseDay := increaseDay
		leftDay := monthEnd.Day() - endTime.Day()
		if leftDay == 0 {
			break
		}
		// 不足5天的情况,比如二月 28、29天
		if leftDay > 0 && leftDay < increaseDay {
			currentIncreaseDay = leftDay
		}
		if beginTime.AddDate(0, 0, currentIncreaseDay).After(monthEnd) {
			endTime = monthEnd
			break
		} else {
			endTime = beginTime.AddDate(0, 0, currentIncreaseDay).Add(-time.Second)
		}
		item := queryItem{
			BeginTime: beginTime,
			EndTime:   beginTime.AddDate(0, 0, currentIncreaseDay).Add(-time.Second),
		}
		// 30号接近月末时,如果有31号 就取月末值
		left := monthEnd.Day() - item.EndTime.Day()
		if left <= 1 {
			item.EndTime = monthEnd
			endTime = monthEnd
		}
		xAxisData = append(xAxisData, item.EndTime.Format("01-02"))
		beginTime = endTime
		ret = append(ret, item)
	}
	return ret, xAxisData
}

func histogramStatisticsByYear(beginTime time.Time) ([]queryItem, []string) {
	ret := make([]queryItem, 0)
	var xAxisData = []string{"3月", "6月", "9月", "12月"}
	year := beginTime.Year()
	var increase = 3
	for i := 0; i < 4; i++ {
		ret = append(ret, queryItem{
			BeginTime: time.Date(year, time.Month(1+i*increase), 1, 0, 0, 0, 0, time.Local),
			EndTime:   time.Date(year, time.Month(1+(i+1)*increase), 1, 0, 0, 0, 0, time.Local),
		})
	}
	return ret, xAxisData
}