package com.tofly.feesapi.yhgl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tofly.feesapi.common.core.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.common.core.dto.PageDto;
import com.tofly.feesapi.common.core.vo.PageResult;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;

import com.tofly.feesapi.security.util.SecurityUtils;
import com.tofly.feesapi.yhgl.entity.YhGroup;
import com.tofly.feesapi.yhgl.entity.YhGroupAccounts;
import com.tofly.feesapi.yhgl.entity.dto.YhGroupFilter;
import com.tofly.feesapi.yhgl.entity.vo.YhGroupSelect;
import com.tofly.feesapi.yhgl.service.YhGroupAccountsService;
import com.tofly.feesapi.yhgl.service.YhGroupService;
import lombok.AllArgsConstructor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/yhgroup")
@Api(tags = "用户群主账户管理接口")
public class YhGroupController {

    @Autowired
    private YhGroupService yhGroupService;
    @Autowired
    private YhGroupAccountsService yhGroupAccountsService;

    @GetMapping("/page")
    @ApiOperation(value = "分页查询", tags = "档案管理")
    public ResultRespone<PageResult<YhGroupSelect>> getPage(@ModelAttribute PageDto pageDto, @ModelAttribute YhGroupFilter filter) {
        return ResultRespone.success(yhGroupService.getPage(pageDto, filter));
    }

    @GetMapping("/getGroupYhbh")
    @ApiOperation(value = "获取群主户号", tags = "档案管理")
    public ResultRespone getGroupYhbh(String yhbh) {
        List<YhGroup> yhGroupList = yhGroupService.list();
        int count = yhGroupList.stream().filter(yhGroup -> yhGroup.getYhbh().equals(yhbh)).collect(Collectors.toList()).size();
        if (count > 0) {
            return ResultRespone.success(yhbh);
        } else {
            List<YhGroupAccounts> yhGroupAccountsList = yhGroupAccountsService.lambdaQuery()
                    .eq(YhGroupAccounts::getYhbh, yhbh)
                    .list();
            if (yhGroupAccountsList.size() > 0) {
                YhGroupAccounts yhGroupAccount = yhGroupAccountsList.get(0);
                String yhGroupyhbh = yhGroupList.stream().filter(item -> item.getId().equals(yhGroupAccount.getGroupId()))
                        .map(YhGroup::getYhbh).findFirst().orElse("");
                if (StringUtil.isNotEmpty(yhGroupyhbh)) {
                    return ResultRespone.success(yhGroupyhbh);
                }
            }
            return ResultRespone.failed("该用户编号不存群主户关系！");
        }
    }

    @ApiOperation(value = "新增用户群主账户管理", tags = "档案管理")
    @PostMapping
    @Transactional
    public ResultRespone save(@RequestBody YhGroup yhGroup) {
        if (StringUtil.isEmpty(yhGroup.getYhbh())) {
            throw new FeesException("用户编号不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(yhGroup.getIsdisabled())) {
            throw new FeesException("是否启用不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        long count = yhGroupService.count(
                new QueryWrapper<YhGroup>()
                        .lambda()
                        .eq(YhGroup::getYhbh, yhGroup.getYhbh())
        );
        if (count > 0) {
            throw new FeesException("该用户编号已添加为群主账户", FeesErrorCode.BUSINESS_ERROR);
        }
        yhGroup.setCzry(SecurityUtils.getUserId().toString());
        yhGroup.setCzrymc(SecurityUtils.getUser().getRealName());
        yhGroup.setCzsj(new Date());
        yhGroup.setId(yhGroupService.getMaxid());
        if (yhGroupService.save(yhGroup)) {
            YhGroupAccounts yhGroupAccount = new YhGroupAccounts();
            yhGroupAccount.setId(yhGroupAccountsService.getMaxid());
            yhGroupAccount.setGroupId(yhGroup.getId());
            yhGroupAccount.setYhbh(yhGroup.getYhbh());
            yhGroupAccount.setCzry(yhGroup.getCzry());
            yhGroupAccount.setCzrymc(yhGroup.getCzrymc());
            yhGroupAccount.setCzsj(new Date());
            return ResultRespone.success(yhGroupAccountsService.save(yhGroupAccount));
        }
        return ResultRespone.failed("添加失败");
    }

    @ApiOperation(value = "通过ID删除用户群主账户管理", tags = "档案管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String")
    })
    @DeleteMapping("/{id}")
    public ResultRespone removeById(@PathVariable String id) {
        long count = yhGroupAccountsService.count(
                new QueryWrapper<YhGroupAccounts>()
                        .lambda().eq(YhGroupAccounts::getGroupId, id)
        );
        if (count > 0) {
            throw new FeesException("该用户群主账户下有用户，不能删除", FeesErrorCode.BUSINESS_ERROR);
        }
        return ResultRespone.success(yhGroupService.removeById(id));
    }

    @ApiOperation(value = "通过ID批量删除用户群主账户管理", tags = "档案管理")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds")
    public ResultRespone removeByIds(String ids) {
        long count = yhGroupAccountsService.count(
                new QueryWrapper<YhGroupAccounts>()
                        .lambda().in(YhGroupAccounts::getGroupId, Arrays.stream(ids.split(",")))
        );
        if (count > 0) {
            throw new FeesException("存在用户群主账户下有用户，不能删除", FeesErrorCode.BUSINESS_ERROR);
        }
        return ResultRespone.success(yhGroupService.removeByIds(Arrays.asList(ids.split(","))));
    }

}
