package com.bweb.controller;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.SessionObject;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsOrganization;
import com.hfkj.entity.SecUser;
import com.hfkj.model.CommonTreeModel;
import com.hfkj.model.ResponseData;
import com.hfkj.model.UserInfoModel;
import com.hfkj.service.BsOrganizationService;
import com.hfkj.service.CommonService;
import com.hfkj.service.SecUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/bsOrganization")
@Api(value = "组织架构管理")
public class BsOrganizationController {

    private static Logger log = LoggerFactory.getLogger(BsOrganizationController.class);

    @Resource
    private UserCenter userCenter;

    @Resource
    private BsOrganizationService bsOrganizationService;

    @Resource
    private SecUserService secUserService;

    @Resource
    private CommonService commonService;

    @RequestMapping(value = "/getOrganizationTree", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取组织架构树")
    public ResponseData getOrganizationTree(Long companyId) {
        try {
            if (companyId == null) {
                log.error("SecOrganizationController --> getOrganizationTree() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            CommonTreeModel tree = bsOrganizationService.findTree(companyId);
            return ResponseMsgUtil.success(tree);
        } catch (Exception e) {
            log.error("SecOrganizationController --> getOrganizationTree() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getOrganizationList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取组织架构列表")
    public ResponseData getOrganizationList(Long companyId) {
        try {
            if (companyId == null) {
                log.error("SecOrganizationController --> getOrganizationList() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            List<BsOrganization> organizationList = bsOrganizationService.findOrganizationList(companyId);
            return ResponseMsgUtil.success(organizationList);
        } catch (Exception e) {
            log.error("SecOrganizationController --> getOrganizationList() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/addOrganization", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增组织架构")
    public ResponseData addOrganization(@RequestBody BsOrganization organization, HttpServletRequest request) {
        try {
            if (organization.getParentId() == null || organization.getCompanyId() == null
                    || StringUtils.isBlank(organization.getName())
                    || StringUtils.isBlank(organization.getPhone())) {
                log.error("SecOrganizationController --> addOrganization() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            if(sessionObject == null){
                log.error("SecOrganizationController --> addOrganization() error!", "");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
/*            // 校验区域
            if (organization.getRegionId().length() >= 6) {
                organization.setRegionId(organization.getRegionId().substring(0,6));
            } else {
                log.error("SecOrganizationController --> addOrganization() error!", "区级单位所属区域必须选择到区级");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ORG_REGION_HAS_IN_REGION_ERROR, "");
            }

            // 校验区域简称
            if (bsOrganizationService.getOrgByRegionAbbreviate(organization.getRegionAbbreviate()) != null){
                log.error("SecOrganizationController --> addOrganization() error!", "区域简称已存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REGION_ABBREVIATE_EXIST, "");
            }*/

            BsOrganization baseOrganization = bsOrganizationService.findByName(organization.getCompanyId(),organization.getName());
            if (baseOrganization != null) {
                log.error("SecOrganizationController --> addOrganization() error!", "该部门名称已经存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ORGANIZATION_NAME_IS_EXIST_ERROR, "");
            }
            organization.setStatus(1);
            organization.setOpId(userInfoModel.getSecUser().getId());
            organization.setCreateTime(new Date());
            organization.setUpdateTime(new Date());
            bsOrganizationService.addOrganization(organization);
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("SecOrganizationController --> addOrganization() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/updateOrganization", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "修改组织架构")
    public ResponseData updateOrganization(@RequestBody BsOrganization organization, HttpServletRequest request) {
        try {
            if (organization.getId() == null
                    || organization.getParentId() == null
                    || organization.getCompanyId() == null
                    || StringUtils.isBlank(organization.getName())
                    || StringUtils.isBlank(organization.getPhone())) {
                log.error("SecOrganizationController --> updateOrganization() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询部门
            BsOrganization bsOrganization = bsOrganizationService.findById(organization.getId());
            if (bsOrganization == null ) {
                log.error("SecOrganizationController --> updateOrganization() error!", "未找到该部门信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_FIND_ORGANIZATION_ERROR, "");
            }

            //发布人员
            SessionObject sessionObject = userCenter.getSessionObject(request);
            if(sessionObject == null){
                log.error("SecOrganizationController --> updateOrganization() error!", "");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
            }
            UserInfoModel userInfoModel = (UserInfoModel) sessionObject.getObject();
/*            // 校验区域
            if (organization.getRegionId().length() >= 6) {
                organization.setRegionId(organization.getRegionId().substring(0,6));
            } else {
                log.error("SecOrganizationController --> addOrganization() error!", "区级单位所属区域必须选择到区级");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ORG_REGION_HAS_IN_REGION_ERROR, "");
            }

            // 校验区域简称
            BsOrganization regionAbbreviate = bsOrganizationService.getOrgByRegionAbbreviate(organization.getRegionAbbreviate());
            if (regionAbbreviate != null && !regionAbbreviate.getRegionAbbreviate().equals(bsOrganization.getRegionAbbreviate())){
                log.error("SecOrganizationController --> addOrganization() error!", "区域简称已存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REGION_ABBREVIATE_EXIST, "");
            }*/

            BsOrganization baseOrganization = bsOrganizationService.findByName(organization.getCompanyId(),organization.getName());
            if (baseOrganization != null && !baseOrganization.getId().equals(organization.getId())) {
                log.error("SecOrganizationController --> updateOrganization() error!", "该部门名称已经存在");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.ORGANIZATION_NAME_IS_EXIST_ERROR, "");
            }

            //管理员Id
            if(organization.getManagerId() != null){
                //查询用户
                SecUser secUser = secUserService.findById(organization.getManagerId());

                if(secUser == null){
                    log.error("SecOrganizationController --> updateOrganization() error!", "用户身份错误或已过期");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.SEC_USER_EXPIRED, "");
                }

                if(!secUser.getCompanyId().equals(organization.getCompanyId())){
                    log.error("SecOrganizationController --> updateOrganization() error!", "公司验证失败");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.BS_COMPANY_UNAVAILABLE, "");
                }

                organization.setManagerId(secUser.getId());
                organization.setManagerName(secUser.getUserName());
                organization.setManagerPhone(secUser.getTelephone());
            }
            organization.setOpId(userInfoModel.getSecUser().getId());
            organization.setUpdateTime(new Date());
            organization.setStatus(bsOrganization.getStatus());
            organization.setCreateTime(bsOrganization.getCreateTime());
            bsOrganizationService.updateOrganization(organization);
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("SecOrganizationController --> updateOrganization() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/deleteOrganization", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除组织架构")
    public ResponseData deleteOrganization(Long organizationId) {
        try {
            if (organizationId == null) {
                log.error("SecOrganizationController --> deleteOrganization() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            List<BsOrganization> organizationList = bsOrganizationService.findSon(organizationId);
            if (organizationList != null && organizationList.size() != 0) {
                log.error("SecOrganizationController --> deleteOrganization() error!", "该部门下还有子级部门，不能删除");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.SON_ORGANIZATION_IS_EXIST_ERROR, "");
            }
            BsOrganization organization = bsOrganizationService.findById(organizationId);
            if (organization == null) {
                log.error("SecOrganizationController --> deleteOrganization() error!", "未找到该部门信息");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.UN_FIND_ORGANIZATION_ERROR, "");
            }
            if (organization.getParentId() == null) {
                log.error("SecOrganizationController --> deleteOrganization() error!", "顶级组织不允许删除");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.TOP_ORGANIZATION_DELETE_ERROR, "");
            }
            organization.setStatus(0);
            bsOrganizationService.updateOrganization(organization);
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("SecOrganizationController --> deleteOrganization() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getOrganization", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取组织架构详情")
    public ResponseData getOrganization(Long organizationId) {
        try {
            if (organizationId == null) {
                log.error("SecOrganizationController --> getOrganization() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            BsOrganization organization = bsOrganizationService.findById(organizationId);
            if (StringUtils.isNotBlank(organization.getRegionId())) {
                organization.setRegionName(commonService.getRegionName(Long.valueOf(organization.getRegionId())));
            }
            return ResponseMsgUtil.success(organization);
        } catch (Exception e) {
            log.error("SecOrganizationController --> getOrganization() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getOrganizationUnit", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取组织单位列表")
    public ResponseData getOrganizationUnit(String regionId) {
        try {
            if (StringUtils.isBlank(regionId)) {
                log.error("BsOrganizationController --> getOrganizationUnit() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            return ResponseMsgUtil.success(bsOrganizationService.getOrganizationUnit(regionId));
        } catch (Exception e) {
            log.error("BsOrganizationController --> getOrganizationUnit() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
