service.go 32.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 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
package service

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"github.com/linmadan/egglib-go/core/application"
	"github.com/linmadan/egglib-go/utils/tool_funs"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
	roleService "gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/role"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/task/adapter"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/task/command"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/dao"
)

type TaskService struct{}

func NewTaskService() *TaskService {
	newService := &TaskService{}
	return newService
}

func dayEndTime(t time.Time) time.Time {
	y, m, d := t.Local().Date()
	t2 := time.Date(y, m, d, 23, 59, 59, 0, time.Local)
	return t2
}

func dayZeroTime(t time.Time) time.Time {
	y, m, d := t.Local().Date()
	t2 := time.Date(y, m, d, 0, 0, 0, 0, time.Local)
	return t2
}

func (srv TaskService) CreateTaskTest(param *command.CreateTaskCommand) error {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	err = srv.CreateTask(transactionContext, param)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "创建任务失败:"+err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	return nil
}

func (srv TaskService) CreateTask(transactionContext application.TransactionContext, param *command.CreateTaskCommand) error {
	taskRepo := factory.CreateTaskRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskStageRepo := factory.CreateTaskStageRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	cnt, _, err := taskRepo.Find(map[string]interface{}{
		"name":     param.Name,
		"leaderId": strconv.Itoa(param.LeaderId),
	})
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "查询任务失败:"+err.Error())
	}
	if cnt > 0 {
		//TODO
		//任务已存在
		return nil
	}
	userRepo := factory.CreateUserRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})

	_, leaderList, err := userRepo.Find(map[string]interface{}{
		"id": param.LeaderId,
	})
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "查询人员失败:"+err.Error())
	}
	if len(leaderList) == 0 {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "没有查询到人员")
	}
	leaderData := leaderList[0]
	nowTime := time.Now()
	newTask := domain.Task{
		Id:        0,
		CreatedAt: time.Time{},
		UpdatedAt: time.Time{},
		DeletedAt: nil,
		CompanyId: int(leaderData.CompanyId),
		Name:      param.Name,
		Alias:     param.Name,
		Leader: domain.TaskLeader{
			Id:      leaderData.Id,
			Account: leaderData.Account,
			Name:    leaderData.Name,
		},
		Status:      domain.TaskWait,
		Level:       0,
		LevelName:   "",
		RelatedUser: []int{},
		RunAt:       nowTime.Unix(),
		StopAt:      0,
	}
	newTask.ApplyLevelName("战略任务")
	err = taskRepo.Save(&newTask)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "创建任务失败:"+err.Error())
	}

	nowEndTime := dayZeroTime(nowTime)

	newTaskStage := []*domain.TaskStage{
		{
			Id:              0,
			TaskId:          newTask.Id,
			Name:            "里程碑1",
			SortBy:          1,
			PlanCompletedAt: nowEndTime.Add(30 * 24 * time.Hour).Unix(),
			RealCompletedAt: 0,
		},
		{
			Id:              0,
			TaskId:          newTask.Id,
			Name:            "里程碑2",
			SortBy:          2,
			PlanCompletedAt: nowEndTime.Add(60 * 24 * time.Hour).Unix(),
			RealCompletedAt: 0,
		},
		{
			Id:              0,
			TaskId:          newTask.Id,
			Name:            "里程碑3",
			SortBy:          3,
			PlanCompletedAt: nowEndTime.Add(90 * 24 * time.Hour).Unix(),
			RealCompletedAt: 0,
		},
	}
	err = taskStageRepo.Save(newTaskStage)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "创建任务失败:"+err.Error())
	}
	return nil
}

