/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.cqcis.com</a>
 */
package com.crunii.micro.service.sysmgr.controller;

import com.crunii.micro.common.constants.CommonConstants;
import com.crunii.micro.common.dto.PageReq;
import com.crunii.micro.common.dto.PageRsp;
import com.crunii.micro.common.dto.Result;
import com.crunii.micro.domain.dto.Worker;
import com.crunii.micro.domain.entity.main.TsmOrg;
import com.crunii.micro.domain.repo.main.TsmOrgRepo;
import com.crunii.micro.service.sysmgr.api.domain.dto.OrgNode;
import com.crunii.micro.service.sysmgr.dto.ChildrenStatisticsRspVO;
import com.crunii.micro.service.sysmgr.dto.org.*;
import com.crunii.micro.service.sysmgr.dto.sysmgr.OrgDto;
import com.crunii.micro.service.sysmgr.dto.sysmgr.OrgTabulationDto;
import com.crunii.micro.service.sysmgr.service.OrgService;
import com.crunii.micro.web.mvc.CurrWorker;
import com.google.common.base.Stopwatch;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author 田平 create 2023-02-21 10:48:14
 */
@Api(value = "组织管理相关")
@Controller
@RequestMapping("/auth/OrgController")
@Slf4j
public class OrgController {
    @Resource
    private OrgService orgService;

    @Resource
    private TsmOrgRepo tsmOrgRepo;

    @ApiOperation(value = "创建组织")
    @RequestMapping(path = "/createOrg", method = RequestMethod.POST)
    @ResponseBody
    public Result<Long> createOrg(@RequestBody @ApiParam OrgC orgC) {
        Result<Long> result = new Result<>();
        result.setData(orgService.createOrg(orgC));
        return result;
    }

