package com.rf.psychological.plan.rest;

import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.group.service.GroupInfoService;
import com.rf.psychological.plan.dao.model.PlanGroupEntry;
import com.rf.psychological.plan.dao.model.TestPlanEntity;
import com.rf.psychological.plan.dao.model.TestPlanUserEntity;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.opLog.annotation.OperationLogAnnotation;
import com.rf.psychological.plan.service.PlanGroupService;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.plan.service.TestPlanUserService;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.plan.service.TestPlanService;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.Constant;
import com.rf.psychological.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试计划与用户分组
 */
@Slf4j
@RestController
@RequestMapping("/planGroup")
@Api(tags = "测试计划与分组")
public class PlanGroupController extends BaseController {

    @Autowired
    private TestPlanService planService;

    @Autowired
    private PlanGroupService planGroupService;

    @Autowired
    private GroupInfoService groupService;

    @Autowired
    private UserService userService;

    @Autowired
    private TestPlanUserService planUserService;

    @SafetyProcess
    @OperationLogAnnotation("新增测试计划与用户分组对应关系")
    @PostMapping("/save")
    @ApiOperation(value = "新增测试计划与用户分组的对应关系")
    public Result save(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonObject = JSONObject.parseObject(data);
        PlanGroupEntry planGroupEntry = jsonObject.toJavaObject(PlanGroupEntry.class);
        if(planGroupEntry.getId() != null){
            PlanGroupEntry planGroupEntry1 = this.planGroupService.findById(planGroupEntry.getId());
            if(planGroupEntry1 == null){
                return fail("测试计划的分组信息不存在");
            }else{
                TestPlanEntity planEntity =  this.planService.findById(planGroupEntry1.getPlanId());
                if(planEntity == null){
                    return fail("测试计划不存在");
                }
                if(planEntity.getStatus() != Constant.TEST_PLAN_STATUS_UNSTART){
                    String message = planEntity.getStatus() == Constant.TEST_PLAN_STATUS_RUNNING?"当前测试计划正在进行中不允许更改":"当前测试计划已关闭不允许更改";
                    return fail(message);
                }
            }
            //删除原来的测试计划-->用户信息  插入新的测试计划-->用户信息
            this.planUserService.deletePlanIdAndGroupId(planGroupEntry1.getPlanId(),planGroupEntry1.getGroupId());
        }
        this.planGroupService.save(planGroupEntry);
        List<UserEntity> userEntityList = this.userService.findUsersInGroup(planGroupEntry.getGroupId());
        if(userEntityList != null && userEntityList.size() > 0){
            List<TestPlanUserEntity> planUserEntityList = new ArrayList<>();
            userEntityList.forEach(userEntity -> {
                String userId = userEntity.getId();
                String planId = planGroupEntry.getPlanId();
                TestPlanUserEntity user = planUserService.findByUserIdAndPlanId(userId,planId);
                if ( user != null){
                    return;
                }
                TestPlanUserEntity entity = new TestPlanUserEntity();
                entity.setUId(userEntity.getId());
                entity.setTestPlanId(planGroupEntry.getPlanId());
                entity.setCreateTime(LocalDateTime.now());
                entity.setIsComplete(Constant.MAGIC_NUM_0);
                planUserEntityList.add(entity);
            });
            this.planUserService.saveInBatch(planUserEntityList);
        }
        return success();
    }

    /**
     * delete plan-->group
     * @return
     */
    @SafetyProcess
    @OperationLogAnnotation("删除测试计划与用户分组对应关系")
    @ApiOperation(value = "删除测试计划与用户分组对应关系")
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable String id){
        PlanGroupEntry planGroupEntry = this.planGroupService.findById(id);
        //删除测试计划-用户信息
        if(planGroupEntry != null){
            this.planUserService.deletePlanIdAndGroupId(planGroupEntry.getPlanId(),planGroupEntry.getGroupId());
            this.planGroupService.deleteById(id);
        }
        return success();
    }
}
