package com.pcloud.book.group.service.impl;

import com.pcloud.book.group.biz.BookGroupAppBiz;
import com.pcloud.book.group.biz.BookGroupBiz;
import com.pcloud.book.group.dto.AltAndCountDTO;
import com.pcloud.book.group.dto.BookAppletSceneDTO;
import com.pcloud.book.group.dto.BookGroupCountDTO;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.BookGroupKeywordResourceDTO;
import com.pcloud.book.group.dto.BookGroupServeCountDTO;
import com.pcloud.book.group.dto.BookGroupServeDTO;
import com.pcloud.book.group.dto.ErpBookGroupDTO;
import com.pcloud.book.group.dto.ErpGroupQrcodeDTO;
import com.pcloud.book.group.dto.GroupCipherDTO;
import com.pcloud.book.group.dto.GroupUseDTO;
import com.pcloud.book.group.dto.MapBookGroupServeCountDTO;
import com.pcloud.book.group.dto.PersonalQrcodeDTO;
import com.pcloud.book.group.dto.QueryByBookAdviserDTO;
import com.pcloud.book.group.dto.ResourceBrowseParamDto;
import com.pcloud.book.group.dto.SelfRobotBookGroupDTO;
import com.pcloud.book.group.dto.SelfRobotUserDTO;
import com.pcloud.book.group.dto.SelfRobtParamDTO;
import com.pcloud.book.group.dto.UserBookBaseInfoDTO;
import com.pcloud.book.group.entity.BookGroupServe;
import com.pcloud.book.group.enums.JoinGroupTypeEnum;
import com.pcloud.book.group.service.BookGroupService;
import com.pcloud.common.dto.ResponseDto;
import com.pcloud.common.dto.StoreFlowInfoDto;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.utils.BeanUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ResponseHandleUtil;

import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtil;
import java.lang.reflect.InvocationTargetException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * Description 社群书内部接口实现类
 * Created by PENG on 2019/5/14.
 */
@RestController("bookGroupService")
@RequestMapping("bookGroupService")
public class BookGroupServiceImpl implements BookGroupService {

    @Autowired
    private BookGroupBiz bookGroupBiz;
    @Autowired
    private BookGroupAppBiz bookGroupAppBiz;

