package com.rf.psychological.institution.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.dao.model.*;
import com.rf.psychological.group.dao.model.GroupAuthEntity;
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.model.InstitutionAuthEntity;
import com.rf.psychological.institution.service.InstitutionAuthService;
import com.rf.psychological.opLog.annotation.OperationLogAnnotation;
import com.rf.psychological.scale.dao.model.SubjectEntity;
import com.rf.psychological.scale.service.CognitiveTaskService;
import com.rf.psychological.scale.service.SubjectService;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
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.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/institutionAuth")
@Api(tags = "机构权限模块接口")
public class InstitutionAuthController extends BaseController {
    @Autowired
    private InstitutionAuthService institutionAuthService;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private CognitiveTaskService cognitiveTaskService;

    @Autowired
    private GroupAuthService groupAuthService;

    @Autowired
    private GroupInfoService groupInfoService;

    /**
     * 权限数据保存
     *
     * @param json
     * @return
     */
    @SafetyProcess
    @OperationLogAnnotation
    @PostMapping("/saveInstitutionAuth")
    @ApiOperation("权限保存")
    public Result saveInstitutionAuth(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        try {
            JSONArray jsonDataArray = JSONArray.parseArray(data);
            List<InstitutionAuthEntity> authList = new ArrayList<>();
            for (Object o : jsonDataArray) {
                JSONObject institutionObj = (JSONObject) o;
                InstitutionAuthEntity institutionAuthEntity = institutionObj.toJavaObject(InstitutionAuthEntity.class);
                System.out.println("institutionAuthEntity" + institutionAuthEntity);
                authList.add(institutionAuthEntity);
            }
            //如果有默认分组，更新默认分组的权限
            if(authList.size()<=0)
                return success();
            InstitutionAuthEntity institutionAuthEntity = authList.get(0);
            GroupEntity groupEntity = this.groupInfoService.findGroupByInstitutionNoAndName(institutionAuthEntity.getInstitutionNo(), Constant.DEFAULT_GROUP_NAME);
            List<GroupAuthEntity> authEntityList = new ArrayList<>();
            if (groupEntity != null) {
                authList.forEach(institutionAuthEntity1 -> {
                    GroupAuthEntity groupAuthEntity = new GroupAuthEntity();
                    groupAuthEntity.setType(institutionAuthEntity1.getType());
                    groupAuthEntity.setGroupId(groupEntity.getId());
                    groupAuthEntity.setBId(institutionAuthEntity1.getBId());

                    authEntityList.add(groupAuthEntity);

                });
            }
            if(authEntityList.size()>0) {
                this.groupAuthService.save(authEntityList);
            }

            this.institutionAuthService.saveInstitutionAuthList(authList);
            return success();
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("", "保存失败，" + exception);
        }
    }

    /**
     * 一键保存机构没有的权限。
     *
     * @param json
     * @return
     */
    @SafetyProcess
    @OperationLogAnnotation
    @PostMapping("/saveAllInstitutionNoAuth")
    @ApiOperation("机构没有的权限全部保存")
    public Result saveAllInstitutionNoAuth(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonObject = JSONArray.parseObject(data);

        String institutionNo = (String) jsonObject.get("institutionNo");
        String type = (String) jsonObject.get("type");

        try {
            institutionAuthService.saveAllInstitutionNoAuth(institutionNo, type);
            return success();
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("", "保存失败，" + exception.toString());
        }
    }

