package com.bonus.system.dept.controller;

import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.log.annotation.Log;
import com.bonus.common.log.enums.BusinessType;
import com.bonus.common.security.annotation.RequiresPermissions;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.system.basic.domain.SysTree;
import com.bonus.system.dept.entity.SubOrgBean;
import com.bonus.system.dept.service.SubOrgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 分公司组织信息
 * 
 * @author fly
 */
@RestController
@RequestMapping("/subOrg")
@Slf4j
public class SubOrgController extends BaseController
{
    public static final int ADDRESS_ERROR = 3;
    @Resource(name = "SubOrgService")
    private SubOrgService service;

    /**
     * 获取组织列表
     */
    @RequiresPermissions("dept:org:list")
    @GetMapping("/list")
    @Log(title = "分公司项目部->项目部管理->列表", businessType = BusinessType.QUERY)
    public TableDataInfo list(SubOrgBean bean) {
        try{
            List<SubOrgBean> subOrgBeans = service.selectSubOrgList(bean);
            return endPage(subOrgBeans);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

    /**
     * 根据组织编号获取详细信息
     */
    @RequiresPermissions("dept:org:query")
    @GetMapping(value = "/{orgId}")
    @Log(title = "分公司项目部->项目部管理->编号获取详细信息", businessType = BusinessType.QUERY)
    public AjaxResult getInfo(@PathVariable Long orgId) {
        try{
            return success(service.selectOrgById(orgId));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");

    }

    /**
     * 新增组织
     */
    @RequiresPermissions("dept:org:add")
    @PostMapping
    @Log(title = "分公司项目部->组织管理->新增组织", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated @RequestBody SubOrgBean org) {
        try{
            if (!service.checkOrgNameUnique(org)) {
                return error("新增组织'" + org.getOrgName() + "'失败，组织名称已存在");
            }
            org.setCreateUserId(SecurityUtils.getLoginUser().getSysUser().getUserId());
            int res = service.insertOrg(org);
            if(res == ADDRESS_ERROR){
                return error("地址输入错误，请输入正确的地址");
            }
            return toAjax(res);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 修改组织
     */
    @RequiresPermissions("dept:org:edit")
    @PutMapping
    @Log(title = "分公司项目部->组织管理->修改组织", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated @RequestBody SubOrgBean org) {
        try{
            if (!service.checkOrgNameUnique(org)) {
                return error("修改组织'" + org.getOrgName() + "'失败，组织名称已存在");
            } else if (org.getId() == org.getParentId()) {
                return error("修改组织'" + org.getOrgName() + "'失败，上级组织不能选择自己");
            }
            org.setUpdateUserId(SecurityUtils.getLoginUser().getSysUser().getUserId());
            int res = service.updateOrg(org);
            if(res == ADDRESS_ERROR){
                return error("地址输入错误，请输入正确的地址");
            }
            return toAjax(res);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 删除组织
     */
    @RequiresPermissions("dept:org:remove")
    @DeleteMapping("/{orgId}")
    @Log(title = "分公司项目部->组织管理->删除组织", businessType = BusinessType.DELETE)
    public AjaxResult remove(@PathVariable("orgId") Long orgId) {
        try{
            if (service.hasChildByOrgId(orgId)) {
                return warn("存在子组织,不允许删除");
            }
            if (service.checkOrgExistUser(orgId)) {
                return warn("组织已分配,不允许删除");
            }
            return toAjax(service.deleteOrgById(orgId));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 提交/撤回 审核
     */
    @RequiresPermissions("dept:org:edit")
    @PutMapping("changeStatus/{orgId}/{reviewerStatus}")
    @Log(title = "分公司项目部->组织管理->修改窗台", businessType = BusinessType.DELETE)
    public AjaxResult changeStatus(@PathVariable("orgId") Long id,@PathVariable("reviewerStatus") String reviewerStatus) {
        try{
            SubOrgBean org = new SubOrgBean();
            org.setId(id);
            org.setReviewerStatus(reviewerStatus);
            return toAjax(service.changeStatus(org));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    @PostMapping("batchChangeStatus")
    @Log(title = "分公司组织信息->分公司项目部审批->一键审批", businessType = BusinessType.UPDATE)
    public AjaxResult batchChangeStatus(@RequestBody SubOrgBean org) {
        try{
            if(CollectionUtils.isEmpty(org.getIds())){
                return AjaxResult.error("请选择要审批的数据");
            }
            for (Long id : org.getIds()) {
                org.setId(id);
                service.changeStatus(org);
            }
            return success();
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 获取组织列表(待审批)
     */
    @RequiresPermissions("dept:check:list")
    @GetMapping("/checkList")
    @Log(title = "分公司项目部->项目部管理", businessType = BusinessType.QUERY)
    public TableDataInfo checkList(SubOrgBean bean) {
        try{
            List<SubOrgBean> subOrgBeans = service.selectSubOrgList(bean);
            return endPage(subOrgBeans);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return getDataTableError(new ArrayList<>());
    }

}