    /**
     * 获取社群书基本信息
     */
    @Override
    @RequestMapping(value = "getBookGroupInfo", method = RequestMethod.GET)
    public ResponseEntity<ResponseDto<BookGroupDTO>> getBookGroupInfo(@RequestParam("bookGroupId") Long bookGroupId) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getBookGroupInfo(bookGroupId));
    }

    /**
     * 批量获取社群书基本信息
     */
    @Override
    @RequestMapping(value = "getBookGroupInfoByIds", method = RequestMethod.POST)
    public ResponseEntity<ResponseDto<Map<Long, BookGroupDTO>>> getBookGroupInfoByIds(@RequestBody List<Long> bookGroupIds) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getBookGroupInfoByIds(bookGroupIds));
    }

    /**
     * 根据bookId和AdviserId批量获取社群书基本信息
     */
    @Override
    @PostMapping(value = "getBookGroupInfoByBookIdAndAdviserId")
    public ResponseEntity<ResponseDto<List<BookGroupDTO>>> getBookGroupInfoByBookIdAndAdviserId(@RequestBody QueryByBookAdviserDTO queryByBookAdviserDTO) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getBookGroupInfoByBookIdAndAdviserId(queryByBookAdviserDTO.getBookIds(),queryByBookAdviserDTO.getAdviserIds()));
    }

    /**
     * 为信息流批量获取社群书基本信息
     */
    @Override
    @RequestMapping(value = "getFlowInfoByBookGroupIds", method = RequestMethod.POST)
    public ResponseEntity<ResponseDto<Map<Long, StoreFlowInfoDto>>> getFlowInfoByBookGroupIds(@RequestBody List<Long> bookGroupIds) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getFlowInfoByBookGroupIds(bookGroupIds));
    }

    /**
     * 获取指定条数社群书基本信息
     */
    @Override
    @RequestMapping(value = "getBookGroupInfoByChannelId",method = RequestMethod.GET)
    public ResponseEntity<ResponseDto<Map<Long, StoreFlowInfoDto>>> getBookGroupInfoByChannelId(@RequestParam("channelId")Long channelId, @RequestParam("itemNum")Integer itemNum) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getBookGroupInfoByChannelId(channelId, itemNum));
    }

    /**
     * 知识商城获取社群书信息
     */
    @Override
    @RequestMapping(value = "listBookGroup4KnowledgeMall",method = RequestMethod.GET)
    public ResponseEntity<ResponseDto<PageBeanNew<StoreFlowInfoDto>>> listBookGroup4KnowledgeMall(@RequestParam(value="channelId",required = false)Long channelId,
                                                                                                  @RequestParam("currentPage")int currentPage,
                                                                                                  @RequestParam("numPerPage") int numPerPage) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.listBookGroup4KnowledgeMall(channelId, currentPage, numPerPage));
    }

    /**
     * 获取社群书基本信息
     */
    @Override
    @RequestMapping(value = "getBaseInfoBySceneId", method = RequestMethod.GET)
    public ResponseEntity<ResponseDto<BookGroupDTO>> getBaseInfoBySceneId(@RequestParam("sceneId") Long sceneId) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getBaseInfoBySceneId(sceneId));
    }

    /**
     * 获取暗号状态
     */
    @ApiOperation("获取暗号状态")
    @GetMapping("/getCipherState")
    @Override
    public ResponseEntity<ResponseDto<Integer>> getCipherState(String cipher) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getCipherState(cipher));
    }

    /**
     * 更新密码状态为已使用
     */
    @ApiOperation("更新暗号状态为已使用")
    @GetMapping("/updateCipherStateToUsed")
    @Override
    public void updateCipherStateToUsed(String cipher, String wxId) throws BizException {
        bookGroupBiz.updateCipherStateToUsed(cipher,wxId);
    }

    /**
     * 获取个人二维码方式群已使用和未使用数量
     */
    @ApiOperation("获取个人二维码方式群已使用和未使用数量")
    @PostMapping("/getGroupUse")
    @Override
    public ResponseEntity<ResponseDto<GroupUseDTO>> getGroupUse(@RequestBody List<String> altIds) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getGroupUse(altIds));
    }

    @Override
    @RequestMapping(value = "updatePersonQrcode",method = RequestMethod.POST)
    public void updatePersonQrcode(@RequestBody PersonalQrcodeDTO personalQrcodeDTO) throws BizException {
        bookGroupBiz.updatePersonQrcode(personalQrcodeDTO);
    }

    /**
    * @description 获取资源浏览数据
    * @author 戴兴
    * @date 2019/8/8 20:45
    */
    @Override
    @PostMapping("getResourcesBrowseCount")
    public ResponseEntity<ResponseDto<Map<Long, Long>>> getResourcesBrowseCount(@RequestBody ResourceBrowseParamDto resourceBrowseParamDto) {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getResourcesBrowseCount(resourceBrowseParamDto));
    }

    @ApiOperation("获取暗号基本信息")
    @GetMapping("/getJoinGroupCipher")
    @Override
    public ResponseEntity<ResponseDto<GroupCipherDTO>> getJoinGroupCipher(@RequestParam("cipher")String cipher) throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getJoinGroupCipher(cipher));
    }


    @GetMapping("getBookGroupFriendsCountByDay")
    public ResponseEntity<ResponseDto<Map<String, Integer>>> getBookGroupFriendsCountByDay(
            @RequestParam("bookGroupId") Long bookGroupId, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
        Map<String, Integer> map = bookGroupBiz.getBookGroupFriendsCountByDay(bookGroupId, startDate, endDate);
        return ResponseHandleUtil.toResponse(map);
    }

    @ApiOperation("将1v1旧数据的关键词全部都干掉，有应用或作品的挂在社群书配置资源里面")
    @GetMapping("dealSelfBookGroupKeywordToServer")
    @Override
    public void dealSelfBookGroupKeywordToServer() {
        bookGroupBiz.dealSelfBookGroupKeywordToServer();
    }

    @ApiOperation("补充1v1旧数据的暗号")
    @GetMapping("fillSelfBookGroupCipher")
    @Override
    public void fillSelfBookGroupCipher() {
        bookGroupBiz.fillSelfBookGroupCipher();
    }

    @ApiOperation("将之前的配置资源取的社群码运营更新为应用本身的运营")
    @GetMapping("dealBookGroupServerChannel")
    @Override
    public void dealBookGroupServerChannel() {
        bookGroupBiz.dealBookGroupServerChannel();
    }


    @Override
    @GetMapping("getKeyWordResourceByBookGroup")
    public ResponseEntity<ResponseDto<List<BookGroupKeywordResourceDTO>>> getKeyWordResourceByBookGroup(
            @RequestParam("bookGroupId") Long bookGroupId) {
        List<BookGroupKeywordResourceDTO> list = bookGroupBiz.getKeyWordResourceByBookGroup(bookGroupId);
        return ResponseHandleUtil.toResponse(list);
    }

    @Override
    @GetMapping("getQrcodeIdsByBookGroupId")
    public ResponseEntity<ResponseDto<List<Long>>> getQrcodeIdsByBookGroupId(@RequestParam("bookGroupId") Long bookGroupId) {
        List<Long> qrcodeIds = bookGroupBiz.getQrcodeIdsByBookGroupId(bookGroupId);
        return ResponseHandleUtil.toResponse(qrcodeIds);
    }

    @Override
    @GetMapping("getFriendIdsByBookGroupId")
    public ResponseEntity<ResponseDto<List<String>>> getFriendIdsByBookGroupId(@RequestParam("bookGroupId") Long bookGroupId) {
        List<String> userIds = bookGroupBiz.getFriendIdsByBookGroupId(bookGroupId);
        return ResponseHandleUtil.toResponse(userIds);
    }

    @Override
    @PostMapping("listPageFriendInfo")
    public ResponseEntity<ResponseDto<PageBeanNew<SelfRobotUserDTO>>> listPageFriendInfo(@RequestBody SelfRobtParamDTO selfRobtParamDTO) {
        if (null == selfRobtParamDTO || null == selfRobtParamDTO.getCurrentPage() || null == selfRobtParamDTO.getNumPerPage()) {
            return ResponseHandleUtil.toResponse(new PageBeanNew<>());
        }
        PageBeanNew<SelfRobotUserDTO> pageBeanNew = bookGroupBiz.listPageFriendInfo(selfRobtParamDTO);
        return ResponseHandleUtil.toResponse(pageBeanNew);
    }

    @ApiOperation("补充社群书的出版社id")
    @GetMapping("fillAgentIdForBookGroup")
    @Override
    public void fillAgentIdForBookGroup(){
        bookGroupBiz.fillAgentIdForBookGroup();
    }

    @ApiOperation("获取个人号累计加好友人数")
    @GetMapping("getAddFriendCount")
    @Override
    public ResponseEntity<ResponseDto<Integer>> getAddFriendCount() {
        Integer count = bookGroupBiz.getAddFriendCount();
        return ResponseHandleUtil.toResponse(count);
    }

    @ApiOperation("获取所有已建分类的1v1的社群码")
    @GetMapping("get1v1HasClassifyBookGroupIds")
    @Override
    public ResponseEntity<ResponseDto<List<Long>>> get1v1HasClassifyBookGroupIds(){
        List<Long> list = bookGroupBiz.get1v1HasClassifyBookGroupIds();
        return ResponseHandleUtil.toResponse(list);
    }

    @ApiOperation("根据小号批量获取服务社群书数量")
    @PostMapping("getBookGroupCountMapByAltIds")
    @Override
    public ResponseEntity<ResponseDto<Map<String,Integer>>> getBookGroupCountMapByAltIds(@RequestBody List<String> altIds){
        Map<String,Integer> map = bookGroupBiz.getBookGroupCountMapByAltIds(altIds);
        return ResponseHandleUtil.toResponse(map);
    }

    @ApiOperation("获取小号社群书数量")
    @PostMapping("getSerBookGroupCountByAltIds")
    @Override
    public ResponseEntity<ResponseDto<Integer>> getSerBookGroupCountByAltIds(@RequestBody List<String> altIds) {
        Integer count = bookGroupBiz.getSerBookGroupCountByAltIds(altIds);
        return ResponseHandleUtil.toResponse(count);
    }

    @ApiOperation("出版社关联的个人号以及个人号的社群书数量")
    @GetMapping("getAltAndCountDTOListByAgentId")
    @Override
    public ResponseEntity<ResponseDto<List<AltAndCountDTO>>> getAltAndCountDTOListByAgentId(@RequestParam("agentId") Long agentId) {
        List<AltAndCountDTO> list = bookGroupBiz.getAltAndCountDTOListByAgentId(agentId);
        return ResponseHandleUtil.toResponse(list);
    }

    @ApiOperation("上架所有的个人号配置资源")
    @GetMapping("dealBookGroupServeOldOnShelves")
    public void dealBookGroupServeOldOnShelves() {
        bookGroupBiz.dealBookGroupServeOldOnShelves();
    }

    @ApiOperation("补充社群书旧的作品应用到新的表")
    @GetMapping("addOldBookGroupAppToNew")
    @Override
    public void addOldBookGroupAppToNew() {
        bookGroupAppBiz.addOldBookGroupAppToNew();
    }

    @ApiOperation("根据类型获取社群书id集合")
    @GetMapping("getBookGroupIdsByJoinGroupType")
    @Override
    public ResponseEntity<ResponseDto<List<Long>>> getBookGroupIdsByJoinGroupType(@RequestParam("joinGroupType") Integer joinGroupType) {
        List<Long> bookGroupIds = bookGroupBiz.getBookGroupIdsByJoinGroupType(joinGroupType);
        return ResponseHandleUtil.toResponse(bookGroupIds);
    }

    @ApiOperation("查小号的好友id列表")
    @PostMapping("getFriendIdListByBookAndRobot")
    @Override
    public ResponseEntity<ResponseDto<List<String>>> getFriendIdListByBookAndRobot(@RequestParam("altId") String altId, @RequestBody @ApiParam List<Long> bookIds) {
        List<String> idList = bookGroupBiz.getFriendIdListByBookAndRobot(altId, bookIds);
        return ResponseHandleUtil.toResponse(idList);
    }

    @ApiOperation("1v1用户扫码书刊名称")
    @PostMapping("mapUserScanBook")
    @Override
    public ResponseEntity<ResponseDto<Map<String, List<UserBookBaseInfoDTO>>>> mapUserScanBook(@RequestParam("altId") String altId, @RequestBody @ApiParam List<String> wxUserIdList) {
        Map<String, List<UserBookBaseInfoDTO>> map = bookGroupBiz.mapUserScanBook(altId, wxUserIdList);
        return ResponseHandleUtil.toResponse(map);
    }

    @GetMapping("getAssocBookGroupByServeInfo")
    @ApiOperation("获取关联社群书数量和名字")
    @Override
    public ResponseEntity<ResponseDto<List<BookGroupDTO>>> getAssocBookGroupByServeInfo(
            @RequestParam("adviserId") Long adviserId,
            @RequestParam("serveId") Long serveId,
            @RequestParam("serveType") String serveType) {
        List<BookGroupDTO> bookGroupDTOList =bookGroupBiz.getAssocBookGroupByServeInfo(adviserId,serveId,serveType);
        return ResponseHandleUtil.toResponse(bookGroupDTOList);
    }

    @Override
    public ResponseEntity<ResponseDto<List<BookGroupCountDTO>>> getAssocBookGroupCount(@RequestBody List<BookGroupCountDTO> bookGroupCountDTOS) {
        if (ListUtils.isEmpty(bookGroupCountDTOS)){
            ResponseHandleUtil.toResponse(new ArrayList<>());
        }
        List<BookGroupCountDTO> dtos = bookGroupBiz.getAssocBookGroupCount(bookGroupCountDTOS);
        return ResponseHandleUtil.toResponse(dtos);
    }

    @Override
    @GetMapping("getLatestCipherBookGroup")
    public ResponseEntity<ResponseDto<Long>> getLatestCipherBookGroup(@RequestParam("altId") String altId, @RequestParam("wxUserId") String wxUserId) {
        Long bookGroupId = bookGroupBiz.getLatestCipherBookGroup(altId, wxUserId);
        return ResponseHandleUtil.toResponse(bookGroupId);
    }

    @PostMapping("createGroupQrcode4Erp")
    public ResponseEntity<ResponseDto<ErpBookGroupDTO>> createGroupQrcode4Erp(@RequestBody ErpGroupQrcodeDTO erpGroupQrcodeDTO) {
        return ResponseHandleUtil.toResponse(bookGroupBiz.createGroupQrcode4Erp(erpGroupQrcodeDTO));
    }

    @ApiOperation("根据用户和社群书id获取个人号信息")
    @GetMapping("getSelfRobotBookGroupInfoByUser")
    @Override
    public ResponseEntity<ResponseDto<SelfRobotBookGroupDTO>> getSelfRobotBookGroupInfoByUser(@RequestParam("wxUserId") String wxUserId, @RequestParam("bookGroupId") Long bookGroupId) {
        SelfRobotBookGroupDTO selfRobotBookGroupDTO = bookGroupBiz.getSelfRobotBookGroupInfoByUser(wxUserId, bookGroupId);
        return ResponseHandleUtil.toResponse(selfRobotBookGroupDTO);
    }

    @Override
    public void addUserCount4RightsSetting() {
        //每天增加读者数
        String key="BOOK:APPLET:RIGHTS_SETTING_USER_COUNT";
        String value = JedisClusterUtils.get(key);
        if (!StringUtil.isEmpty(value)){
            Integer count =Integer.valueOf(value)+new Random().nextInt(10)+20;
            JedisClusterUtils.set(key,count.toString(),36*3600);
        }
    }

    @ApiOperation("通过sceneId查询小程序相关信息")
    @GetMapping("getBookAppletBySceneId")
    @Override
    public ResponseEntity<ResponseDto<BookAppletSceneDTO>> getBookAppletBySceneId(@RequestParam("sceneId") Long sceneId){
        BookAppletSceneDTO bookAppletSceneDTO=bookGroupBiz.getBookAppletBySceneId(sceneId);
        return ResponseHandleUtil.toResponse(bookAppletSceneDTO);
    }


    @Override
    public ResponseEntity<ResponseDto<Long>> getBookGroupId4OldData(Long raysBookId)
        throws BizException {
        return ResponseHandleUtil.toResponse(bookGroupBiz.getBookGroupId4OldData(raysBookId));
    }

    @Override
    @PostMapping("mapBookGroupServeCount")
    public ResponseEntity<ResponseDto<Map<String, BookGroupServeCountDTO>>> mapBookGroupServeCount(@RequestBody MapBookGroupServeCountDTO mapBookGroupServeCountDTO) {
        return ResponseHandleUtil.toResponse(bookGroupBiz.mapBookGroupServeCount(mapBookGroupServeCountDTO.getAdviserIds(),mapBookGroupServeCountDTO.getBookIds(),mapBookGroupServeCountDTO.getChannelIds()));
    }

    @Override
    public ResponseEntity<ResponseDto<List<BookGroupServeDTO>>> getBookGroupServeList(@RequestParam("bookGroupId") Long bookGroupId){
        List<BookGroupServe> list =bookGroupBiz.getBookGroupServeList(bookGroupId);
        List<BookGroupServeDTO> newList = new ArrayList<BookGroupServeDTO>();
        if (!ListUtils.isEmpty(list)){
            list.forEach(item->{
                BookGroupServeDTO newItme = new BookGroupServeDTO();
                BeanUtils.copyProperties(item,newItme);
                newList.add(newItme);
            });
        }
        return ResponseHandleUtil.toResponse(newList);
    }

    @Override
    @GetMapping("getRayGroupQrcode4Website")
    public ResponseEntity<ResponseDto<String>>getRayGroupQrcode4Website(@RequestParam(value = "agentId", required = false) Long agentId){
        BookGroupDTO bookGroupDTO = bookGroupBiz.getMaxScanCountBookGroup(agentId, JoinGroupTypeEnum.XIAORUI.getCode());
        return ResponseHandleUtil.toResponse(bookGroupDTO==null?"":bookGroupDTO.getGroupQrcodeUrl());
    }
}
