package com.rf.psychological.group.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.group.dao.model.GroupEntity;
import com.rf.psychological.group.service.GroupAuthService;
import com.rf.psychological.group.service.GroupInfoService;
import com.rf.psychological.institution.service.InstitutionAuthService;
import com.rf.psychological.opLog.annotation.OperationLogAnnotation;
import com.rf.psychological.plan.dao.model.PlanGroupEntry;
import com.rf.psychological.plan.dao.model.TestPlanUserEntity;
import com.rf.psychological.plan.service.PlanGroupService;
import com.rf.psychological.plan.service.TestPlanUserService;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.plan.dao.model.TestPlanEntity;
import com.rf.psychological.plan.service.TestPlanService;
import com.rf.psychological.user.dao.model.UserEntity;
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 io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
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;

/**
 * @author lpf
 * @description:
 * @date 26/10/2021下午4:44
 */

@Slf4j
@RestController
@RequestMapping("/group")
@Api(tags = "组操作")
public class GroupInfoController extends BaseController {

    @Autowired
    private GroupInfoService groupInfoService;

    @Autowired
    private GroupAuthService groupAuthService;

    @Autowired
    private UserService userService;

    @Autowired
    private InstitutionAuthService institutionAuthService;

    @Autowired
    private PlanGroupService planGroupService;

    @Autowired
    private TestPlanService planService;

    @Autowired
    private TestPlanUserService planUserService;

    @SafetyProcess
    @GetMapping("/find")
    @ApiOperation("find groups in the institution")
    public Result findGroup(@RequestParam("institutionNo") String institutionNo) throws Exception {
        try {
            return success(this.groupInfoService.findAllByInstitutionNo(institutionNo));
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("", "find error，" + exception.toString());
        }
    }

    @SafetyProcess
    @OperationLogAnnotation
    @PostMapping("/del")
    @ApiOperation("通过组ids删除组(该组的数据表权限也会一同删除)")
    public Result delGroup(@ApiParam("传入一个id的list类型，每个String") @RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONArray jsonArray = JSONObject.parseObject(data).getJSONArray("ids");
        List<String>ids = jsonArray.toJavaList(String.class);
        try {
            String defaultGroupId = null;
            String institutionNo = null;
            //将该组下面用户的组权限变为0
            for (String id : ids) {
                if(defaultGroupId == null){
                    GroupEntity groupEntity = this.groupInfoService.findById(id);
                    if(groupEntity != null ){
                        if(groupEntity.getGroupName().equals(Constant.DEFAULT_GROUP_NAME)){
                            return fail("不能删除默认分组");
                        }
                        groupEntity = this.groupInfoService.findGroupByInstitutionNoAndName(groupEntity.getInstitutionNo(), Constant.DEFAULT_GROUP_NAME);
                        defaultGroupId = groupEntity.getId();
                        institutionNo = groupEntity.getInstitutionNo();
                    }else{
                        log.info("分组"+id+"不存在");
                        continue;
                    }
                }
                //把原分组id修改为默认分组的id
                this.userService.updateUserGroup(institutionNo,id,defaultGroupId);
            }
            //删除组
            this.groupInfoService.delGroup(ids);
            //删除组权限
            this.groupAuthService.deleteAllByGroupId(ids);
            return success();
        } catch (Exception exception) {
            log.info(exception.getMessage());
            exception.printStackTrace();
            return fail();
        }
    }


    @SafetyProcess
    @OperationLogAnnotation("添加组")
    @PostMapping("/add")
    @ApiOperation("add group")
    public Result addGroup(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonObject = JSONArray.parseObject(data);
        GroupEntity groupEntity = jsonObject.toJavaObject(GroupEntity.class);
        if(groupEntity.getGroupName().equals(Constant.DEFAULT_GROUP_NAME)){
            return failBadRequest(null,"分组名称"+groupEntity.getGroupName()+"不合法");
        }
        try {
            return success(this.groupInfoService.addGroup(groupEntity));
        } catch (Exception exception) {
            log.info(exception.getMessage());
            exception.printStackTrace();
            return fail();
        }
    }

