package com.ruoyi.web.controller.business;

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

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.enums.BusinessType;
import com.ruoyi.common.core.domain.entity.PolicyMenu;
import com.ruoyi.system.service.IPolicyMenuService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 政策类别Controller
 * 
 * @author boman
 * @date 2022-06-10
 */
@RestController
@RequestMapping("/system/policy")
public class PolicyMenuController extends BaseController
{
    @Autowired
    private IPolicyMenuService policyMenuService;

    /**
     * 查询政策类别列表
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public AjaxResult list(PolicyMenu policyMenu)
    {
        List<PolicyMenu> list = policyMenuService.selectPolicyMenuList(policyMenu);
        return AjaxResult.success(list);
    }

    /**
     * 查询类别列表（排除节点）
     * @param menuId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list/exclude/{menuId}")
    public AjaxResult excludeChild(@PathVariable(value = "menuId", required = false) Long menuId)
    {
        List<PolicyMenu> menus = policyMenuService.selectPolicyMenuList(new PolicyMenu());
        Iterator<PolicyMenu> it = menus.iterator();
        while (it.hasNext())
        {
            PolicyMenu d = (PolicyMenu) it.next();
            if (d.getMenuId().intValue() == menuId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), menuId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(menus);
    }

    /**
     * 导出政策类别列表
     */
    @PreAuthorize("@ss.hasPermi('system:menu:export')")
    @Log(title = "政策类别", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PolicyMenu policyMenu)
    {
        List<PolicyMenu> list = policyMenuService.selectPolicyMenuList(policyMenu);
        ExcelUtil<PolicyMenu> util = new ExcelUtil<PolicyMenu>(PolicyMenu.class);
        util.exportExcel(response, list, "政策类别数据");
    }

    /**
     * 获取政策类别详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable("menuId") Long menuId)
    {
        return AjaxResult.success(policyMenuService.selectPolicyMenuByMenuId(menuId));
    }

    /**
     * 新增政策类别
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "政策类别", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PolicyMenu policyMenu)
    {
        if (UserConstants.NOT_UNIQUE.equals(policyMenuService.checkMenuNameUnique(policyMenu)))
        {
            return AjaxResult.error("新增类别'" + policyMenu.getMenuName() + "'失败，类别名称已存在");
        }
        policyMenu.setCreateBy(getUsername());
        return toAjax(policyMenuService.insertPolicyMenu(policyMenu));
    }

    /**
     * 修改政策类别
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "政策类别", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PolicyMenu policyMenu)
    {

        Long menuId = policyMenu.getMenuId();
        if (UserConstants.NOT_UNIQUE.equals(policyMenuService.checkMenuNameUnique(policyMenu)))
        {
            return AjaxResult.error("修改类别'" + policyMenu.getMenuName() + "'失败，类别名称已存在");
        }
        else if (policyMenu.getParentId().equals(menuId))
        {
            return AjaxResult.error("修改类别'" + policyMenu.getMenuName() + "'失败，上级类别不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, policyMenu.getStatus()) && policyMenuService.selectNormalChildrenMenuById(menuId) > 0)
        {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }
        return toAjax(policyMenuService.updatePolicyMenu(policyMenu));
    }

    /**
     * 删除政策类别
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "政策类别", businessType = BusinessType.DELETE)
	@DeleteMapping("/{menuIds}")
    public AjaxResult remove(@PathVariable Long[] menuIds)
    {
        return toAjax(policyMenuService.deletePolicyMenuByMenuIds(menuIds));
    }


    /**
     * 获取政策类别下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(PolicyMenu policyMenu)
    {
        List<PolicyMenu> menus = policyMenuService.selectMenusList(policyMenu);
        return AjaxResult.success(policyMenuService.buildMenuTreeSelect(menus));
    }

    /***
     * 获取政策类别（APP）
     */
    @GetMapping("/listPolicyMenuApp")
    public AjaxResult listApp(String idCard)
    {
        return policyMenuService.listApp(idCard);
    }
}
