package com.ruoyi.web.controller.finance;

import ch.qos.logback.core.pattern.ConverterUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.EmptyUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.FncSubjectType;
import com.ruoyi.system.domain.vo.FncSubjectTypeVo;
import com.ruoyi.system.service.IFncSubjectTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 科目类别Controller
 *
 * @author jlf
 * @date 2022-11-17
 */
@Api(tags = "科目类别Controller")
@RestController
@RequestMapping("/finance/subjectType")
//@RequiredArgsConstructor(onConstructor = @Autowired)
public class FncSubjectTypeController extends BaseController {

    @Autowired
    private  IFncSubjectTypeService fncSubjectTypeService;

    @ApiOperation("查询科目类别列表")
    @PreAuthorize("@ss.hasPermi('finance:subjectType:list')")
    @GetMapping("/list")
    public TableDataInfo<FncSubjectTypeVo> list(FncSubjectTypeVo entity) {
        return fncSubjectTypeService.queryList(entity);
    }

    @ApiOperation("查询科目类别所有列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(FncSubjectTypeVo entity) {
        return AjaxResult.success("查询成功", fncSubjectTypeService.queryAll(entity));
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('finance:subjectType:list')")
    @GetMapping("/list/exclude/{id}")
    public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id)
    {
        List<FncSubjectType> list = fncSubjectTypeService.list();

        List<Long> ids = new ArrayList<>();
        //递归获取
        if (EmptyUtil.isNotEmpty(list) && EmptyUtil.isNotEmpty(id)) {
            list.stream().filter(item -> item.getParentId() == 0).forEach(item -> {
                if (item.getSubjectTypeId().equals(id)) {
                    return;
                } else {
                    ids.add(item.getSubjectTypeId());
                    list.stream().filter(child -> Objects.equals(child.getParentId(), item.getSubjectTypeId())).forEach(child -> {
                        excludeChild(list,child,id,ids);
                    });
                }
            });
        }

        list.removeIf(d -> d.getSubjectTypeId().intValue() == id || !ids.contains(d.getSubjectTypeId()));
        return success(list);
    }

    public void excludeChild(List<FncSubjectType> list,FncSubjectType entity, Long id, List<Long> ids) {

        if (EmptyUtil.isNotEmpty(entity)) {
            if (entity.getSubjectTypeId().equals(id)) {
                return;
            } else {
                ids.add(entity.getSubjectTypeId());
                list.stream().filter(item -> Objects.equals(item.getParentId(), entity.getSubjectTypeId())).forEach(child -> {

                    excludeChild(list,child,id,ids);
                });
            }
        }

    }


    @ApiOperation("导出科目类别列表")
    @PreAuthorize("@ss.hasPermi('finance:subjectType:export')")
    @Log(title = "科目类别", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FncSubjectTypeVo entity) {
        List<FncSubjectTypeVo> list = fncSubjectTypeService.queryAll(entity);
        ExcelUtil<FncSubjectTypeVo> util = new ExcelUtil<>(FncSubjectTypeVo.class);
        util.exportExcel(response, list, "科目类别数据");
    }

    @ApiOperation("获取科目类别详细信息")
    @PreAuthorize("@ss.hasPermi('finance:subjectType:query')")
    @GetMapping(value = "/getInfo/{subjectTypeId}")
    public AjaxResult getInfo(@PathVariable("subjectTypeId") Long subjectTypeId) {
        return AjaxResult.success("查询成功", fncSubjectTypeService.queryById(subjectTypeId));
    }

    @ApiOperation("新增科目类别")
    @PreAuthorize("@ss.hasPermi('finance:subjectType:add')")
    @Log(title = "科目类别", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody FncSubjectType entity) {
        return toAjax(fncSubjectTypeService.save(entity));
    }

    @ApiOperation("修改科目类别")
    @PreAuthorize("@ss.hasPermi('finance:subjectType:edit')")
    @Log(title = "科目类别", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody FncSubjectType entity) {
        return toAjax(fncSubjectTypeService.updateById(entity));
    }

    @ApiOperation("删除科目类别")
    @PreAuthorize("@ss.hasPermi('finance:subjectType:remove')")
    @Log(title = "科目类别", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{subjectTypeIds}")
    public AjaxResult remove(@PathVariable Long[] subjectTypeIds) {
        return toAjax(fncSubjectTypeService.removeByIds(Arrays.asList(subjectTypeIds)) ? 1 : 0);
    }
}
