package com.ruoyi.web.controller.system;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Mark;
import com.ruoyi.common.core.domain.entity.Overhaul;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.entity.SysFileInfo;
import com.ruoyi.system.service.IMarkService;
import com.ruoyi.system.service.IOverhaulService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysFileInfoService;
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.*;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 锅炉信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IOverhaulService overhaulService;
    @Autowired
    private ISysFileInfoService fileInfoService;
    @Autowired
    private IMarkService markService;

    /**
     * 获取锅炉列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        dept.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 查询锅炉列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        SysDept dept = new SysDept();
        dept.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        List<SysDept> depts = deptService.selectDeptList(dept);
        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);
    }

    /**
     * 根据锅炉编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

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


    /**
     * 获取锅炉下拉树列表
     */
    @GetMapping("/getOne")
    public AjaxResult getOne()
    {
        List<SysDept> sysDepts = deptService.list(new LambdaQueryWrapper<SysDept>().eq(SysDept::getTenantId,SecurityUtils.getLoginUser().getTenantId()));
        sysDepts = sysDepts.stream().filter(sysDept -> !sysDept.getAncestors().contains(",")).collect(Collectors.toList());
        //查询维修记录
        AtomicInteger sequeue = new AtomicInteger();
        sysDepts.stream().forEach(sysDept -> {
            List<Overhaul> overhauls = overhaulService.list(new LambdaQueryWrapper<Overhaul>().eq(Overhaul::getDeptId,sysDept.getDeptId()).orderByDesc(Overhaul::getOverhaulTime));
            sysDept.setOverhauls(overhauls);
            sysDept.setSequeue(sequeue.get());
            sequeue.incrementAndGet();
        });
        return AjaxResult.success(sysDepts);
    }

    /**
     * 获取锅炉下拉树列表
     */
    @GetMapping("/getPoint")
    public AjaxResult getPoint(@RequestParam String deptId,@RequestParam String overhaulId)
    {
        List<SysDept> sysDepts = deptService.list(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getTenantId,SecurityUtils.getLoginUser().getTenantId())
                .eq(SysDept::getParentId, Convert.toLong(deptId)));
        sysDepts.stream().forEach(sysDept -> {
            List<SysFileInfo> fileInfos = fileInfoService.list(new LambdaQueryWrapper<SysFileInfo>().eq(SysFileInfo::getDeptId,sysDept.getDeptId()).eq(SysFileInfo::getOverhaulId,Convert.toLong(overhaulId)));
            sysDept.setFileInfos(fileInfos);
            List<Mark> marks = markService.list(new LambdaQueryWrapper<Mark>().eq(Mark::getDeptId,sysDept.getDeptId()).eq(Mark::getOverhaulId,Convert.toLong(overhaulId)));
            sysDept.setMarks(marks);
        });
        return AjaxResult.success(sysDepts);
    }

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

    /**
     * 新增锅炉
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @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.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        dept.setCreateBy(getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改锅炉
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @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(getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除锅炉
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @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));
    }
}
