package ink.wgink.service.department.controller.api;

import ink.wgink.annotation.CheckRequestBodyAnnotation;
import ink.wgink.common.base.DefaultBaseController;
import ink.wgink.exceptions.ParamsException;
import ink.wgink.interfaces.consts.IFileConstant;
import ink.wgink.interfaces.consts.ISystemConstant;
import ink.wgink.pojo.ListPage;
import ink.wgink.pojo.dtos.ZTreeDTO;
import ink.wgink.pojo.dtos.department.DepartmentDTO;
import ink.wgink.pojo.result.*;
import ink.wgink.pojo.vos.IdsVO;
import ink.wgink.service.department.pojo.vos.DepartmentVO;
import ink.wgink.service.department.pojo.vos.MergeDepartmentInfoVO;
import ink.wgink.service.department.pojo.vos.MergeNewDepartmentInfoVO;
import ink.wgink.service.department.pojo.vos.SplitDepartmentVO;
import ink.wgink.service.department.service.IDepartmentService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * @ClassName: DepartmentController
 * @Description: 组织部门
 * @Author: wenc
 * @Date: 2019/1/8 7:23 PM
 * @Version: 1.0
 **/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "组织部门")
@RestController
@RequestMapping(ISystemConstant.API_PREFIX + "/department")
public class DepartmentController extends DefaultBaseController {

    @Autowired
    private IDepartmentService departmentService;