// 更新任务
// TODO 检查是否可以修改,和通知
func (srv TaskService) UpdateTask(param *command.UpdateTaskCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	if len(param.StageList) < 3 {
		return map[string]interface{}{
			"id": param.Id,
		}, application.ThrowError(application.INTERNAL_SERVER_ERROR, "里程碑数量至少3个")
	}
	if len(param.StageList) > 5 {
		return map[string]interface{}{
			"id": param.Id,
		}, application.ThrowError(application.INTERNAL_SERVER_ERROR, "里程碑数量太多")
	}
	taskRepo := factory.CreateTaskRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	userRepo := factory.CreateUserRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskStageRepo := factory.CreateTaskStageRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskData, err := taskRepo.FindOne(map[string]interface{}{
		"id": param.Id,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	_, stageList, err := taskStageRepo.Find(map[string]interface{}{
		"taskId": param.Id,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	//任务的相关人员
	relatedUserIds := []int{}
	for _, val := range param.RelatedUserId {
		id, _ := strconv.Atoi(val)
		relatedUserIds = append(relatedUserIds, id)
	}
	var relatedUser []*domain.User
	if len(relatedUserIds) > 0 {
		_, relatedUser, err = userRepo.Find(map[string]interface{}{
			"ids": relatedUserIds,
		})
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取任务的相关人员"+err.Error())
		}
	}
	ok, err := srv.canUpdateTask(taskData, stageList)
	if err != nil {
		return nil, err
	}
	if !ok {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "日评数据已生成,任务不能再被编辑")
	}
	//更新相关人员
	taskData.RelatedUser = []int{}
	for _, val := range relatedUser {
		taskData.RelatedUser = append(taskData.RelatedUser, int(val.Id))
	}
	//更新任务名称
	taskData.Alias = param.Alias
	taskData.ApplyLevelName(param.LevelName)
	nowTime := time.Now()
	stageMap := map[int]*domain.TaskStage{}
	for _, val := range stageList {
		val.DeletedAt = &nowTime
		stageMap[val.Id] = val
	}
	lastPlanCompletedAt := time.Time{}
	newStageList := []*domain.TaskStage{}
	//标记完成时间变更的里程碑
	markStage := []domain.TaskStage{}
	for i, val2 := range param.StageList {
		t, err := time.ParseInLocation("2006-01-02", val2.PlanCompletedAt, time.Local)
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "请填写里程碑完成时间")
		}
		t = dayEndTime(t)
		if i > 0 {
			if lastPlanCompletedAt.After(t) {
				return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "里程碑["+val2.Name+"]完成时间填写错误")
			}
		}
		lastPlanCompletedAt = t
		if val2.Id == 0 {
			newStage := domain.TaskStage{
				Id:              0,
				TaskId:          taskData.Id,
				Name:            val2.Name,
				SortBy:          i + 1,
				PlanCompletedAt: t.Unix(),
				RealCompletedAt: 0,
			}
			newStageList = append(newStageList, &newStage)
			continue
		}
		oldStage, ok := stageMap[val2.Id]
		if !ok {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "里程碑数据被其他人变更")
		}
		oldStage.DeletedAt = nil
		oldStage.SortBy = i + 1
		oldStage.Name = val2.Name
		if ok := oldStage.PlanCompleted(t); ok {
			markStage = append(markStage, *oldStage)
		}
	}

	stageList = append(stageList, newStageList...)
	//查询是否已经有每日评估
	taskRecordRepo := factory.CreateTaskRecordRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	cnt, _, err := taskRecordRepo.Find(map[string]interface{}{
		"taskId": taskData.Id,
		"limit":  1,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "相关联的任务反馈信息"+err.Error())
	}
	if cnt > 0 {
		for _, v := range stageList {
			if v.DeletedAt != nil {
				return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "已有日评数据,不能删除里程碑")
			}
		}
	}

	err = taskStageRepo.Save(stageList)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	err = taskRepo.Save(taskData)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	messageRepo := factory.CreateMessagePersonalRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	//更具markStage 记录的里程碑数据生成通知
	for _, val := range markStage {
		for _, val2 := range taskData.RelatedUser {
			t1 := time.Unix(val.PlanCompletedAt, 0).Format("2006-01-02")
			s := fmt.Sprintf("【%s 任务里程碑 %s 完成时间变更为 %s,请知晓", taskData.Name, val.Name, t1)
			payload := map[string]string{
				"id": strconv.Itoa(val.Id),
			}
			payloadStr, _ := json.Marshal(payload)
			newMessage := domain.MessagePersonal{
				Id:           0,
				Types:        domain.MessageTypesTaskModify,
				TargetUserId: val2,
				ReadFlag:     domain.MessageUnread,
				Title:        s,
				Content:      s,
				Payload:      string(payloadStr),
			}
			err = messageRepo.Save(&newMessage)
			if err != nil {
				return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
			}
		}
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	return map[string]interface{}{
		"id": param.Id,
	}, nil
}

