package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.oa.domain.CmcManageDept;
import com.ruoyi.oa.service.ICmcManageDeptService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysPostService;

/**
 * 岗位信息操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/post")
public class SysPostController extends BaseController
{
    @Autowired
    private ISysPostService postService;

    @Autowired
    private  ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private  ICmcManageDeptService cmcManageDeptService;

    /**
     * 获取岗位列表
     */
    @PreAuthorize("@ss.hasPermi('system:post:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysPost post)
    {
        startPage();
        List<SysPost> list = postService.selectPostList(post);
        return getDataTable(list);
    }

    /**
     * 获取部门主任
     */
    @GetMapping("/deptLeader")
    public AjaxResult getDeptLeader(String userId)
    {
        SysUser deptLeader = postService.selectDeptLeaderByUserId(userId);
        if (deptLeader == null)
            deptLeader = postService.selectViceDeptLeaderByUserId(userId);
        if (deptLeader == null)
            deptLeader = postService.selectSubLeaderByUserId(userId);
        if (deptLeader == null)
            deptLeader = postService.selectSubGmByUserId(userId);
        if (deptLeader == null)
            deptLeader = postService.selectBranchLeaderByUserId(userId);
        if (deptLeader == null)
            deptLeader = postService.selectParentDeptLeaderByUserId(userId);
        return success(deptLeader);
    }

    /**
     * 通过deptId获取部门主任
     */
    @GetMapping("/deptLeaders")
    public AjaxResult getDeptLeaders(String userId)
    {
        List<SysUser> deptLeaderList =  postService.selectDeptLeadersByDeptId(userId);
        return success(deptLeaderList);
    }

    /**
     * 获取部门副主任
     */
    @GetMapping("/deptViceLeader")
    public AjaxResult getViceDeptLeader(String userId)
    {
        SysUser deptLeader = postService.selectViceDeptLeaderByUserId(userId);
        return success(deptLeader);
    }

    /**
     * 通过deptId获取部门主任
     */
    @GetMapping("/deptLeaderByDept")
    public AjaxResult getDeptLeaderByDeptId(String deptId)
    {
        if (deptId.equals("116"))
            deptId = "102";
        SysUser deptLeader = postService.selectDeptLeaderByDeptId(deptId);
        if (deptLeader == null)
            deptLeader = postService.selectViceDeptLeaderByDeptId(deptId);
        if (deptLeader == null)
            deptLeader = postService.selectSubLeaderByDeptId(deptId);
        if (deptLeader == null)
            deptLeader = postService.selectSubGmByDeptId(deptId);
        if (deptLeader == null)
            deptLeader = postService.selectBranchLeaderByDeptId(deptId);
        if (deptLeader == null)
            deptLeader = postService.selectParentDeptLeaderByDeptId(deptId);
        return success(deptLeader);
    }

    /**
     * 通过deptId获取部门主任
     */
    @GetMapping("/deptLeadersByDept")
    public AjaxResult getDeptLeadersByDeptId(String deptId)
    {
        List<SysUser> deptLeaderList =  postService.selectDeptLeadersByDeptId(deptId);
        return success(deptLeaderList);
    }

    /**
     * 通过deptId获取是否部门负责人
     */
    @GetMapping("/isDeptLeader")
    public AjaxResult getIsDeptLeader()
    {
        boolean isLeader = false;
        String deptId = getLoginUser().getDeptId().toString();
        List<Long> userIdList = new ArrayList<>();
        if (postService.selectDeptLeaderByDeptId(deptId) != null) //主任
            userIdList.add(postService.selectDeptLeaderByDeptId(deptId).getUserId());
        if (postService.selectViceDeptLeaderListByDeptId(deptId) != null) //副主任
            for(SysUser sysUser : postService.selectViceDeptLeaderListByDeptId(deptId))
                userIdList.add(sysUser.getUserId());
        if (postService.selectSubLeaderByDeptId(deptId) != null) //子公司执行董事
            userIdList.add(postService.selectSubLeaderByDeptId(deptId).getUserId());
        if (postService.selectSubGmByDeptId(deptId) != null) //子公司总经理
            userIdList.add(postService.selectSubGmByDeptId(deptId).getUserId());
        if (postService.selectBranchLeaderByDeptId(deptId) != null) //分公司经理
            userIdList.add(postService.selectBranchLeaderByDeptId(deptId).getUserId());
        if (userIdList.contains(getLoginUser().getUserId()))
            isLeader = true;
        return success(isLeader);
    }

    /**
     * 通过deptId获取部门副主任
     */
    @GetMapping("/deptViceLeaderByDept")
    public AjaxResult getViceDeptLeaderByDeptId(String deptId)
    {
        SysUser deptLeader = postService.selectViceDeptLeaderByDeptId(deptId);
        return success(deptLeader);
    }

    /**
     * 通过userId获取分管领导
     */
    @GetMapping("/manageLeader")
    public AjaxResult getManageLeader(String userId)
    {
        return success(getManageId(userService.selectUserById(Long.parseLong(userId)).getDeptId().toString(), ""));
    }

    /**
     * 查询总经理
     */
    @GetMapping("/postName")
    public AjaxResult getUserByPost(String postName)
    {
        return success(postService.selectUserListByPostName(postName));
    }

    /**
     * 通过deptId获取分管领导
     */
    @GetMapping("/manageLeaderByDept")
    public AjaxResult getManageLeaderByDeptId(String deptId, String partyAId)
    {
        return success(getManageId(deptId, partyAId));
    }

    @Log(title = "岗位管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:post:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPost post)
    {
        List<SysPost> list = postService.selectPostList(post);
        ExcelUtil<SysPost> util = new ExcelUtil<SysPost>(SysPost.class);
        util.exportExcel(response, list, "岗位数据");
    }

    /**
     * 根据岗位编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:post:query')")
    @GetMapping(value = "/{postId}")
    public AjaxResult getInfo(@PathVariable Long postId)
    {
        return success(postService.selectPostById(postId));
    }

    /**
     * 新增岗位
     */
    @PreAuthorize("@ss.hasPermi('system:post:add')")
    @Log(title = "岗位管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysPost post)
    {
        if (!postService.checkPostNameUnique(post))
        {
            return error("新增岗位'" + post.getPostName() + "'失败，岗位名称已存在");
        }
        else if (!postService.checkPostCodeUnique(post))
        {
            return error("新增岗位'" + post.getPostName() + "'失败，岗位编码已存在");
        }
        post.setCreateBy(getUsername());
        return toAjax(postService.insertPost(post));
    }

    /**
     * 修改岗位
     */
    @PreAuthorize("@ss.hasPermi('system:post:edit')")
    @Log(title = "岗位管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysPost post)
    {
        if (!postService.checkPostNameUnique(post))
        {
            return error("修改岗位'" + post.getPostName() + "'失败，岗位名称已存在");
        }
        else if (!postService.checkPostCodeUnique(post))
        {
            return error("修改岗位'" + post.getPostName() + "'失败，岗位编码已存在");
        }
        post.setUpdateBy(getUsername());
        return toAjax(postService.updatePost(post));
    }

    /**
     * 删除岗位
     */
    @PreAuthorize("@ss.hasPermi('system:post:remove')")
    @Log(title = "岗位管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{postIds}")
    public AjaxResult remove(@PathVariable Long[] postIds)
    {
        return toAjax(postService.deletePostByIds(postIds));
    }

    /**
     * 获取岗位选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        List<SysPost> posts = postService.selectPostAll();
        return success(posts);
    }

    public  List<SysUser> getManageId(String deptId, String partyAId) {
        List<SysUser> userList = new ArrayList<>();
        Long parentId = deptService.selectDeptById(Long.valueOf(deptId)).getParentId();
        if (parentId > 100)
            deptId = parentId.toString();
        CmcManageDept cmcManageDept = new CmcManageDept();
        cmcManageDept.setDeptId(deptId);
        cmcManageDept.setPartyAId(partyAId);
        for (CmcManageDept manageDept : cmcManageDeptService.selectCmcManageDeptList(cmcManageDept)) {
            userList.add(userService.selectUserById(manageDept.getUserId()));
        }
        return userList;
    }
}
