package com.yonge.cooleshow.admin.controller;

import com.alibaba.fastjson.JSON;
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.admin.io.request.SysSuggestionVo;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.biz.dal.entity.SysSuggestionV2;
import com.yonge.cooleshow.biz.dal.entity.SysUser;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.SysSuggestionV2Service;
import com.yonge.cooleshow.biz.dal.service.SysUserService;
import com.yonge.cooleshow.biz.dal.wrapper.SysSuggestionWrapper;
import com.yonge.cooleshow.common.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
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.RequestHeader;
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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Validated
@RestController
@RequestMapping("${app-config.url.admin:}/sysSuggestionV2")
@Api(tags = "平台建议表")
public class SysSuggestionV2Controller extends BaseController {

    @Autowired
    private SysSuggestionV2Service sysSuggestionService;

    @Autowired
    private SysUserService sysUserService;

    @Resource
    private SysUserFeignService sysUserFeignService;


    /**
     * 查询单条
     *
     * @param id 详情ID
     * @return R<SysSuggestionVo.SysSuggestion>
     */
    @ApiOperation(value = "详情", notes = "传入id")
    @PreAuthorize("@pcs.hasPermissions('sysSuggestionV2/detail')")
    @GetMapping("/detail/{id}")
    public R<SysSuggestionWrapper.SysSuggestion> detail(@PathVariable("id") Long id) {

        // 建议详情
        SysSuggestionV2 wrapper = sysSuggestionService.detail(id);
        SysSuggestionWrapper.SysSuggestion suggestion =
                SysSuggestionWrapper.SysSuggestion.from(JSON.toJSONString(wrapper));
        if (wrapper != null && wrapper.getSuggestionTypeId() != null) {
            List<Long> userIdList = new ArrayList<>();
            userIdList.add(wrapper.getUserId());
            if (wrapper.getHandleBy() != null) {
                userIdList.add(wrapper.getHandleBy());
            }
            Map<Long, SysUser> userIdMap = sysUserService.getMapByIds(userIdList);
            suggestion.setNickname(userIdMap.getOrDefault(suggestion.getUserId(), new SysUser()).getUsername());
            suggestion.setHandleName(userIdMap.getOrDefault(suggestion.getHandleBy(), new SysUser()).getUsername());
        }

        return R.from(suggestion);
    }

    /**
     * 查询分页
     *
     * @param query SysSuggestionWrapper.SysSuggestionQuery
     * @return R<PageInfo < SysSuggestionWrapper.SysSuggestion>>
     */
    @ApiOperation(value = "查询分页", notes = "传入sysSuggestionSearch")
    @PreAuthorize("@pcs.hasPermissions('sysSuggestionV2/page')")
    @PostMapping("/page")
    public R<PageInfo<SysSuggestionWrapper.SysSuggestion>> page(@RequestBody SysSuggestionWrapper.SysSuggestionQuery query) {

        IPage<SysSuggestionWrapper.SysSuggestion> pages = sysSuggestionService.selectPage(QueryInfo.getPage(query), query);

        List<SysSuggestionWrapper.SysSuggestion> records = pages.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            List<Long> userIdList = records.stream()
                    .map(SysSuggestionWrapper.SysSuggestion::getUserId)
                    .filter(Objects::nonNull).distinct().collect(Collectors.toList());

            List<Long> handUserIdList = records.stream()
                    .map(SysSuggestionWrapper.SysSuggestion::getHandleBy)
                    .filter(Objects::nonNull).distinct().collect(Collectors.toList());
            if (!handUserIdList.isEmpty()) {
                userIdList.addAll(handUserIdList);
            }
            Map<Long, SysUser> userIdMap = sysUserService.getMapByIds(userIdList);

            records.forEach(next -> {
                next.setNickname(userIdMap.getOrDefault(next.getUserId(), new SysUser()).getUsername());
                next.setHandleName(userIdMap.getOrDefault(next.getHandleBy(), new SysUser()).getUsername());
            });
        }
        return R.from(QueryInfo.pageInfo(pages, records));
    }

    /**
     * 新增
     *
     * @param suggestion SysSuggestionVo.SysSuggestion
     * @return R<Boolean>
     */
    @ApiOperation(value = "新增", notes = "传入sysSuggestion")
    @PreAuthorize("@pcs.hasPermissions('sysSuggestionV2/save')")
    @PostMapping("/save")
    public R<Boolean> add(@Validated @RequestBody SysSuggestionVo.SysSuggestion suggestion,
                          @RequestHeader(name = "user-agent") String userAgent) {
        com.yonge.cooleshow.auth.api.entity.SysUser sysUser = sysUserFeignService.queryUserInfo();
        suggestion.setUserId(sysUser.getId());
        suggestion.setClientType(ClientEnum.SYSTEM);
        suggestion.setUserAgent(userAgent);

        return R.from(sysSuggestionService.add(JSON.parseObject(suggestion.jsonString(), SysSuggestionV2.class)));
    }

    /**
     * 修改
     *
     * @param suggestion SysSuggestionVo.SysSuggestion
     * @return R<Boolean>
     */
    @ApiOperation(value = "修改", notes = "传入sysSuggestion")
    @PreAuthorize("@pcs.hasPermissions('sysSuggestionV2/update')")
//	@PostMapping("/update")
    public R<Boolean> update(@Validated @RequestBody SysSuggestionVo.SysSuggestion suggestion) {

        return R.from(sysSuggestionService.update(JSON.parseObject(suggestion.jsonString(), SysSuggestionV2.class)));
    }

    /**
     * 删除
     *
     * @param id 详情ID
     * @return R<Boolean>
     */
    @ApiOperation(value = "删除", notes = "传入id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", dataType = "long")
    })
    @PreAuthorize("@pcs.hasPermissions('sysSuggestionV2/remove')")
    @PostMapping("/remove")
    public R<Boolean> remove(@RequestParam Long id) {

        return R.from(sysSuggestionService.removeById(id));
    }

    @ApiOperation(value = "修改", notes = "传入sysSuggestion")
    @PreAuthorize("@pcs.hasPermissions('sysSuggestionV2/handleSuggestion')")
    @PostMapping("/handleSuggestion")
    public R<Boolean> handleSuggestion(@Validated @RequestBody SysSuggestionWrapper.HandleSuggestion handleSuggestion) {
        com.yonge.cooleshow.auth.api.entity.SysUser sysUser = sysUserFeignService.queryUserInfo();
        handleSuggestion.setHandleBy(sysUser.getId());
        return R.from(sysSuggestionService.handleSuggestion(handleSuggestion));
    }

    @ApiOperation(value = "查询未处理的建议数量")
    @PreAuthorize("@pcs.hasPermissions('sysSuggestionV2/queryUnHandleNum')")
    @GetMapping("/queryUnHandleNum")
    public R<Integer> queryUnHandleNum() {
        Integer count = sysSuggestionService.lambdaQuery()
                .eq(SysSuggestionV2::getHandleStatus, false)
                .count();
        return R.from(count);
    }
}
