package com.sptg.gateway.controller.permissions;

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.constant.SysLogConstant;
import com.sptg.common.core.util.CommonUtil;
import com.sptg.common.core.util.TreeUtil;
import com.sptg.common.core.util.WebUtils;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.permissions.api.constant.PermissionsSecurityToken;
import com.sptg.permissions.api.dto.RegionAuthorizeDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.entity.Region;
import com.sptg.permissions.api.entity.RegionAuthorize;
import com.sptg.permissions.api.feigns.OrgFeign;
import com.sptg.permissions.api.feigns.RegionAuthorizeFeign;
import com.sptg.statistics.api.constant.SysLogMenuConstant;
import com.sptg.statistics.api.entity.SysOperationLog;
import com.sptg.statistics.api.feigns.SysOperationLogFeign;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * title: RegionAuthorizeController
 * package: com.sptg.gateway.controller.permissions
 * description: 区域授权-控制器
 *
 *                  
 *                 
 */
@RestController
@RequiredArgsConstructor
public class RegionAuthorizeController {

    /* -------------------------------------------------- 接口注入 -------------------------------------------------- */

    private final ResidentialFeign residentialFeign;
    private final RegionAuthorizeFeign regionAuthorizeFeign;
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final OrgFeign orgFeign;
    private final SysOperationLogFeign sysOperationLogFeign;

    /* --------------------------------------------------- 控制器 --------------------------------------------------- */

