package com.hotent.uc.controller.openController;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.annotation.OpenApi;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.exception.BaseException;
import com.hotent.base.feign.PortalFeignService;
import com.hotent.base.jwt.JwtTokenHandler;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.*;
import com.hotent.base.util.JwtUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.base.util.time.DateUtil;
import com.hotent.uc.manager.DemensionManager;
import com.hotent.uc.manager.OrgManager;
import com.hotent.uc.model.Demension;
import com.hotent.uc.model.Org;
import com.hotent.uc.params.org.OrgVo;
import com.hotent.vo.OrgFullVo;
import com.hotent.vo.OrgShortVo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api(tags = "三方厂家Api组织接口")
@RequestMapping("/${openApi.prefix}/server/org/")
@ApiGroup(group= {ApiGroupConsts.GROUP_UC})
@OpenApi(moduleName = "org组织模块",function = "开放接口")
public class OrgApiController {
    @Autowired
    private OrgManager orgService;
    @Resource
    JwtTokenHandler jwtTokenHandler;
    @Autowired
    private DemensionManager demensionManager;
    @Autowired
    private PortalFeignService portalFeignService;
    /**
     * 获取所有组织基础信息
     * @return
     */
    @RequestMapping(value="getOrgsAll",method= RequestMethod.GET, produces = { "application/json; charset=utf-8" })
    @ApiOperation(value = "根据更新时间获取,获取所有组织基础信息", httpMethod = "GET", notes = "根据更新时间获取,获取所有组织基础信息")
    @OpenApi(description = "根据更新时间获取,获取所有组织基础信息")
    public CommonResult<?> getOrgsAll(HttpServletRequest request,String updateTime) throws Exception {
        String token = JwtUtil.getToken(request);
        Claims claims = jwtTokenHandler.parseToken(token);
        String demId=getDemId(request);
        String sysCode= (String) claims.get("sysCode");
        QueryFilter<Org> filter = QueryFilter.build();
        filter.withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
        filter.withParam("demId", demId);
        filter.withQuery(new QueryField("IS_DELE_","1", QueryOP.NOT_EQUAL, FieldRelation.AND));
        if(StringUtil.isNotEmpty(updateTime)) {
            filter.withQuery(new QueryField("UPDATE_TIME_", DateUtil.changeDate(updateTime+" 00:00:00","yyyy-MM-dd HH:mm:ss"), QueryOP.GREAT_EQUAL, FieldRelation.AND));
            filter.withSorter(new FieldSort("UPDATE_TIME_", Direction.DESC));
        }
        List<Org> list = orgService.getByParentAndDemTemp(filter);
        List<OrgShortVo> orgList = list.stream()
                .map(item -> {
                    OrgShortVo vo = new OrgShortVo();
                    BeanUtils.copyProperties(item, vo);
                    vo.setIsParent(item.isIsParent());
//                    if(item.getOrderNo()==null){
//                        vo.setOrderNo(0L);
//                    }
//                    if(item.getUpdateTime()==null){
//                        vo.setUpdateTime(vo.getCreateTime());
//                    }
                    return vo;
                })
                .collect(Collectors.toList());
        List<String> orgIdList=getPermissionList(sysCode);
        List<OrgShortVo> filteredList = orgList.stream()
                .filter(entity -> orgIdList.contains(entity.getId()))
                .collect(Collectors.toList());
        PageList<OrgShortVo> pageList = new PageList();
        pageList.setTotal(filteredList.size());
        pageList.setRows(filteredList);
        return new CommonResult(true, "获取所有组织基础信息成功", pageList);
    }


