package cn.ezhizao.project.system.controller;

import cn.ezhizao.common.constant.UserConstants;
import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.turnover.domain.BizTurnover;
import cn.ezhizao.project.business.turnover.service.IBizTurnoverService;
import cn.ezhizao.project.system.domain.SysDept;
import cn.ezhizao.project.system.domain.SysDeptUser;
import cn.ezhizao.project.system.service.ISysDeptService;
import cn.ezhizao.project.system.service.ISysDeptUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

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

    @Resource
    private ISysDeptUserService deptUserService;
    @Resource
    HttpServletRequest request;

    @Resource
    private IBizTurnoverService bizTurnoverService;

    /**
     * 获取部门列表
     */
    @Log(title = "部门管理查询", businessType = BusinessType.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(SysDept dept) throws NoSuchFieldException, IllegalAccessException {
        String tenantId = request.getHeader("tenantId");
        dept.setTenantId(Long.valueOf(tenantId));
        if(dept.getWorkshopId()!=null) {
            startPage();
            List<SysDept> departments = deptService.selectDeptList(dept);
            return getDataTable (departments);
        }
        List<SysDept> departments = deptService.selectDeptList(dept);
        return getDataTable(departments);
    }
    @Log(title = "合格证选择工段", businessType = BusinessType.SELECT)
    @GetMapping("/listForCertificate")
    public TableDataInfo listForCertificate(SysDept dept) throws NoSuchFieldException, IllegalAccessException {
        String tenantId = request.getHeader("tenantId");
        dept.setHasPackageLine(1);
        dept.setTenantId(Long.valueOf(tenantId));
        if(dept.getWorkshopId()!=null) {
            startPage();
            List<SysDept> departments = deptService.selectDeptList(dept);
            return getDataTable (departments);
        }
        List<SysDept> departments = deptService.selectDeptList(dept);
        return getDataTable(departments);
    }
    /**
     * 获取部门名称和id
     */
    @Log(title = "部门管理获取部门名称和id", businessType = BusinessType.SELECT)
    @GetMapping("/getDeptList")
    public AjaxResult getDeptList(SysDept dept) {
//        String tenantId = request.getHeader("tenantId");
//        dept.setTenantId(Long.valueOf(tenantId));
        List<SysDept> departments = deptService.getDeptList(dept);
        return success(departments);
    }
    /**
     * 获取部门信息
     */
    @Log(title = "获取未分配车间的工段", businessType = BusinessType.SELECT)
    @GetMapping("/getDeptInfo")
    public TableDataInfo getDeptInfo(SysDept dept) {
        String tenantId = request.getHeader("tenantId");
        dept.setTenantId(Long.valueOf(tenantId));
        startPage();
        List<SysDept> departments = deptService.getDeptInfo(dept);
        return getDataTable(departments);
    }
    @Log(title = "针对设备设置使用部门，查询部门", businessType = BusinessType.SELECT)
    @GetMapping("/listForEquipment")
    public AjaxResult listForEquipment(SysDept dept) {
        String tenantId = request.getHeader("tenantId");
        dept.setTenantId(Long.valueOf(tenantId));
        List<SysDept> departments = deptService.selectDeptList(dept);
        return success(departments);
    }
    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @Log(title = "查询部门列表（排除节点）", businessType = BusinessType.SELECT)
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        String tenantId = request.getHeader("tenantId");
       SysDept dept = new SysDept();
       dept.setTenantId(Long.valueOf(tenantId));
        List<SysDept> depts = deptService.selectDeptList(dept);
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

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

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) throws NoSuchFieldException, IllegalAccessException {
        String tenantId = request.getHeader("tenantId");
        dept.setTenantId(Long.valueOf(tenantId));
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());
        return toAjax(deptService.insertDept(dept));
    }
    /**
     * 新增或修改部门
     */
    @Log(title = "部门管理保存", businessType = BusinessType.INSERT)
    @PostMapping(value = "save")
    @Transactional
    public AjaxResult save(@Validated @RequestBody SysDept dept) throws NoSuchFieldException, IllegalAccessException {
        if(dept.getTenantId() ==null) {
        String tenantId = request.getHeader("tenantId");
        dept.setTenantId(Long.valueOf(tenantId));
        }
        Long deptId = dept.getDeptId();
        // 判断没有id的进行新增操作
        if(deptId == null){
            if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
            {
                return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
            }
            if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptCodeUnique(dept)))
            {
                return error("新增部门'" + dept.getDeptName() + "'失败，部门编码已存在");
            }
            dept.setCreateBy(getUsername());
            int i = deptService.insertDept(dept);
            //  新增默认摆放区域信息
            if (i > 0) {
                BizTurnover turnover = new BizTurnover();
                turnover.setStatus(9);
                turnover.setCode("默认区");
                turnover.setTenantId(dept.getTenantId());
                turnover.setDeptId(dept.getDeptId());
                bizTurnoverService.save(turnover);
            }
            return toAjax(i);
        }else {
            deptService.checkDeptDataScope(deptId);
            if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
                return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
            }else if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptCodeUnique(dept))) {
                return error("修改部门'" + dept.getDeptName() + "'失败，部门编码已存在");
            }
            else if (dept.getParentId().equals(deptId)) {
                return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
            } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
                return error("该部门包含未停用的子部门！");
            }
            dept.setUpdateBy(getUsername());
            return toAjax(deptService.updateDept(dept));
        }
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) throws NoSuchFieldException, IllegalAccessException {
        String tenantId = request.getHeader("tenantId");
        dept.setTenantId(Long.valueOf(tenantId));
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return toAjax(deptService.updateDept(dept));
    }
    /**
     * 修改工段车间
     */
    @Log(title = "修改工段车间", businessType = BusinessType.UPDATE)
    @PutMapping("/updateDeptWorkshop")
    public AjaxResult updateDeptWorkshop(@RequestBody  SysDept sysDept) throws NoSuchFieldException, IllegalAccessException {
        //车间工段进行删除工段时如果传入值代表添加工段，如果没传入则代表删除，讲workshopId的值变为0
       if(sysDept.getWorkshopId() == null) {
           sysDept.setWorkshopId(0L);
       }
        return toAjax(deptService.updateDeptworkshop(sysDept));
    }

    /**
     * 修改工段车间
     */
    @Log(title = "通过工段id修改工段车间", businessType = BusinessType.UPDATE)
    @PutMapping("/updateDeptWorkshopByDeptId")
    public AjaxResult updateDeptWorkshopByDeptId(@RequestBody  SysDept sysDept) throws NoSuchFieldException, IllegalAccessException {
        deptService.updateDeptWorkshopByDeptId(sysDept);
        return success();
    }
    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "删除部门", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        List<SysDeptUser> deptUserList = deptUserService.query().in("dept_id", deptId).eq("deleted",0).list();
        if (deptUserList.size() > 0)
        {
            return error("部门存在用户,不允许删除");
        }
        if (deptService.hasChildByDeptId(deptId))
        {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 获取工段树列表
     */
    @Log(title = "获取工段树列表", businessType = BusinessType.SELECT)
    @GetMapping("/workSectionTree")
    public AjaxResult workSectionTree(SysDept dept) throws NoSuchFieldException, IllegalAccessException {
        String tenantId = request.getHeader("tenantId");
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        dept.setTenantId(Long.valueOf(tenantId));
        // 未删除
        dept.setDelFlag("0");
        // 施工段
        dept.setIsWorkSection("1");
        //用于工段查询
     if (dept.getGetType() == true){
         QueryWrapper<SysDeptUser> queryWrapper = new QueryWrapper<>();
         List<Long> ids = new ArrayList<>();
         queryWrapper.eq("user_id",userId);
//         queryWrapper.eq("tenant_id",tenantId);
         queryWrapper.eq("deleted",0);
         queryWrapper.eq("is_formman",1);
         List<SysDeptUser> deptList = deptUserService.list(queryWrapper);
         for (SysDeptUser deptUser : deptList
         ) {
             ids.add(deptUser.getDeptId());
         }
         dept.setDeptIds(ids);
         if (dept.getDeptIds().size() > 0) {
             return success(deptService.selectDeptTreeList(dept));
         }
         else {
             //如果这个人不是工段长，则给他开放看到所有工段的权限
             dept.setUserId(1L);
             return success(deptService.selectDeptTreeList(dept));
         }
     }
        return success(deptService.selectDeptTreeList(dept));
    }

}
