package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ICoreTreeService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysDepartmentService;
import cn.estsh.i3plus.core.api.iservice.busi.ISysOrganizeService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SessionUser;
import cn.estsh.i3plus.pojo.platform.bean.SysDepartment;
import cn.estsh.i3plus.pojo.platform.bean.SysOrganize;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description : 部门管理服务
 * @Reference :
 * @Author : yunhao
 * @Date : 2018-10-24 21:20
 * @Modify :
 **/
@RestController
@Api(description = "部门管理服务")
@RequestMapping(PlatformConstWords.BASE_URL +"/department")
public class SysDepartmentController extends CoreBaseController {
    public static final Logger LOGGER = LoggerFactory.getLogger(SysDepartmentController.class);

    @Autowired
    private ISysDepartmentService departmentService;

    @Autowired
    private ICoreTreeService coreTreeService;

    @Autowired
    private ISysOrganizeService organizeService;

    @PostMapping(value = "/insert")
    @ApiOperation(value = "添加部门", notes = "返回内容添加部门")
    public ResultBean insertSysDepartment(SysDepartment department) {
        try {
            //登陆用户
            SessionUser user = AuthUtil.getSessionUser();

            //条件验证
            ValidatorBean.beginValid(department)
                    .notNull("name", department.getName())
                    .notNull("departmentCode", department.getDepartmentCode())
                    .checkNotZero("organizeId",department.getOrganizeId());

            //新增初始化
            ConvertBean.modelInitialize(department, user);
            if(department.getParentId() == null || department.getParentId() <= 0){
                department.setParentId(CommonEnumUtil.PARENT.DEFAULT.getValue());
                department.setParentNameRdd("顶级部门");
            }

            departmentService.insertSysDepartment(department);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ResultBean.fail(e).setCode(ImppExceptionEnum.BUSINESS_EXCEPTION_DATA_ERROR.getCode());
        }
    }

    @PutMapping(value = "/update")
    @ApiOperation(value = "修改部门", notes = "根据部门id修改信息")
    public ResultBean updateSysDepartmentById(SysDepartment department) {
        try {
            //登陆用户
            SessionUser user = AuthUtil.getSessionUser();

            //条件验证
            ValidatorBean.beginValid(department)
                    .checkNotZero("id", department.getId())
                    .notNull("departmentName", department.getName())
                    .notNull("departmentCode", department.getDepartmentCode())
                    .checkNotZero("organizeId",department.getOrganizeId());

            ConvertBean.modelUpdate(department, user);
            if(department.getParentId() == null || department.getParentId() <= 0){
                department.setParentId(CommonEnumUtil.PARENT.DEFAULT.getValue());
                department.setParentNameRdd("顶级部门");
            }

            departmentService.updateSysDepartment(department);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "查询所有部门", notes = "查询所有部门")
    public ResultBean findSysDepartmentAll() {
        try {
            List<SysDepartment> departmentList = departmentService.listSysDepartment();
            return ResultBean.success("操作成功").setResultList(departmentList).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get/{id}")
    @ApiOperation(value = "根据id查询部门", notes = "根据id查询部门")
    public ResultBean getSysDepartmentById(@PathVariable("id") String id) {
        try {
            ValidatorBean.checkNotNull(id, "角色id 不能为空");

            SysDepartment department = departmentService.getSysDepartmentById(Long.parseLong(id));

            if(department != null){
                return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(department);
            }else {
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/query")
    @ApiOperation(value = "查询部门", notes = "组合查询部门信息外加分页信息")
    public ResultBean querySysDepartment(SysDepartment department, Pager pager) {
        try {
            ListPager list = null;
            if(department.getOrganizeId() != null){
                SysOrganize organize = organizeService.getSysOrganizeById(department.getOrganizeId());
                if(organize != null){
                    coreTreeService.findSysOrganizeChildrenTreePack(organize,0);
                    List<Long> childIds = coreTreeService.findSysOrganizeChildIds(organize);
                    list = departmentService.findSysDepartmentByPager(department,childIds, pager);
                }else {
                    return ResultBean.fail("不存在组织信息").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
                }
            }else{
                list = departmentService.findSysDepartmentByPager(department, pager);
            }
            return ResultBean.success("操作成功").setListPager(list).setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/delete/{id}")
    @ApiOperation(value = "删除部门", notes = "根据部门id删除信息")
    public ResultBean deleteSysDepartment(@PathVariable("id") String id) {
        try {
            //条件验证
            ValidatorBean.checkNotNull(id, "id为空。");

            departmentService.deleteSysDepartmentById(Long.parseLong(id));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/batch-delete")
    @ApiOperation(value = "根据id批量删除", notes = "根据id批量删除")
    public ResultBean deleteSysDepartmentByIds(String[] ids){
        try{
            ids = ConvertBean.modelSafeArrayNumber(ids,true);
            if(ids.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }
            departmentService.deleteSysDepartmentByIds(StringTool.getArrayLong(ids));
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

}