    /**
     * 根据组织ID获取其自组织列表,若orgID为0 则返回根目录列表
     * @param orgId
     */
    @RequestMapping(value="getOrgListByParent",method= RequestMethod.GET, produces = { "application/json; charset=utf-8" })
    @ApiOperation(value = "根据组织ID获取其子组织列表,若orgID为0 则返回根目录列表", httpMethod = "GET", notes = "根据组织ID获取其自组织列表,若orgID为0 则返回根目录列表，参数{\"orgId\":\"1\"}")
    @OpenApi(description = "根据组织ID获取其子组织列表,若orgID为0 则返回根目录列表")
    public CommonResult<?> getOrgListByParent(HttpServletRequest request, String orgId) {
        String token = JwtUtil.getToken(request);
        Claims claims = jwtTokenHandler.parseToken(token);
        String demId=getDemId(request);
        String sysCode= (String) claims.get("sysCode");
        QueryFilter<Org> filter = QueryFilter.build();
        filter.withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
        filter.withParam("demId", demId);
        if(StringUtil.isNotEmpty(orgId) && !"0".equals(orgId)) {
            filter.withParam("parentId", "('"+orgId+"')");
        }
        List<Org> list = orgService.getByParentAndDem(filter);
        List<OrgShortVo> orgList = list.stream()
                .map(item -> {
                    OrgShortVo vo = new OrgShortVo();
                    BeanUtils.copyProperties(item, vo);
                    vo.setIsParent(item.isIsParent());
//                    if(item.getOrderNo()==null){
//                        vo.setOrderNo(0L);
//                    }
//                    if(item.getUpdateTime()==null){
//                        vo.setUpdateTime(vo.getCreateTime());
//                    }
                    return vo;
                })
                .collect(Collectors.toList());
        List<String> orgIdList=getPermissionList(sysCode);
        List<OrgShortVo> filteredList = orgList.stream()
                .filter(entity -> orgIdList.contains(entity.getId()))
                .collect(Collectors.toList());
        PageList<OrgShortVo> pageList = new PageList();
        pageList.setTotal(filteredList.size());
        pageList.setRows(filteredList);
        return new CommonResult(true, "获取组织基础信息成功", pageList);
    }

    /**
     * 根据组织ID获取组织详情
     * @param orgId 组织ID 不能为空
     */
    @RequestMapping(value="getOrgDetail",method= RequestMethod.GET, produces = { "application/json; charset=utf-8" })
    @ApiOperation(value = "根据组织ID获取组织详情", httpMethod = "GET", notes = "根据组织ID获取组织详情，参数{\"orgId\":\"1\"}")
    @OpenApi(description = "根据组织ID获取组织详情")
    public CommonResult<?> getOrgDetail(HttpServletRequest request, String orgId) {
        if (StringUtil.isEmpty(orgId)) {
            throw new BaseException("组织Id【orgId】不能为空！");
        }
        String token = JwtUtil.getToken(request);
        Claims claims = jwtTokenHandler.parseToken(token);
        String demId=getDemId(request);
        String sysCode= (String) claims.get("sysCode");
        boolean flag= getPermissionList(sysCode).stream().anyMatch(e->e.equals(orgId));
        if(flag){
            QueryFilter<Org> filter = QueryFilter.build();
            filter.withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
            filter.withParam("demId", demId);
            filter.withParam("id", orgId);
            List<Org> list = orgService.getByParentAndDem(filter);
            if(list==null || list.size()<=0){
                return new CommonResult(false, "未查询到组织信息");
            }

            Org org = list.get(0);
            OrgFullVo vo = new OrgFullVo();
            BeanUtils.copyProperties(org, vo);
            vo.setIsParent(org.isIsParent());
//            if(org.getOrderNo()==null){
//                vo.setOrderNo(0L);
//            }
//            if(org.getUpdateTime()==null){
//                vo.setUpdateTime(vo.getCreateTime());
//            }
            if(org.getSuperiorOrgId()==null){
                vo.setSuperiorOrgId("");
            }
            if(org.getSuperiorDepId()==null){
                vo.setSuperiorDepId("");
            }
            if(org.getGrade()==null){
                vo.setGrade("");
            }
            return new CommonResult(true, "获取组织信息成功", vo);
        }else{
            QueryFilter<Org> filter = QueryFilter.build();
            filter.withPage(new PageBean(1, PageBean.WITHOUT_PAGE));
            filter.withParam("demId", demId);
            filter.withParam("id", orgId);
            List<Org> list = orgService.getByParentAndDem(filter);
            if(list==null || list.size()<=0){
                return new CommonResult(false, "未查询到组织信息");
            }
            return new CommonResult(false, "获取组织信息失败，权限不足", null);
        }
    }

