package com.yijia.web.controller.system;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.yijia.common.core.domain.TreeSelect;
import com.yijia.common.core.domain.model.LoginUser;
import com.yijia.common.utils.bean.BeanUtils;
import com.yijia.station.domain.DeptInfoDemo;
import com.yijia.station.domain.SysDeptDemo;
import org.apache.commons.lang3.ArrayUtils;
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.yijia.common.annotation.Log;
import com.yijia.common.constant.UserConstants;
import com.yijia.common.core.controller.BaseController;
import com.yijia.common.core.domain.AjaxResult;
import com.yijia.common.core.domain.entity.SysDept;
import com.yijia.common.enums.BusinessType;
import com.yijia.common.utils.SecurityUtils;
import com.yijia.common.utils.StringUtils;
import com.yijia.system.service.ISysDeptService;

/**
 * 部门信息
 *
 * @author yijia
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    @GetMapping("/listTree")
    public AjaxResult listTree(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptListTree(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    @GetMapping(value = "/getGroupInfo")
    public AjaxResult getGroupInfo(SysDept dept)
    {
        SysDept sysDepts =new SysDept();
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysDept  sysDept=deptService.selectDeptById(currentUser.getUser().getDeptId());
        if(sysDept.getJiBie()!=null && sysDept.getJiBie()==1){
            dept.setDeptId(sysDept.getDeptId());
            sysDepts=deptService.getGroupInfo(dept);
        }else if(sysDept.getJiBie()!=null && sysDept.getJiBie()==2){
            dept.setDeptId(sysDept.getParentId());
            sysDepts=deptService.getGroupInfo(dept);
        }else{
            sysDepts=new SysDept();
        }
//        SysDeptDemo sysDeptDemo =new SysDeptDemo();
//        BeanUtils.copyProperties(sysDeptDemo, sysDepts);
        return AjaxResult.success(sysDepts);
    }


    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/userdepttree")
    public AjaxResult userdepttree(SysDept dept)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //获取当前登陆人级别
        SysDept deptJb=deptService.selectDeptById(currentUser.getUser().getDeptId());
        List<SysDept> depts =new ArrayList<>();
        if(deptJb!=null ){
            if(deptJb.getJiBie()==0){
                dept.setDeptId(null);
                depts = deptService.selectDeptList(dept);
            }else if(deptJb.getJiBie()==1){
                dept.setParentId(deptJb.getDeptId());
                dept.setDeptId(deptJb.getDeptId());
                depts= deptService.queryDeptList(dept);
            }else if(deptJb.getJiBie()==2){
                dept.setDeptId(deptJb.getDeptId());
                depts= deptService.selectDeptList(dept);
            }
        }
        List<TreeSelect> list = deptService.buildDeptTreeSelect(depts);
        return AjaxResult.success(list);
    }
    /**
     * 查询所有的集团
     *
     */
    @GetMapping("/groupList")
    public AjaxResult groupList(SysDept dept)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        List<SysDept> depts =new ArrayList<>();
        if(currentUser.getUser().getDept().getJiBie() !=null && currentUser.getUser().getDept().getJiBie()== 0 && currentUser.getUser().getAgentFlag().equals("1")){
            SysDept sysDept =new SysDept();
            sysDept.setUserId(currentUser.getUser().getUserId());
            //查询代理人所有的集团
            depts = deptService.selectGroupAgentList(sysDept);
        }else {
            SysDept sysDept =new SysDept();
            sysDept.setParentId(currentUser.getUser().getDeptId());
            depts = deptService.searchDeptList(sysDept);
        }
        return AjaxResult.success(depts);
    }
    /**
     * 根据集团查询油站信息
     *
     */
    @GetMapping("/searchDeptList")
    public AjaxResult searchDeptList(SysDept dept)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        List<SysDept> depts = new ArrayList<>();
        if(dept!=null&& dept.getDeptId()!=null ){
            SysDept sysDept =new SysDept();
            sysDept.setParentId(dept.getDeptId());
            depts = deptService.searchDeptList(sysDept);
        }else{
            if(currentUser.getUser().getDept().getJiBie()!=null && currentUser.getUser().getDept().getJiBie()==1){
                SysDept sysDept =new SysDept();
                sysDept.setParentId(currentUser.getUser().getDeptId());
                depts = deptService.searchDeptList(sysDept);
            }
        }
        return AjaxResult.success(depts);
    }

    /****
     * 查询分配代理管理
     */
    @GetMapping("/selectSysAgentList")
    public AjaxResult selectSysAgentList(SysDept dept)
    {
        List<SysDept> depts = deptService.selectSysAgentList(dept);
        List<DeptInfoDemo> deptList=new ArrayList<>();
        if(depts!=null && depts.size()>0){
            for(SysDept sysDept :depts){
                DeptInfoDemo deptDemo =new DeptInfoDemo();
                deptDemo.setDeptId(sysDept.getDeptId());
                deptDemo.setDeptName(sysDept.getDeptName());
                deptList.add(deptDemo);
            }
        }
        return AjaxResult.success(deptList);
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getDeptId()))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }


}