    @ApiOperation(value = "更新组织")
    @RequestMapping(path = "/updateOrg", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> updateOrg(@RequestBody @ApiParam OrgU orgU) {
        Result<String> result = new Result<>();
        orgService.updateOrg(orgU);
        return result;
    }

    @ApiOperation(value = "通过父组织Id获取子组织")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentOrgId", value = "父组织id", required = true)
    })
    @RequestMapping(path = "/getOrgChildren", method = RequestMethod.GET)
    @ResponseBody
    public Result<List<OrgNode>> getOrgChildren(@RequestParam("parentOrgId") Long parentOrgId, @RequestParam(name = "registrationSystemType", required = false) Integer registrationSystemType) {
        Result<List<OrgNode>> result = new Result<>();
        result.setData(orgService.getOrgChildren(parentOrgId, registrationSystemType));
        return result;
    }

    @ApiOperation(value = "通过父组织Id获取子组织(数据权限过滤)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentOrgId", value = "父组织id", required = true)
    })
    @RequestMapping(path = "/getOrgChildrenByParentOrgId", method = RequestMethod.GET)
    @ResponseBody
    public Result<List<OrgNode>> getOrgChildrenByParentOrgId(@RequestParam("parentOrgId") Long parentOrgId) {
        Result<List<OrgNode>> result = new Result<>();
        result.setData(orgService.getOrgChildrenByParentOrgId(parentOrgId));
        return result;
    }

    @ApiOperation(value = "校验组织编码是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgCode", value = "组织编码", required = true)
    })
    @RequestMapping(path = "/checkOrgCode", method = RequestMethod.GET)
    @ResponseBody
    public Result<Boolean> checkOrgCode(String orgCode) {
        Result<Boolean> result = new Result<>();
        result.setData(orgService.checkOrgCode(orgCode));
        return result;
    }

    @ApiOperation(value = "组织Id获取组织")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "组织Id", required = true)
    })
    @RequestMapping(path = "/getOrg", method = RequestMethod.GET)
    @ResponseBody
    public Result<TsmOrg> getOrg(Long orgId) {
        Result<TsmOrg> result = new Result<>();
        result.setData(orgService.getTsmOrg(orgId));
        return result;
    }

    @ApiOperation(value = "模糊查询组织")
    @RequestMapping(path = "/findOrg", method = RequestMethod.POST)
    @ResponseBody
    public Result<List<OrgNode>> findOrg(@RequestBody OrgDto orgDto) {
        Result<List<OrgNode>> result = new Result<>();
        result.setData(orgService.findOrg(orgDto));
        return result;
    }

    @ApiOperation(value = "通过父组织Id获取所有子组织")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentOrgId", value = "父组织id", required = true)
    })
    @RequestMapping(path = "/getAllOrgChildren", method = RequestMethod.GET)
    @ResponseBody
    public Result<Set<OrgNode>> getAllOrgChildren(Long parentOrgId) {
        Result<Set<OrgNode>> result = new Result<>();
        result.setData(orgService.getAllOrgChildren(parentOrgId));
        return result;
    }

    @ApiOperation(value = "查询组织树")
    @RequestMapping(path = "/getOrgChildrenTree", method = RequestMethod.POST)
    @ResponseBody
    public Result<List<OrgTreeDto>> getOrgChildrenTree(@CurrWorker @ApiIgnore Worker worker, @RequestBody @ApiParam OrgTreeReqDto param) {
        Result<List<OrgTreeDto>> result = new Result<>();
        result.setData(orgService.getOrgChildrenTree(worker, param));
        return result;
    }

    @ApiOperation(value = "查询组织树权限")
    @RequestMapping(path = "/getOrgTreeAuthority", method = RequestMethod.POST)
    @ResponseBody
    public Result<List<OrgTreeDto>> getOrgTreeAuthority(@CurrWorker @ApiIgnore Worker worker, @RequestBody @ApiParam OrgTreeAuthorityReqDto req) {
        Result<List<OrgTreeDto>> result = new Result<>();
        result.setData(orgService.getOrgTreeAuthority(worker, req));
        return result;
    }

    @ApiOperation(value = "查询组织树权限-团组织列表")
    @RequestMapping(path = "/getOrgTreeAuthList", method = RequestMethod.POST)
    @ResponseBody
    public Result<List<OrgTreeDto>> getOrgTreeAuthList(@CurrWorker @ApiIgnore Worker worker, @RequestBody @ApiParam OrgTreeAuthorityReqDto req) {
        Result<List<OrgTreeDto>> result = new Result<>();
        result.setData(orgService.getOrgTreeAuthList(worker, req));
        return result;
    }

    @ApiOperation(value = "根据区域id获取直属组织")
    @RequestMapping(path = "/getOrgByZoneId", method = RequestMethod.GET)
    @ResponseBody
    public Result<List<TsmOrg>> getOrgByZoneId(@RequestParam("zoneId") Long zoneId) {
        Result<List<TsmOrg>> result = new Result<>();
        result.setData(orgService.getOrgByZoneId(zoneId));
        return result;
    }

    @ApiOperation(value = "根据组织名获取组织(精确查找)")
    @RequestMapping(path = "/getOrgByOrgName", method = RequestMethod.GET)
    @ResponseBody
    public Result<TsmOrg> getOrgByOrgName(@RequestParam("orgName") String orgName) {
        Result<TsmOrg> result = new Result<>();

        result.setData(orgService.getOrgByOrgName(orgName));
        return result;
    }

    @ApiOperation("组织排序数据录入")
    @PostMapping("/orgSortData")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId", value = "组织id", required = true)
    })
    public void orgSortData(Long orgId) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        List<TsmOrg> orgIdList = tsmOrgRepo.findByParentOrgIdAndState(orgId, CommonConstants.STATE_VALID);
        for (int i = 0; i < orgIdList.size(); i++) {
            // 查看该组织是否还有下集组织
            List<TsmOrg> checkParentOrg = tsmOrgRepo.findByParentOrgIdAndState(orgIdList.get(i).getOrgId(),
                    CommonConstants.STATE_VALID);
            if (checkParentOrg.size() > 0) {
                // 若有下级组织则迭代
                orgSortData(orgIdList.get(i).getOrgId());
            } else {
                // 若没有就对该组织赋值序列号
                log.info("组织id:" + orgIdList.get(i).getOrgId() + ",赋值序列号:" + (i + 1));
                if (Objects.isNull(orgIdList.get(i).getSortId())) {
                    orgService.orgSortData(orgIdList.get(i).getOrgId(), (long) (i + 1));
                    log.info("赋值序列号成功");
                } else {
                    log.info("该组织id:" + orgIdList.get(i).getOrgId() + "已有序列号");
                }
            }
        }
        stopwatch.stop();
        stopwatch.elapsed();
        log.info("完成时间:" + stopwatch);
    }




    @ApiOperation(value = "组织-查询置顶父级以及下级组织")
    @RequestMapping(path = "/getOrgByOne", method = RequestMethod.GET)
    @ResponseBody
    public Result<List<OrgTreeOneDto>> getOrgByOne() {
        Result<List<OrgTreeOneDto>> result = new Result<>();
        result.setData(orgService.getOrgByOne());
        return result;
    }

    @PostMapping("/pageChildrenOrg")
    @ApiOperation("团组织-查询下级组织")
    @ResponseBody
    public Result<PageRsp<ChildrenOrgRspVO>> pageChildrenOrg(@RequestBody PageReq<ChildrenOrgReqVO> childrenOrgReqVO) {
        return Result.ofSuccess(orgService.pageChildrenOrg(childrenOrgReqVO));
    }

    @PostMapping("/exportOrgTabulation")
    @ApiOperation(value = "导出下级组织列表")
    @ResponseBody
    public Result<Object> exportOrgTabulation(@Validated @RequestBody OrgTabulationDto dto) {
        return orgService.exportOrgTabulation(dto);
    }

    @PostMapping("/moveDataList")
    @ApiOperation("组织列表上下移动")
    @ResponseBody
    public Result<Object> moveDataList(@Validated @RequestBody MoveDataListDto dto) {
        return orgService.moveDataList(dto);
    }

    @ApiOperation(value = "删除组织")
    @PostMapping("/deleteOrg")
    @ResponseBody
    public Result<Object> deleteOrg(@RequestBody DeleteOrgDto dto) {
        return orgService.deleteOrg(dto.getOrgId());
    }

    @ApiOperation(value = "团组织-创建组织")
    @RequestMapping(path = "/createTeamOrg", method = RequestMethod.POST)
    @ResponseBody
    public Result<Long> createTeamOrg(@CurrWorker @ApiIgnore Worker worker,@RequestBody @ApiParam TeamOrgC teamOrgC) {
        Result<Long> result = new Result<>();
        result.setData(orgService.createTeamOrg(worker,teamOrgC));
        return result;
    }

    @ApiOperation(value = "团组织-修改组织")
    @RequestMapping(path = "/updateTeamOrg", method = RequestMethod.POST)
    @ResponseBody
    public Result updateTeamOrg(@CurrWorker @ApiIgnore Worker worker,@RequestBody @ApiParam TeamOrgC teamOrgC) {
        Result<Long> result = new Result<>();
        orgService.updateTeamOrg(worker,teamOrgC);
        return result;
    }



    @ApiOperation(value = "团组织-设置组织管理员")
    @RequestMapping(path = "/doManagePeople", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> doManagePeople(@CurrWorker @ApiIgnore Worker worker,@RequestBody @ApiParam OrgManPeopleC orgManPeopleC) {
        Result<Boolean> result = new Result<>();
        result.setData(orgService.doManagePeople(worker,orgManPeopleC));
        return result;
    }

    @PostMapping("/exportAllOrg")
    @ApiOperation(value = "导出全部组织列表")
    @ResponseBody
    public Result<Object> exportAllOrg(@Validated @RequestBody OrgTabulationDto dto, @CurrWorker @ApiIgnore Worker worker) {
        return orgService.exportAllOrg(dto, worker);
    }


    @PostMapping("/pageChildrenStatistics")
    @ApiOperation("查询下级组织统计")
    @ResponseBody
    public Result<PageRsp<ChildrenStatisticsRspVO>> pageChildrenStatistics(@RequestBody PageReq<ChildrenOrgReqVO> childrenOrgReqVO) {
        return Result.ofSuccess(orgService.pageChildrenStatistics(childrenOrgReqVO));
    }


    @PostMapping("/exportChildrenStatistics")
    @ApiOperation(value = "导出下级组织统计")
    @ResponseBody
    public void exportChildrenStatistics( @RequestBody ChildrenOrgReqVO dto) {
         orgService.exportChildrenStatistics(dto);
    }

    @GetMapping("/getOrgBySystem")
    @ApiOperation(value = "根据系统查询所属组织")
    @ResponseBody
    public List<OrgTreeDto> getOrgBySystem(@RequestParam("affiliatingSystem") String affiliatingSystem) {
        return orgService.getOrgBySystem(affiliatingSystem);
    }
    
    @ApiOperation("导出团组织统计")
    @PostMapping("/exportOrgStatistics")
    @ResponseBody
    public void exportOrgStatistics() {
        orgService.exportOrgStatistics();
    }
}