    @RequestMapping(value = "addOrEditOrg", method = RequestMethod.POST, produces = { "application/json; charset=utf-8" })
    @ApiOperation(value = "新增、编辑组织或部门", httpMethod = "POST", notes = "新增、编辑组织或部门,orgId为空为新增，orgType(0:组织 1:部门 2:关联组织 3:虚拟组织)")
    @OpenApi(description = "新增、编辑组织或部门")
    public CommonResult<?> addOrEditOrg(HttpServletRequest request,@ApiParam(name="orgValue",value="新增、编辑组织或部门",required=true) @RequestBody OrgVo org)
            throws Exception {
        String token = JwtUtil.getToken(request);
        Claims claims = jwtTokenHandler.parseToken(token);
        String demId=getDemId(request);
        String orgName= org.getName();
        if(StringUtil.isEmpty(orgName)){
            return new CommonResult(false, "名称不能为空");
        }
        Integer orgType= org.getOrgType();//类型0:组织 1:部门 2:关联组织 3:虚拟组织
        if(orgType==null){
            return new CommonResult(false, "类型不能为空");
        }

        if(orgType==1){
            String parentId= org.getParentId();//类型0:组织 1:部门 2:关联组织 3:虚拟组织
            if(StringUtil.isEmpty(parentId)){
                return new CommonResult(false, "父id不能为空");
            }

        }
        org.setDemId(demId);
        return orgService.addOrEditOrg(org,demId);
    }


    @RequestMapping(value = "deleteOrg", method = RequestMethod.DELETE, produces = { "application/json; charset=utf-8" })
    @ApiOperation(value = "删除组织或部门", httpMethod = "DELETE", notes = "删除组织或部门")
    @OpenApi(description = "删除组织或部门")
    public CommonResult<?> deleteOrg(HttpServletRequest request,@ApiParam(name="orgValue",value="删除组织或部门",required=true) @RequestBody OrgVo org)
            throws Exception {
        String token = JwtUtil.getToken(request);
        Claims claims = jwtTokenHandler.parseToken(token);
        String demId=getDemId(request);
        String id= org.getId();
        if(StringUtil.isEmpty(id)){
            return new CommonResult(false, "id不能为空");
        }
        org.setDemId(demId);
        return orgService.deleteOrg(org,demId);
    }
    /**
     * @description 获取用户token中的单位默认维度id
     * @author  yangzibin
     * @date    2024/7/13 14:03
     * @param	request
     * @return  String
     */
    private String getDemId(HttpServletRequest request){
        String token = JwtUtil.getToken(request);
        Claims claims = jwtTokenHandler.parseToken(token);
        String tenantId = (String) claims.get("tenantId"); //获取维度
        String demId="";
        QueryWrapper<Demension> lambdaQueryWrapper=new QueryWrapper<>();
        lambdaQueryWrapper.eq("TENANT_ID_",tenantId);
        lambdaQueryWrapper.eq("IS_DEFAULT_","1");
        Demension demension=demensionManager.getBaseMapper().selectOne(lambdaQueryWrapper);
        if(demension!=null){
            demId=demension.getId();
        }
        return demId;
    }
    /**
     * @description
     * @author  yangzibin
     * @date    2024/7/13 15:25
     * @param	sysCode
     * @return  java.util.List<java.lang.String>
     */
    private List<String> getPermissionList(String sysCode){
        ArrayNode arrayNode=portalFeignService.getOrgIdList(sysCode,"0","","");
        List<String> idsList=new ArrayList<>();
        for (JsonNode str : arrayNode) {
            idsList.add(str.asText());
        }
        return idsList;
    }

}