// 获取任务详情
func (srv TaskService) GetTaskInfo(param *command.GetTaskCommand) (*adapter.TaskInfoAdapter, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	taskRepo := factory.CreateTaskRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskStageRepo := factory.CreateTaskStageRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	userRepo := factory.CreateUserRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskData, err := taskRepo.FindOne(map[string]interface{}{
		"id": param.TaskId,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	_, stageList, err := taskStageRepo.Find(map[string]interface{}{
		"taskId": param.TaskId,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	relatedUserId := taskData.RelatedUser
	var relatedUserList []*domain.User
	if len(relatedUserId) > 0 {
		_, relatedUserList, err = userRepo.Find(map[string]interface{}{
			"ids": relatedUserId,
		})
		if err != nil {
			return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取相关人员"+err.Error())
		}
	}

	//查询是否已经有每日评估
	taskRecordRepo := factory.CreateTaskRecordRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	cnt, _, err := taskRecordRepo.Find(map[string]interface{}{
		"taskId": param.TaskId,
		"limit":  1,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "相关联的任务反馈信息"+err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	result := adapter.TaskInfoAdapter{
		Id:       taskData.Id,
		Name:     taskData.Name,
		Alias:    taskData.Alias,
		LeaderId: taskData.Leader.Id,
		Leader: adapter.UserData{
			Id:      taskData.Leader.Id,
			Account: taskData.Leader.Account,
			Name:    taskData.Leader.Name,
		},
		Status:            int(taskData.Status),
		StatusDescription: taskData.StatusDescription(),
		Level:             taskData.Level,
		LevelName:         taskData.LevelName,
		RelatedUserId:     []string{},
		RelatedUser:       []adapter.UserData{},
		StageList:         []adapter.TaskStage{},
	}
	for _, val := range relatedUserList {
		idStr := strconv.Itoa(int(val.Id))
		result.RelatedUserId = append(result.RelatedUserId, idStr)
		result.RelatedUser = append(result.RelatedUser, adapter.UserData{
			Id:      val.Id,
			Account: val.Account,
			Name:    val.Name,
		})
	}

	for _, val := range stageList {
		t1 := ""
		t2 := ""
		if val.PlanCompletedAt > 0 {
			t1 = time.Unix(val.PlanCompletedAt, 0).Local().Format("2006-01-02")
		}
		if val.RealCompletedAt > 0 {
			t2 = time.Unix(val.RealCompletedAt, 0).Local().Format("2006-01-02")
		}
		stage := adapter.TaskStage{
			Id:                val.Id,
			Name:              val.Name,
			PlanCompletedAt:   t1,
			RealCompletedAt:   t2,
			SortBy:            val.SortBy,
			StatusDescription: val.StatusDescription(),
		}
		if cnt > 0 {
			stage.IsRef = true
		}
		result.StageList = append(result.StageList, stage)
	}
	return &result, nil
}

// RunTask 启动任务
func (srv TaskService) RunTask(param *command.RunTaskCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	taskRepo := factory.CreateTaskRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskData, err := taskRepo.FindOne(map[string]interface{}{
		"id": param.TaskId,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if taskData.Status == domain.TaskRunning {
		return map[string]interface{}{"id": param.TaskId}, nil
	}
	taskData.Status = domain.TaskRunning
	taskData.RunAt = time.Now().Unix()
	err = taskRepo.Save(taskData)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "保存任务数据"+err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	return map[string]interface{}{"id": param.TaskId}, nil
}

// RunTask 停止任务
func (srv TaskService) StopTask(param *command.StopTaskCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	taskRepo := factory.CreateTaskRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskData, err := taskRepo.FindOne(map[string]interface{}{
		"id": param.TaskId,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if taskData.Status == domain.TaskStop {
		return map[string]interface{}{"id": param.TaskId}, nil
	}

	taskData.Status = domain.TaskStop
	taskData.StopAt = time.Now().Unix()
	err = taskRepo.Save(taskData)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "保存任务数据"+err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	return map[string]interface{}{"id": param.TaskId}, nil
}

// ListTask 任务列表
func (srv TaskService) ListTask(param *command.ListTaskCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	taskRepo := factory.CreateTaskRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskStageRepo := factory.CreateTaskStageRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	//
	condition := map[string]interface{}{
		"offset":    0,
		"limit":     20,
		"companyId": param.CompanyId,
	}
	if len(param.SearchWord) > 0 {
		condition["aliasOrLeader"] = "%" + param.SearchWord + "%"
	}
	if param.PageSize > 0 {
		condition["limit"] = param.PageSize
		if param.PageNumber > 0 {
			condition["offset"] = (param.PageNumber - 1) * param.PageSize
		}
	}

	taskCnt, taskList, err := taskRepo.Find(condition)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "查询任务数据"+err.Error())
	}
	taskIdList := []int{}
	for _, val := range taskList {
		taskIdList = append(taskIdList, val.Id)
	}

	_, stageList, err := taskStageRepo.Find(map[string]interface{}{
		"taskIdList": taskIdList,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "查询任务阶段数据"+err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	taskResult := []*adapter.TaskItem{}
	taskMapResult := map[int]*adapter.TaskItem{}
	for _, val := range taskList {
		tk := adapter.TaskItem{
			Id:        val.Id,
			Name:      val.Name,
			Alias:     val.Alias,
			Leader:    val.Leader.Name,
			Status:    int(val.Status),
			Level:     val.Level,
			LevelName: val.LevelName,
			// StageA:    adapter.TaskStage{},
			// StageB:    adapter.TaskStage{},
			// StageC:    adapter.TaskStage{},
			// StageD:    adapter.TaskStage{},
			// StageE:    adapter.TaskStage{},
		}
		taskResult = append(taskResult, &tk)
		taskMapResult[val.Id] = &tk
	}
	for _, val := range stageList {
		taskData, ok := taskMapResult[val.TaskId]
		if !ok {
			continue
		}
		stage := adapter.TaskStage{
			Id:                val.Id,
			Name:              val.Name,
			StatusDescription: val.StatusDescription(),
			SortBy:            val.SortBy,
		}
		switch val.SortBy {
		case 1:
			taskData.StageA = stage
		case 2:
			taskData.StageB = stage
		case 3:
			taskData.StageC = stage
		case 4:
			taskData.StageD = stage
		case 5:
			taskData.StageE = stage
		}
	}
	result := tool_funs.SimpleWrapGridMap(int64(taskCnt), taskResult)
	return result, nil
}

func (srv TaskService) canUpdateTask(taskData *domain.Task, stageList []*domain.TaskStage) (bool, error) {
	return true, nil
}

// CancelAttention 用户取消关注某个任务
func (srv TaskService) CancelAttention(param *command.CancelAttentionCommand) error {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	taskIgnoreRepo := factory.CreateTaskIgnoreRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskIgnore := domain.TaskIgnore{
		Id:        0,
		TaskId:    param.TaskId,
		UserId:    param.UserId,
		CreatedAt: time.Time{},
	}
	err = taskIgnoreRepo.Save(&taskIgnore)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	return nil
}

// 员工绩效-任务管理-列表
func (srv TaskService) ListTask2(param *command.SearchTaskCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	hrbpFlag, err := roleService.GetHrBp(transactionContext, int(param.CompanyId), int(param.UserId))
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取用户的角色信息"+err.Error())
	}
	if hrbpFlag == domain.RoleTypeSystem {
		listData, err := srv.listTask2ForHrbp(param)
		return listData, err
	}
	var limit = 20
	var offset = 0
	if param.PageSize > 0 {
		limit = param.PageSize
		if param.PageNumber > 0 {
			offset = (param.PageNumber - 1) * param.PageSize
		}
	}
	condition := dao.ListTaskCondition{
		Limit:     limit,
		Offset:    offset,
		UserId:    param.UserId,
		TaskName:  param.TaskName,
		LevelName: param.LevelName,
		OnlyMy:    param.OnlyMy,
		LeaderId:  param.LeaderId,
	}

	taskDao := dao.NewTaskDao(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	tasklistData, err := taskDao.ListTaskStageNotHrbp(condition)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取任务列表"+err.Error())
	}
	taskCount, err := taskDao.CountTaskStageNotHrbp(condition)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "统计任务总数"+err.Error())
	}
	taskStageAnomalyCnt, err := taskDao.CountTaskStageAnomalyNotHrbp(condition)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "统计任务里程碑总数"+err.Error())
	}
	taskAnomalyCnt, err := taskDao.CountTaskAnomalyNotHrbp(condition)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "统计任务里程碑总数"+err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}

	taskResult := []*adapter.TaskItem{}
	taskMapResult := map[int]*adapter.TaskItem{}
	for _, val := range tasklistData {
		if _, ok := taskMapResult[val.TaskId]; ok {
			continue
		}
		tk := adapter.TaskItem{
			Id:        val.TaskId,
			Name:      val.TaskName,
			Alias:     val.TaskAliasName,
			Leader:    val.LeaderName,
			Status:    val.TaskStatus,
			Level:     val.Level,
			LevelName: val.LevelName,
			// StageA:    adapter.TaskStage{},
			// StageB:    adapter.TaskStage{},
			// StageC:    adapter.TaskStage{},
			// StageD:    adapter.TaskStage{},
			// StageE:    adapter.TaskStage{},
		}
		taskMapResult[val.TaskId] = &tk
		taskResult = append(taskResult, &tk)
	}
	for _, val := range tasklistData {
		taskData, ok := taskMapResult[val.TaskId]
		if !ok {
			continue
		}
		stage := adapter.TaskStage{
			Id:     val.StageId,
			Name:   val.StageName,
			SortBy: val.StageSortBy,
		}
		switch val.StageSortBy {
		case 1:
			taskData.StageA = stage
		case 2:
			taskData.StageB = stage
		case 3:
			taskData.StageC = stage
		case 4:
			taskData.StageD = stage
		case 5:
			taskData.StageE = stage
		}
	}
	result := tool_funs.SimpleWrapGridMap(int64(taskCount), taskResult)
	result["taskStageAnomaly"] = taskStageAnomalyCnt
	result["taskAnomalyCnt"] = taskAnomalyCnt
	return result, nil
}

// 以hrbp角色权限获取任务列表
// 统计里程碑异常数,反馈异常数
func (srv TaskService) listTask2ForHrbp(param *command.SearchTaskCommand) (map[string]interface{}, error) {
	var limit = 20
	var offset = 0
	if param.PageSize > 0 {
		limit = param.PageSize
		if param.PageNumber > 0 {
			offset = (param.PageNumber - 1) * param.PageSize
		}
	}
	condition := dao.ListTaskCondition{
		Limit:     limit,
		Offset:    offset,
		UserId:    param.UserId,
		TaskName:  param.TaskName,
		LevelName: param.LevelName,
		OnlyMy:    param.OnlyMy,
		LeaderId:  param.LeaderId,
	}
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	taskDao := dao.NewTaskDao(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	tasklistData, err := taskDao.ListTaskStageByHrbp(condition)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取任务列表"+err.Error())
	}
	taskCount, err := taskDao.CountTaskStageByHrbp(condition)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "统计任务总数"+err.Error())
	}
	taskStageAnomalyCnt, err := taskDao.CountTaskStageAnomalyByHrbp(condition)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "统计任务里程碑总数"+err.Error())
	}
	taskAnomalyCnt, err := taskDao.CountTaskAnomalyByHrbp(condition)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "统计任务里程碑总数"+err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	taskResult := []*adapter.TaskItem{}
	taskMapResult := map[int]*adapter.TaskItem{}
	for _, val := range tasklistData {
		if _, ok := taskMapResult[val.TaskId]; ok {
			continue
		}
		tk := adapter.TaskItem{
			Id:        val.TaskId,
			Name:      val.TaskName,
			Alias:     val.TaskAliasName,
			Leader:    val.LeaderName,
			Status:    val.TaskStatus,
			Level:     val.Level,
			LevelName: val.LevelName,
			// StageA:    adapter.TaskStage{},
			// StageB:    adapter.TaskStage{},
			// StageC:    adapter.TaskStage{},
			// StageD:    adapter.TaskStage{},
			// StageE:    adapter.TaskStage{},
		}
		taskMapResult[val.TaskId] = &tk
		taskResult = append(taskResult, &tk)
	}
	for _, val := range tasklistData {
		taskData, ok := taskMapResult[val.TaskId]
		if !ok {
			continue
		}
		stage := adapter.TaskStage{
			Id:     val.StageId,
			Name:   val.StageName,
			SortBy: val.StageSortBy,
		}
		switch val.StageSortBy {
		case 1:
			taskData.StageA = stage
		case 2:
			taskData.StageB = stage
		case 3:
			taskData.StageC = stage
		case 4:
			taskData.StageD = stage
		case 5:
			taskData.StageE = stage
		}
	}
	result := tool_funs.SimpleWrapGridMap(int64(taskCount), taskResult)
	result["taskStageAnomaly"] = taskStageAnomalyCnt
	result["taskAnomalyCnt"] = taskAnomalyCnt
	return result, nil
}

