package com.leromro.web.controller.system;

import java.math.BigDecimal;
import java.util.List;

import com.leromro.common.core.domain.R;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.leromro.common.utils.SecurityUtils;
import com.leromro.core.domain.DeptRegionManagement;
import com.leromro.core.domain.vo.DeptInfoVO;
import com.leromro.core.service.IDeptRegionManagementService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
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 com.leromro.common.annotation.Log;
import com.leromro.common.constant.UserConstants;
import com.leromro.common.core.controller.BaseController;
import com.leromro.common.core.domain.AjaxResult;
import com.leromro.common.core.domain.entity.SysDept;
import com.leromro.common.enums.BusinessType;
import com.leromro.common.utils.StringUtils;
import com.leromro.system.service.ISysDeptService;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
@Api(tags = "区域地址")
public class SysDeptController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IDeptRegionManagementService deptRegionManagementService;

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

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息,并且获取部门所管理的区域的列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        SysDept sysDept = deptService.selectDeptById(deptId);
        List<DeptRegionManagement> list = deptRegionManagementService.list(new LambdaQueryWrapper<DeptRegionManagement>().eq(DeptRegionManagement::getDeptId, deptId));
        DeptInfoVO deptInfoVO = new DeptInfoVO();
        BeanUtils.copyProperties(sysDept,deptInfoVO);
        deptInfoVO.setDeptRegionList(list);
        return success(deptInfoVO);
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else
        if (dept.getDistributionRatio() == null) {
            throw new RuntimeException("新增公司未设置分账比例");
        }
        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)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!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));
    }

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

    /**
     * 修改区域/服务中心分账比例
     */
    @PutMapping("/distribution/ratio")
    public R updateDistributionRatio(@RequestParam List<Long> ids, @RequestParam BigDecimal ratio){
        deptService.updateDistributionRatio(ids,ratio);
        return R.ok();
    }
/*    @PostMapping("/pointList/{deptId}")
    public R updateDeptPointList(String pointList,@PathVariable Long deptId){
        SysDept sysDept = new SysDept();
        sysDept.setPointList(pointList);
        sysDept.setDeptId(deptId);
        deptService.updateDeptPointList(sysDept);
        return R.ok();
    }*/

    @GetMapping("/pointList")
    public R<String> getDeptListById(Long deptId){

        String pointList = deptService.getPointList(deptId);
        return R.ok(pointList);
    }
}
