/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.base.em.Constant;
import com.tofly.base.entity.App;
import com.tofly.base.entity.UserAscription;
import com.tofly.base.entity.dto.UserAscriptionDto;
import com.tofly.base.service.AppService;
import com.tofly.base.service.UserAscriptionService;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.common.oauth.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户归属管理
 *
 * @author fcl
 * @date Wed Mar 10 00:00:00 CST 2021
 */
@RestController
@AllArgsConstructor
@RequestMapping("/userAscription")
@Api(tags = "用户归属管理")
public class UserAscriptionController {

    private final UserAscriptionService userAscriptionService;

    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param userAscription
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public ResultRespone getAppPage(Page page, @ModelAttribute UserAscription userAscription) {
        return ResultRespone.success(userAscriptionService.page(page, Wrappers.query(userAscription)));
    }

    @GetMapping("/getUserAscriptionMap")
    @ApiOperation(value = "查询父子级关系归属Map")
    public ResultRespone getUserAscriptionMap(@ModelAttribute UserAscription userAscription) {
        List<UserAscription> list = userAscriptionService.list(Wrappers.query(userAscription));
        List<UserAscriptionDto> dtoList  = new ArrayList<>();
        if(null!=list && list.size()>0){
           // 父级分组
            Map<String, List<UserAscription>> collect = list.stream().collect(Collectors.groupingBy(UserAscription::getParentUserLonginName));
            collect.forEach((k,v)->{
                UserAscriptionDto dto = new UserAscriptionDto();
                dto.setParentUserLonginName(k);
                List<String> userNameList = new ArrayList<>();
                v.forEach(i->{
                    userNameList.add(i.getUserLonginName());
                });
                dto.setUserLonginNameList(userNameList);
                dtoList.add(dto);
            });
        }


        return ResultRespone.success(dtoList);
    }


    /**
     * 通过id查询
     *
     * @param id id
     * @return ResultRespone
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone getById(@PathVariable("id") Long id) {
        return ResultRespone.success(userAscriptionService.getById(id));
    }

    /**
     * 新增
     *
     * @param parentUserId
     * @param userIds
     * @return ResultRespone
     */
    @ApiOperation(value = "新增(可重复绑定)")
    @PostMapping("/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentUserId", value = "父级id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "userIds", value = "用户id,多个以,分隔", required = true, dataType = "String")
    })
    public ResultRespone save(Long parentUserId, String userIds) {
        List<Long> userIdList = Arrays.stream(userIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        userIdList.forEach(info -> {
            UserAscription userAscription = new UserAscription();
            userAscription.setParentUserId(parentUserId);
            userAscription.setUserId(info);
            userAscriptionService.save(userAscription);
        });
        return ResultRespone.success();
    }

    @ApiOperation(value = "通过父级id,用户id批量删除,绑定关系")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentUserId", value = "父级id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "userIds", value = "用户id,多个以,分隔", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByUserIds")
    public ResultRespone deleteByUserIds(Long parentUserId,String userIds) {
        List<Long> userIdList = Arrays.stream(userIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        // 查询当前该用户列表中是否存绑定关系 存在则删除
        List<UserAscription> list = userAscriptionService.list(new QueryWrapper<UserAscription>().lambda()
                .eq(UserAscription::getParentUserId,parentUserId)
                .in(UserAscription::getUserId, userIdList));
        if (null != list && list.size() > 0) {
            userAscriptionService.removeByIds(list.stream().map(UserAscription::getId).collect(Collectors.toList()));
        }
        return ResultRespone.success();
    }

    /**
     * 通过id批量删除
     *
     * @param ids id
     * @return ResultRespone
     */

    @ApiOperation(value = "通过ID批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds")
    public ResultRespone removeById(String ids) {
        return ResultRespone.success(userAscriptionService.removeByIds(Arrays.asList(ids.split(","))));
    }

}