    /**
     * 权限数据查看
     *
     * @return
     */
    @SafetyProcess
    @PostMapping("/getInstitutionAuth")
    @ApiOperation("查看某一下的机构权限表")
    public Result getInstitutionAuth(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        System.out.println("data=====:" + data);

        JSONObject jsonObject = JSONObject.parseObject(data);
        int pageNum = (int) jsonObject.get("pageNum");
        int pageSize = (int) jsonObject.get("pageSize");
        String institutionNo = (String) jsonObject.get("institutionNo");
        String type = (String) jsonObject.get("type");
        String searchKey = (String) jsonObject.get("searchKey");

        JSONObject result = new JSONObject();
        if (type.equals("0")) {
            //判断是否为查询预警量表列表;0--是; 1--否
            if (jsonObject.containsKey("warn") && jsonObject.getString("warn").equals(Constant.DEFAULT_VALUE_ZERO)){
                result.put("data", this.institutionAuthService.getByInstitutionNoAndName(pageNum, pageSize, institutionNo, type, searchKey,Constant.DEFAULT_VALUE_ZERO));
                result.put("allNum", this.institutionAuthService.getAllByTableInAuthAndSubInfoNum(institutionNo, type, searchKey,Constant.DEFAULT_VALUE_ZERO));
            }else {
                result.put("data", this.institutionAuthService.getByInstitutionNoAndName(pageNum, pageSize, institutionNo, type, searchKey,null));
                result.put("allNum", this.institutionAuthService.getAllByTableInAuthAndSubInfoNum(institutionNo, type, searchKey,null));
            }
        }
        if (type.equals("1")) {
            result.put("data", this.institutionAuthService.getAllConTask(pageNum, pageSize, institutionNo, type, searchKey, false));
            result.put("allNum", this.institutionAuthService.getAllConTaskNum(institutionNo, type, searchKey, false));
        }
        try {
            return success(result);
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("", "查询失败，" + exception.toString());
        }
    }

    @SafetyProcess
    @GetMapping("/findNoAuth")
    @ApiOperation("查找机构没有的权限")
    public Result findInstitutionNoAuth(@RequestParam("institutionNo") String institutionNo,
                                        @RequestParam("type") String type, @RequestParam("searchKey") String searchKey,
                                        @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        try {
            JSONObject result = new JSONObject();
            //查询量表部分
            if (type.equals("0")) {
                Page<SubjectEntity> institutionNoSubAuthList = subjectService.findInstitutionNoSubAuthList(institutionNo, searchKey, pageNum, pageSize);
                result.put("data", institutionNoSubAuthList.getContent());
                result.put("allNum", institutionNoSubAuthList.getTotalElements());
            } else {
                Page<CognitiveTaskEntity> institutionNoCTAuthList = cognitiveTaskService.findInstitutionNoCTAuthList(institutionNo, searchKey, pageNum, pageSize);
                result.put("data", institutionNoCTAuthList.getContent());
                result.put("allNum", institutionNoCTAuthList.getTotalElements());
            }
            return success(result);
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("", "find error，" + exception.toString());
        }
    }

    /**
     * 权限数据删除
     *
     * @return
     */
    @SafetyProcess
    @OperationLogAnnotation(value = "数据权限删除")
    @PostMapping("/delInAuth")
    @ApiOperation("数据权限根据id批量删除")
    public Result delInstitutionAuthByIds(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonObject = JSONArray.parseObject(data);

        List<String> ids = (List<String>) jsonObject.get("ids");

        String institutionNo = (String) jsonObject.get("institutionNo");
        List<String> bIds = (List<String>) jsonObject.get("bId");//量表的id

        try {
            this.institutionAuthService.deleteByIds(ids);
            //机构删除权限并把给机构下含有该组的权限删除
            this.groupAuthService.deleteGroupAuthBecauseInstitutionDelete(institutionNo, bIds);
            return success("", "删除成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("", "删除失败，" + exception.toString());
        }
    }

    /**
     * 删除机构全部权限
     *
     * @return
     */
    @SafetyProcess
    @OperationLogAnnotation
    @PostMapping("/delAllInAuth")
    @ApiOperation("删除全部机构权限")
    public Result delAllInAuth(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        System.out.println("data=====:" + data);
        JSONObject jsonObject = JSONArray.parseObject(data);
        String institutionNo = (String) jsonObject.get("institutionNo");
        String type = (String) jsonObject.get("type");
        try {
            institutionAuthService.delAllInAuth(institutionNo, type);
            return success("", "删除成功");
        } catch (Exception exception) {
            exception.printStackTrace();
            return fail("", "删除失败，" + exception.toString());
        }
    }

}