// ReplyTaskStage 根据每日的任务反馈 ,更新任务里程碑
func (srv TaskService) ReplyTaskStage(transactionContext application.TransactionContext, param []*domain.TaskRecord) error {
	taskRepo := factory.CreateTaskRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskStageRepo := factory.CreateTaskStageRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	var taskList []*domain.Task
	var taskStages []*domain.TaskStage
	for _, val := range param {
		taskData, err := taskRepo.FindOne(map[string]interface{}{"id": val.TaskId})
		if err != nil {
			return application.ThrowError(application.INTERNAL_SERVER_ERROR, "找不到任务数据"+err.Error())
		}

		if !(len(val.AssistContent) == 0 || val.AssistContent == "无") {
			taskData.Anomaly = 0
		}
		taskList = append(taskList, taskData)
		_, stageList, err := taskStageRepo.Find(map[string]interface{}{"ids": []int{val.TaskStageCheck.Id}})
		if err != nil {
			return application.ThrowError(application.INTERNAL_SERVER_ERROR, "找不到任务里程碑数据"+err.Error())
		}
		if len(stageList) > 0 {
			stageList[0].RealCompletedAt = val.TaskStageCheck.RealCompletedAt
			taskStages = append(taskStages, stageList[0])
		}
	}
	err := taskStageRepo.Save(taskStages)
	if err != nil {
		return application.ThrowError(application.INTERNAL_SERVER_ERROR, "保存任务里程碑数据"+err.Error())
	}
	for _, val := range taskList {
		err = taskRepo.Save(val)
		if err != nil {
			return application.ThrowError(application.INTERNAL_SERVER_ERROR, "保存任务数据"+err.Error())
		}
	}
	return nil
}