    @ApiOperation(value = "组织部门新增", notes = "组织部门新增接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("save")
    @CheckRequestBodyAnnotation
    public SuccessResult save(@RequestBody DepartmentVO departmentVO) throws Exception {
        departmentService.save(departmentVO);
        return new SuccessResult();
    }

    @ApiOperation(value = "组织部门删除", notes = "组织部门删除接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "组织部门ID列表，用下划线分隔", paramType = "path", example = "1_2_3")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @DeleteMapping("remove/{ids}")
    public SuccessResult remove(@PathVariable("ids") String ids) {
        departmentService.remove(Arrays.asList(ids.split("\\_")));
        return new SuccessResult();
    }

    @ApiOperation(value = "组织部门修改", notes = "组织部门修改接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentId", value = "组织部门ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("update/{departmentId}")
    @CheckRequestBodyAnnotation
    public SuccessResult update(@PathVariable("departmentId") String departmentId,
                                @RequestBody DepartmentVO departmentVO) {
        departmentService.update(departmentId, departmentVO);
        return new SuccessResult();
    }

    @ApiOperation(value = "重置组织部门编码", notes = "重置组织部门编码接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("resetcode")
    public SuccessResult resetCode() {
        departmentService.resetCode();
        return new SuccessResult();
    }


    @ApiOperation(value = "更新合并到新增组织部门", notes = "更新合并到新增组织部门接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("updatemergenew")
    @CheckRequestBodyAnnotation
    public SuccessResult updateMergeNew(@RequestBody MergeNewDepartmentInfoVO mergeNewDepartmentInfoVO) throws Exception {
        departmentService.updateMergeNew(mergeNewDepartmentInfoVO);
        return new SuccessResult();
    }

    @ApiOperation(value = "更新合并到组织部门", notes = "更新合并到组织部门接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("updatemerge/{departmentId}")
    @CheckRequestBodyAnnotation
    public SuccessResult updateMerge(@PathVariable("departmentId") String departmentId, @RequestBody MergeDepartmentInfoVO mergeDepartmentInfoVO) {
        departmentService.updateMerge(departmentId, mergeDepartmentInfoVO);
        return new SuccessResult();
    }

    @ApiOperation(value = "更新分割组织部门", notes = "更新分割组织部门接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentId", value = "部门ID", paramType = "path"),
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("updatesplit/{departmentId}")
    @CheckRequestBodyAnnotation
    public SuccessResult updateSplit(@PathVariable("departmentId") String departmentId, @RequestBody SplitDepartmentVO splitDepartmentVO) {
        departmentService.updateSplit(departmentId, splitDepartmentVO);
        return new SuccessResult();
    }

    @ApiOperation(value = "组织部门导入Excel", notes = "组织部门导入Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "excel", value = "文件名称", paramType = "query"),
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("importexcel")
    public UploadExcelResultDTO importExcel(MultipartFile excel) throws Exception {
        if (Objects.isNull(excel)) {
            throw new ParamsException("Excel不能为空");
        }
        if (!excel.getOriginalFilename().endsWith(IFileConstant.EXCEL_SUFFIX_XLS) &&
                !excel.getOriginalFilename().endsWith(IFileConstant.EXCEL_SUFFIX_XLSX)) {
            throw new ParamsException("文件格式为Excel");
        }
        return departmentService.importExcel(excel);
    }

    @ApiOperation(value = "组织部门列表", notes = "组织部门列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentParentId", value = "组织部门上级ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("list/{departmentParentId}")
    public List<DepartmentDTO> list(@PathVariable("departmentParentId") String departmentParentId) {
        Map<String, Object> params = new HashMap<>(0);
        params.put("departmentParentId", departmentParentId);
        return departmentService.listAll(params);
    }

    @ApiOperation(value = "组织部门zTree列表", notes = "组织部门zTree列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "父ID", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listztree")
    public List<ZTreeDTO> listZTree() {
        Map<String, Object> params = requestParams();
        String departmentParentId = "0";
        if (!StringUtils.isBlank(params.get("id") == null ? null : params.get("id").toString())) {
            departmentParentId = params.get("id").toString();
        }
        return departmentService.listZTree(departmentParentId, params);
    }

    @ApiOperation(value = "组织部门zTree列表", notes = "通过地区编码、部门上级ID和部门类型组织部门zTree列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentAreaCode", value = "地区编码", paramType = "path"),
            @ApiImplicitParam(name = "departmentParentId", value = "组织部门上级ID", paramType = "path"),
            @ApiImplicitParam(name = "departmentType", value = "部门类型，1：机构，2：部门", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("list-ztree/area-code/{departmentAreaCode}/parent-id/{departmentParentId}/type/{departmentType}")
    public List<ZTreeDTO> listByAreaCodeAndParentIdAndType(@PathVariable("departmentAreaCode") String departmentAreaCode,
                                                           @PathVariable("departmentParentId") String departmentParentId,
                                                           @PathVariable("departmentType") Integer departmentType) {
        return departmentService.listZTreeByAreaCodeAndParentIdAndType(departmentAreaCode, departmentParentId, departmentType);
    }

    @ApiOperation(value = "组织部门详情", notes = "组织部门详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentId", value = "部门ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("get/{departmentId}")
    public DepartmentDTO get(@PathVariable("departmentId") String departmentId) {
        return departmentService.get(departmentId);
    }

    @ApiOperation(value = "组织部门分页列表", notes = "组织部门分页列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "上级ID", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "rows", value = "显示数量", paramType = "query", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpage")
    public SuccessResultList<List<DepartmentDTO>> listPage(ListPage page) {
        Map<String, Object> params = requestParams();
        String departmentParentId = "0";
        if (!StringUtils.isBlank(params.get("parentId") == null ? null : params.get("parentId").toString())) {
            departmentParentId = params.get("parentId").toString();
        }
        params.put("departmentParentId", departmentParentId);
        page.setParams(params);
        return departmentService.listPage(page);
    }

    @ApiOperation(value = "组织部门获得同一级部门数量（按部门名称）", notes = "组织部门获得同一级部门数量（按部门名称）接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "departmentParentId", value = "上级部门ID", paramType = "path"),
            @ApiImplicitParam(name = "departmentName", value = "上级部门ID", paramType = "path"),
            @ApiImplicitParam(name = "noDepartmentId", value = "不统计的部门ID", paramType = "query"),
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("countbyparentidandname/{departmentParentId}/{departmentName}")
    public SuccessResultData<Integer> countByParentIdAndName(@PathVariable("departmentParentId") String departmentParentId,
                                                             @PathVariable("departmentName") String departmentName,
                                                             @RequestParam(name = "noDepartmentId", required = false) String noDepartmentId) throws UnsupportedEncodingException {
        Map<String, Object> params = getParams();
        params.put("departmentParentId", departmentParentId);
        params.put("departmentName", URLDecoder.decode(departmentName, "UTF-8"));
        params.put("noDepartmentId", noDepartmentId);
        return new SuccessResultData<>(departmentService.count(params));
    }

    @ApiOperation(value = "组织部门列表", notes = "组织部门列表接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("list/ids")
    public List<DepartmentDTO> list(@RequestBody IdsVO idsVO) {
        if (idsVO.getIds().isEmpty()) {
            throw new ParamsException("id列表不能为空");
        }
        return departmentService.listByIds(idsVO.getIds());
    }

}
