package com.huimv.eartag2.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huimv.eartag2.admin.entity.AccountGroup;
import com.huimv.eartag2.admin.entity.Group;
import com.huimv.eartag2.admin.service.IAccountGroupService;
import com.huimv.eartag2.admin.service.IGroupService;
import com.huimv.eartag2.admin.service.ISysAccountMultilevelService;
import com.huimv.eartag2.common.common.token.TokenSign;
import com.huimv.eartag2.common.utils.Result;
import com.huimv.eartag2.common.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/group")
public class SysGroupController {

    @Autowired
    private IGroupService groupService;

    @Autowired
    private IAccountGroupService accountGroupService;
    @Autowired
    private ISysAccountMultilevelService accountMultilevelService;

    @PostMapping("/add")
    public Result addGroup (@RequestBody Group group, HttpServletRequest request){
        Integer userId = TokenSign.getMemberIdByJwtToken(request);
        return groupService.addGroup(group,userId);
    }


    @PostMapping("/edit")
    public Result updateGroup(@RequestBody Group group ){
        return groupService.updateGroup( group);
    }

    @RequestMapping("/remove")
    public Result removeGroup(@RequestParam("groupId") Integer groupId) {

        accountGroupService.remove(new QueryWrapper<AccountGroup>().in("group_id",groupId));
        return groupService.removeGroup(groupId);
    }

    @PostMapping("/list")
    public Result listGroup(@RequestBody Map map , HttpServletRequest request) {
        String orgId = TokenSign.getOrgId(request);
        Integer userId = TokenSign.getMemberIdByJwtToken(request);

        List<Integer> allChildId = accountMultilevelService.getAllChildId(orgId);
        allChildId.add(userId);
        return new Result(ResultCode.SUCCESS,groupService.listGroup(map,allChildId));
    }

    public IPage<Group> listGroup_old(@RequestBody Map map , HttpServletRequest request) {
        String orgId = TokenSign.getOrgId(request);
        Integer userId = TokenSign.getMemberIdByJwtToken(request);

        List<Integer> allChildId = accountMultilevelService.getAllChildId(orgId);
        allChildId.add(userId);
        return groupService.listGroup(map,allChildId);
    }
}