    @SafetyProcess
@OperationLogAnnotation("修改组名称")
    @PostMapping("/updateName")
    @ApiOperation("update groupName")
    public Result updateGroup(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonObject = JSONArray.parseObject(data);
        String id = (String) jsonObject.get("id");
        String groupName = (String) jsonObject.get("groupName");
        if (StringUtils.isEmpty(StringUtils.trim(groupName))){
            return fail("分组名称不能为空");
        }
        if(groupName.equals(Constant.DEFAULT_GROUP_NAME)){
            return fail("分组名称"+groupName+"不合法");
        }
        GroupEntity groupEntity = this.groupInfoService.findById(id);
        if(groupEntity != null && groupEntity.getGroupName().equals(Constant.DEFAULT_GROUP_NAME)){
            return fail("不允许修改默认分组名称");
        }
        try {
            this.groupInfoService.updateGroup(groupName, id);
            return success();
        } catch (Exception exception) {
            log.info(exception.getMessage());
            exception.printStackTrace();
            return fail();
        }
    }

    @SafetyProcess
    @PostMapping ("/user/update")
    @ApiOperation("更改用户所属分组")
    public Result changeUserGroup(@RequestBody String json) throws Exception {

        JSONObject jsonObject = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));
        String gId = jsonObject.getString("gId");
        List<String> ids = jsonObject.getJSONArray("ids").toJavaList(String.class);
        if (StringUtils.isEmpty(gId) || ids.isEmpty()) {
            return fail("组id或者用户id输入有空");
        }
        //1.如果用户原所属分组有进行中的计划，不允许修改分组
        //2.如果原所属分组没有进行中的计划，删除用户的未开始计划
        //3.如果新分组有测试计划，为用户创建测试计划信息
        for (String id :ids) {
            if (StringUtils.isEmpty(id)){
                continue;
            }
            //如果用户原分组有测试计划，删除原分组的测试计划
            UserEntity user = this.userService.getOne(id);
            int countRunningPlan = 0;
            List<String> unStartPlanIds = new ArrayList<>();
            //查询原分组是否有测试计划
            List<PlanGroupEntry> planGroupEntries = this.planGroupService.findByGroupId(user.getGId());
            if(planGroupEntries != null && planGroupEntries.size()>0){
                for (PlanGroupEntry planGroupEntry:planGroupEntries) {
                    TestPlanEntity testPlanEntity = this.planService.findById(planGroupEntry.getPlanId());
                    if(testPlanEntity != null){
                        if(testPlanEntity.getStatus() == Constant.TEST_PLAN_STATUS_RUNNING){
                            countRunningPlan += 1;
                            break;
                        } else if (testPlanEntity.getStatus() == Constant.TEST_PLAN_STATUS_UNSTART) {
                            unStartPlanIds.add(testPlanEntity.getId());
                        }
                    }
                }
            }
            if(countRunningPlan > 0){
                return fail("用户"+user.getPetName()+"原所属分组有正在进行中的计划，不允许修改分组");
            }
            if(unStartPlanIds.size()>0){
                unStartPlanIds.forEach(item -> this.planUserService.deleteByUIdAndTestPlanId(id,item));
            }
            //如果新移入的分组有测试计划，为用户创建测试计划信息
            createPlanUserInfo(gId, id);
           // this.userService.updateUserGroup(gId, id);
            user.setGId(gId);
            this.userService.save(user);
        }
        return success();

    }

    /**
     * 创建测试计划用户信息
     * @param groupId
     * @param userId
     */
    private void createPlanUserInfo( String groupId, String userId) {
        createPlanUserInfo(groupId, userId, this.planGroupService, this.planUserService);
    }

    public static void createPlanUserInfo(String groupId, String userId,PlanGroupService planGroupService, TestPlanUserService planUserService ) {
        List<PlanGroupEntry> planGroupEntryList = planGroupService.findByGroupId(groupId);
        if(planGroupEntryList != null && planGroupEntryList.size()>0){
            List<TestPlanUserEntity> testPlanUserEntityList = new ArrayList<>();
            planGroupEntryList.forEach(planGroupEntry ->{
                TestPlanUserEntity testPlanUser = new TestPlanUserEntity();
                testPlanUser.setTestPlanId(planGroupEntry.getPlanId());
                testPlanUser.setCreateTime(LocalDateTime.now());
                testPlanUser.setIsComplete(Constant.TEST_PLAN_USER_STATUS_UNCOMPLETE);
                testPlanUser.setUId(userId);
                testPlanUserEntityList.add(testPlanUser);
            });
            planUserService.saveInBatch(testPlanUserEntityList);
        }
    }

    @SafetyProcess
    @PostMapping("/user/find")
    @ApiOperation("查询组下的用户信息")
    public Result findUserInfo(@RequestBody String json ) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data")));

        if ("".equals(jsonObject.getString("gid"))) {
            return fail("组id为空");
        }
        try {
            return success(this.userService.findUsersInGroup(jsonObject));
//            return success(this.userService.findUsersInGroup(gId));
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("", "后台异常，请寻找管理员：");
        }
    }
}
