package com.bonus.system.basic.controller;

import com.bonus.common.core.domain.R;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
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.SysOrg;
import com.bonus.system.basic.domain.SysTree;
import com.bonus.system.basic.service.SysOrgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 组织信息
 * 
 * @author zys
 */
@RestController
@RequestMapping("/org")
@Slf4j
public class SysOrgController extends BaseController
{
    public static final int ADDRESS_ERROR = 3;
    @Resource(name = "sysOrgService")
    private SysOrgService sysOrgService;

    /**
     * 获取组织列表
     */
    @RequiresPermissions("system:org:list")
    @GetMapping("/list")
    @Log(title = "系统管理->组织管理", businessType = BusinessType.QUERY)
    public AjaxResult list(SysOrg sysOrg) {
        try{
            List<SysOrg> org = sysOrgService.selectOrgList(sysOrg);
            return success(org);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 根据组织编号获取详细信息
     */
    @RequiresPermissions("system:org:query")
    @GetMapping(value = "/{orgId}")
    public AjaxResult getInfo(@PathVariable Long orgId) {
        try{
            return success(sysOrgService.selectOrgById(orgId));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");

    }

    /**
     * 获取组织下拉树列表
     */
    @GetMapping("/treeSelect")
    public AjaxResult treeSelect(SysOrg org) {
        try{
            List<SysOrg> sysOrgList = sysOrgService.selectOrgList(org);
            return success(sysOrgService.buildOrgTreeSelect(sysOrgList));
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 获取组织人员下拉
     */
    @GetMapping("/orgPersonSelect")
    public AjaxResult orgPersonSelect() {
        try{
            List<SysTree> tree = sysOrgService.orgPersonSelect();
            return success(tree);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

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

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

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

    @PostMapping("/importData")
    @RequiresPermissions("system:org:import")
    @ResponseBody
    @Log(title = "系统管理->组织管理->导入组织", businessType = BusinessType.IMPORT)
    public AjaxResult importData(@Param("file") MultipartFile file) {
        try{
            String result = sysOrgService.importData(file);
            if(result.contains("导入异常")){
                return error(result);
            }
            return success("导入成功");
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

    /**
     * 获取组织列表下拉树
     */

    @GetMapping("/listTree")
    @Log(title = "系统管理->组织管理->下拉树", businessType = BusinessType.QUERY)
    public AjaxResult listTree(SysOrg sysOrg) {
        try{
            List<SysOrg> org = sysOrgService.selectOrgList(sysOrg);
            return success(org);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return error("系统异常");
    }

}