    /**
     * 功能描述: 获取某机构的授权区域列表
     * @param orgId 查询的机构Id
     * @return ResultBean<Region>
     *                  
     *                       
     */
    @GetMapping(value = "/permissions/region/authorize/getAuthorizeRegionList/{orgId}")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_REGION_PERMISSIONS,format = DataFormatEnum.JSON)
    public ResultBean<Region> getAuthorizeRegionList(@PathVariable(value = "orgId") Long orgId){
        //  获取机构信息
        Organization organization = this.orgFeign.getOrgById(orgId);
        if (null == organization){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  权限校验
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        if (!organization.getPosition().startsWith(onLineUser.getOrgPosition())){
            return new ResultBean<>(ResultEnum.FORBIDDEN);
        }
        //  获取此机构的区域授权信息
        List<Region> list = this.regionAuthorizeFeign.getAuthorizeRegionList(organization.getPosition());
        return new ResultBean<>(ResultEnum.SUCCESS, TreeUtil.tree(list));
    }

    /**
     * 功能描述: 获取某用户的授权区域列表（包括此机构的下级）
     * @param dto
     * {
     *  groupBy         :   必填,分组条件{ 1：省，2：市，3：区 }
     *  pid             :   选填
     * }
     * @return ResultBean<Region>
     *                  
     *                       
     */
    @Security(format = DataFormatEnum.JSON)
    @GetMapping(value = "/permissions/region/authorize/getAuthorizeRegion")
    public ResultBean<Region> getAuthorizeRegion(RegionAuthorizeDto dto){
        if (null == dto || null == dto.getGroupBy()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        List<Region> regionList = this.regionAuthorizeFeign.getAuthorizeRegion(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,regionList);
    }

    /**
     * 功能描述: 分页查询授权列表
     * @param dto
     * {
     *      areaId          :   选填,区域Id
     *      isAuthorized    :   选填，{ 1：已授权，2：未授权，null：全部 }
     *      orgId           :   必填
     *      residentialName :   选填,小区名称
     * }
     * @param pageBean 分页信息
     * @return List<RegionAuthorize>
     *                  
     *                      
     */
    @GetMapping(value = "/permissions/region/authorize/pagingQuery")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_REGION_PERMISSIONS,format = DataFormatEnum.JSON)
    public ResultBean<Page> pagingQuery(RegionAuthorizeDto dto,PageBean<RegionAuthorize,RegionAuthorizeDto> pageBean){
        if (null == dto || null == dto.getOrgId()){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  获取机构信息
        Organization organization = this.orgFeign.getOrgById(dto.getOrgId());
        if (null == organization){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  权限校验
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        if (!organization.getPosition().startsWith(onLineUser.getOrgPosition())){
            return new ResultBean<>(ResultEnum.FORBIDDEN);
        }
        dto.setOrgPosition(organization.getPosition());
        dto.setUserOrgPosition(onLineUser.getOrgPosition());
        pageBean.setDto(dto);
        Page<RegionAuthorize> page = this.regionAuthorizeFeign.pagingQuery(pageBean);
        return new ResultBean<>(ResultEnum.SUCCESS,page);
    }

    /**
     * 功能描述: 批量授权
     * @param dto 授权信息
     * @return ResultBean<Boolean>
     *                  
     *                      
     */
    @PostMapping(value = "/permissions/region/authorize/batch/add")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_REGION_PERMISSIONS,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> batchAdd(RegionAuthorizeDto dto){
        //  参数校验
        Assert.notNull(dto,"请求参数有误");
        Assert.notNull(dto.getOrgId(),"机构Id不能为空");
        Assert.hasText(dto.getOrgIds(),"小区Id不能为空");
        List<Long> orgIdList = CommonUtil.stringToLongList(dto.getOrgIds());
        Assert.isTrue(orgIdList.size() > OperationConstant.ZERO,"小区Id不能为空");
        //  获取机构信息
        Organization organization = this.orgFeign.getOrgById(dto.getOrgId());
        Assert.notNull(organization,"机构Id不存在");
        //  权限校验
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        if (!organization.getPosition().startsWith(onLineUser.getOrgPosition())){
            return new ResultBean<>(ResultEnum.FORBIDDEN);
        }
        dto.setOrgPosition(organization.getPosition());
        dto.setOrgIdList(orgIdList);
        dto.setCreateAccountId(onLineUser.getId());
        ResultBean<Boolean> resultBean=this.regionAuthorizeFeign.batchAdd(dto);
        if( null != resultBean && resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ORGANIZATION_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),"机构区域权限分配orgIds("+dto.getOrgIds()+")",dto,onLineUser);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述: 批量删除
     * @param dto 授权信息
     * @return ResultBean<Boolean>
     *                  
     *                      
     */
    @PostMapping(value = "/permissions/region/authorize/batch/delete")
    @Security(token = PermissionsSecurityToken.ORGANIZATION_REGION_PERMISSIONS,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> batchDelete(RegionAuthorizeDto dto){
        //  参数校验
        if (null == dto || null == dto.getOrgId() || StringUtils.isEmpty(dto.getOrgIds())){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        List<Long> orgIdList = CommonUtil.stringToLongList(dto.getOrgIds());
        if (orgIdList.size() == OperationConstant.ZERO){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  获取机构信息
        Organization organization = this.orgFeign.getOrgById(dto.getOrgId());
        if (null == organization){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        //  权限校验
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        if (!organization.getPosition().startsWith(onLineUser.getOrgPosition())){
            return new ResultBean<>(ResultEnum.FORBIDDEN);
        }
        dto.setOrgIdList(orgIdList);
        dto.setOrgPosition(organization.getPosition());
        ResultBean<Boolean> resultBean=this.regionAuthorizeFeign.batchDelete(dto);
        if(null != resultBean && resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ORGANIZATION_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),"机构删除区域权限分配orgIds("+dto.getOrgIds()+")",dto,onLineUser);
            sysOperationLogFeign.info(sysOperationLog);
            /*-------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述: 查询授权小区的上级机构列表
     * @param dto
     * {
     *      isSelectParent  :   选填,是否查询父级
     *      pid             :   选填,指定某机构的的数据
     * }
     * @return ResultBean<Organization>
     *                  
     *                       
     */
    @Security(format = DataFormatEnum.JSON)
    @GetMapping(value = "/permissions/region/authorize/getAuthorizeOrgList")
    public ResultBean<Organization> getAuthorizeOrgList(RegionAuthorizeDto dto){
        dto = null == dto ? new RegionAuthorizeDto() : dto;
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        List<Organization> orgList = this.regionAuthorizeFeign.getAuthorizeOrgList(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,orgList);
    }

    /**
     * 功能描述: 查询授权小区的上级机构列表
     * @param dto
     * {
     *      pid             :   选填,指定某机构的的数据
     * }
     * @return ResultBean<Organization>
     *                
     *                     
     */
    @Security(format = DataFormatEnum.JSON)
    @GetMapping(value = "/permissions/region/authorize/getAuthorizeOrgListTwo")
    public ResultBean<Organization> getAuthorizeOrgListTwo(RegionAuthorizeDto dto){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto = null == dto ? new RegionAuthorizeDto() : dto;
        dto.setOrgPosition(onLineUser.getOrgPosition());
        List<Organization> orgList = this.regionAuthorizeFeign.getAuthorizeOrgListTwo(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,orgList);
    }

    /**
     * 功能描述: 分页获取授权小区的详细信息
     * @param dto 查询条件
     * @return ResultBean<Page>
     *                  
     *                       
     */
    @Security(format = DataFormatEnum.JSON)
    @GetMapping(value = "/permissions/region/authorize/pagingQueryAuthorizeOrg")
    public ResultBean<Page> pagingQueryAuthorizeOrg(RegionAuthorizeDto dto, PageBean<RegionAuthorize,RegionAuthorizeDto> pageBean){
        dto = null == dto ? new RegionAuthorizeDto() : dto;
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setOrgPosition(onLineUser.getOrgPosition());
        pageBean.setDto(dto);
        //  获取授权小区的列表
        Page<Organization> orgPage = this.regionAuthorizeFeign.pagingQueryAuthorizeOrg(pageBean);
        if (orgPage.getTotal() > OperationConstant.ZERO){
            //  获取详细信息
            List<Long> idList = orgPage.getRecords().stream().map(Organization::getId).collect(Collectors.toList());
            List<Residential> xqList = this.residentialFeign.getByOrgIdList(idList);
            Page<Residential> xqPage = new Page<>(pageBean.getCurrent(),pageBean.getSize());
            xqPage.setRecords(xqList);
            xqPage.setTotal(orgPage.getTotal());
            return new ResultBean<>(ResultEnum.SUCCESS,xqPage);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,pageBean);
    }

}