// 获取任务的反馈
func (srv TaskService) ListTaskRecord(param *command.ListTaskRecordCommand) (map[string]interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	taskRecordRepo := factory.CreateTaskRecordRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	cnt, taskRecordList, err := taskRecordRepo.Find(map[string]interface{}{
		"companyId": param.CompanyId,
		"taskId":    param.TaskId,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取任务反馈数据"+err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	resultList := []adapter.TaskRecordAdapter{}
	for _, val := range taskRecordList {
		item := adapter.TaskRecordAdapter{
			Id:            val.Id,
			StaffAssessId: val.StaffAssessId,
			TaskId:        val.TaskId,
			TaskCategory:  val.TaskCategory,
			TaskName:      val.TaskName,
			TaskAlias:     val.TaskAlias,
			TaskLeader:    val.TaskLeader.Name,
			AssistLevel:   val.AssistLevel,
			AssistContent: val.AssistContent,
			TaskStageCheck: adapter.TaskStage{
				Id:                val.Id,
				Name:              val.TaskStageCheck.Name,
				StatusDescription: val.TaskStageCheck.StatusDescription(),
				SortBy:            val.TaskStageCheck.SortBy,
				PlanCompletedAt:   "",
				RealCompletedAt:   "",
			},
			CreatedAt: val.CreatedAt.Local().Format("2006-01-02"),
		}
		t1 := time.Unix(val.TaskStageCheck.PlanCompletedAt, 0).Local().Format("2006-01-02")
		item.TaskStageCheck.PlanCompletedAt = t1
		if val.TaskStageCheck.RealCompletedAt > 0 {
			t2 := time.Unix(val.TaskStageCheck.RealCompletedAt, 0).Local().Format("2006-01-02")
			item.TaskStageCheck.RealCompletedAt = t2
		}
		resultList = append(resultList, item)
	}
	result := tool_funs.SimpleWrapGridMap(int64(cnt), resultList)
	return result, nil
}

// 获取任务详情
func (srv TaskService) DeleteTaskInfo(param *command.GetTaskCommand) (*adapter.TaskInfoAdapter, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	taskRepo := factory.CreateTaskRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	taskData, err := taskRepo.FindOne(map[string]interface{}{
		"id": param.TaskId,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "xx"+err.Error())
	}
	if taskData.CompanyId != param.CompanyId {
		return nil, nil
	}
	nowTime := time.Now()
	taskData.DeletedAt = &nowTime
	err = taskRepo.Save(taskData)
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "xx"+err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	return nil, nil
}