package com.yonge.cooleshow.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.microsvc.toolkit.common.response.paging.PageInfo;
import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.microsvc.toolkit.common.response.template.R;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.ImGroup;
import com.yonge.cooleshow.biz.dal.entity.TenantGroup;
import com.yonge.cooleshow.biz.dal.service.ImGroupService;
import com.yonge.cooleshow.biz.dal.service.TenantGroupService;
import com.yonge.cooleshow.biz.dal.wrapper.TenantGroupWrapper;
import com.yonge.cooleshow.tenant.vo.TenantGroupVo;
import com.yonge.toolset.base.exception.BizException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Validated
@RestController
@RequestMapping("${app-config.url.admin:}/tenantGroup")
@Api(tags = "机构小组表")
public class TenantGroupController {

    @Autowired
    private TenantGroupService tenantGroupService;

    @Resource
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private ImGroupService imGroupService;

    @ApiOperation(value = "查询分页", notes = "机构小组表- 传入 TenantGroupWrapper.TenantGroupQuery")
    @PreAuthorize("@pcs.hasPermissions('tenantGroup/page', {'BACKEND'})")
    @PostMapping("/page")
    public R<PageInfo<TenantGroupWrapper.TenantGroup>> page(@RequestBody TenantGroupWrapper.TenantGroupQuery query) {
        return R.from(QueryInfo.pageInfo(tenantGroupService.selectPage(QueryInfo.getPage(query), query)));
    }

    @ApiOperation(value = "处理机构小组交接", notes = "处理机构小组交接")
    @PreAuthorize("@pcs.hasPermissions('tenantGroup/adjustTenantGroup', {'BACKEND'})")
    @PostMapping("/adjustTenantGroup")
    public R<Boolean> adjustTenantGroup(@RequestBody TenantGroupWrapper.AdjustTenantGroup adjustTenantGroup) {
        return R.from(tenantGroupService.adjustTenantGroup(adjustTenantGroup));
    }

    @ApiOperation(value = "详情", notes = "机构小组表-根据详情ID查询单条, 传入id")
    @GetMapping("/detail/{id}")
    @PreAuthorize("@pcs.hasPermissions('tenantGroup/detail')")
    public R<TenantGroupWrapper.TenantGroup> detail(@PathVariable("id") Long id) {
        TenantGroup wrapper = tenantGroupService.detail(id);
        if (wrapper == null) {
            return R.from(new TenantGroupWrapper.TenantGroup());
        }
        TenantGroupWrapper.TenantGroup group = TenantGroupWrapper.TenantGroup.from(JSON.toJSONString(wrapper));
        group.setImGroupExist(false);
        if (StringUtils.isNotEmpty(wrapper.getImGroupId())) {
            ImGroup imGroup = imGroupService.getById(wrapper.getImGroupId());
            if (imGroup != null) {
                group.setImGroupExist(true);
            }
        }
        List<TenantGroupWrapper.TenantGroupMember> members =
                tenantGroupService.queryGroupMember(wrapper.getTenantId(), id);
        List<Long> userIds = members.stream().map(TenantGroupWrapper.TenantGroupMember::getUserId)
                .collect(Collectors.toList());
        group.setUserIds(userIds);
        group.setGroupUserCount(members.size());
        group.setUserList(members);
        return R.from(group);
    }

    @ApiOperation(value = "新增", notes = "机构小组表- 传入 TenantGroupWrapper.TenantGroup")
    @PostMapping("/save")
    @PreAuthorize("@pcs.hasPermissions('tenantGroup/save')")
    public R<JSONObject> add(@Validated @RequestBody TenantGroupVo.TenantGroup tenantGroup) {
        Long tenantId = tenantGroup.getTenantId();
        if (tenantId == null) {
            throw new BizException("机构ID不能为空");
        }
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        TenantGroupWrapper.TenantGroup group = TenantGroupWrapper.TenantGroup.from(tenantGroup.jsonString());
        group.setCreateBy(sysUser.getId());
        // 新增数据
        tenantGroupService.add(group, tenantGroup.getImGroupCreate());

        return R.defaultR();
    }

    @ApiOperation(value = "修改", notes = "机构小组表- 传入 TenantGroupWrapper.TenantGroup")
    @PostMapping("/update")
    @PreAuthorize("@pcs.hasPermissions('tenantGroup/update')")
    public R<JSONObject> update(@Validated @RequestBody TenantGroupVo.TenantGroup tenantGroup) {
        // 更新数据
        tenantGroupService.update(TenantGroupWrapper.TenantGroup.from(tenantGroup.jsonString()), tenantGroup.getImGroupCreate());

        return R.defaultR();
    }

    @ApiOperation(value = "删除", notes = "机构小组表- 传入id")
    @PostMapping("/remove")
    @PreAuthorize("@pcs.hasPermissions('tenantGroup/remove')")
    public R<Boolean> remove(@RequestParam Long id) {

        return R.from(tenantGroupService.delete(id));
    }
}