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

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.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      : wei.peng
 * @Date        : 2018-10-22 16:58:42.972
 * @Modify      :
 **/
@RestController
@Api(description = "组织")
@RequestMapping(PlatformConstWords.BASE_URL +"/organize")
public class SysOrganizeController extends CoreBaseController{

    public static final Logger LOGGER = LoggerFactory.getLogger(SysOrganizeController.class);

    @Autowired
    private ISysOrganizeService organizeService;

    @PostMapping(value = "/insert")
    @ApiOperation(value = "新增组织", notes = "组织")
    public ResultBean insertSysOrganize(SysOrganize organize) {
        try {
            //条件验证
            ValidatorBean.beginValid(organize)
                    .notNull("name", organize.getName())
                    .notNull("organizeCode", organize.getOrganizeCode())
                    .notNull("organizeType", organize.getOrganizeType());

            //新增初始化
            ConvertBean.modelInitialize(organize, AuthUtil.getSessionUser());
            if(organize.getParentId() == null || organize.getParentId() <= 0){
                organize.setParentId(CommonEnumUtil.PARENT.DEFAULT.getValue());
                organize.setParentNameRdd("顶级组织");
            }

            organize = organizeService.insertSysOrganize(organize);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(organize);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/update")
    @ApiOperation(value = "修改组织", notes = "组织")
    public ResultBean updateSysOrganize(SysOrganize organize) {
        try {
            // 数据校验
            ValidatorBean.beginValid(organize)
                    .notNull("id", organize.getId())
                    .notNull("name", organize.getName())
                    .notNull("organizeCode", organize.getOrganizeCode())
                    .notNull("organizeType", organize.getOrganizeType());

            ConvertBean.modelUpdate(organize, AuthUtil.getSessionUser());
            if(organize.getParentId() == null || organize.getParentId() <= 0){
                organize.setParentId(CommonEnumUtil.PARENT.DEFAULT.getValue());
                organize.setParentNameRdd("顶级组织");
            }

            organizeService.updateSysOrganize(organize);
            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 = "/delete/{id}")
    @ApiOperation(value = "删除组织", notes = "删除组织")
    public ResultBean deleteSysOrganize(@PathVariable("id") String idStr) {
        try {
            // 数据校验
            ValidatorBean.checkIsNumber(idStr.toString(), "您要删除的组织不存在");

            organizeService.deleteSysOrganizeById(Long.parseLong(idStr));
            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 findSysOrganizeAll() {
        try {
            List<SysOrganize> list = organizeService.listSysOrganize();
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(list);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value="/query")
    @ApiOperation(value="查询组织",notes="组合查询组织外加分页")
    public ResultBean queryPosition(SysOrganize organize, Pager pager){
        try{
            ListPager<SysOrganize> listPager = organizeService.querySysOrganize(organize, pager);
            return ResultBean.success("操作成功").setListPager(listPager).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 = "查询组织", notes = "查询根据ID查询组织")
    public ResultBean getBySysOrganizeId(@PathVariable("id") String id) {
        try {
            // 数据校验
            ValidatorBean.checkNotNull(id, "角色id 不能为空");

            SysOrganize organize = organizeService.getSysOrganizeById(Long.parseLong(id));

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

    @PutMapping(value = "/status")
    @ApiOperation(value = "修改组织状态", notes = "根据ID修改组织状态")
    public ResultBean updateStatus(String id, int status) {
        try {
            // 数据校验
            ValidatorBean.checkNotNull(id, "组织id 不能为空");
            ValidatorBean.checkNotZero(status, "组织状态不能为空");

            organizeService.updateSysOrganizeStatus(Long.parseLong(id), status, AuthUtil.getSessionUser());
            return new ResultBean(true);
        } 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 deleteSysOrganizeByIds(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();
            }

            organizeService.deleteSysOrganizeByIds(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);
        }
    }
}
