package com.pcloud.book.rightsSetting.facade;

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.dto.RightsSettingDto;
import com.pcloud.book.rightsSetting.dto.RightsSettingQueryDTO;
import com.pcloud.book.rightsSetting.dto.RightsSettingShowStateDTO;
import com.pcloud.book.rightsSetting.entity.RightsNowPic;
import com.pcloud.book.rightsSetting.entity.RightsNowPopup;
import com.pcloud.book.rightsSetting.entity.RightsSetting;
import com.pcloud.book.rightsSetting.entity.RightsSettingClassify;
import com.pcloud.book.rightsSetting.entity.RightsSettingItem;
import com.pcloud.common.dto.ResponseDto;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.permission.PermissionException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.SessionUtil;
import com.pcloud.common.utils.cookie.Cookie;
import com.pcloud.common.utils.nginx.NginxUtils;
import com.pcloud.common.utils.string.StringUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CookieValue;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.Min;
import java.util.List;

@RequestMapping("rightsSetting")
@RestController("rightsSettingFacede")
public class RightsSettingFacede {

    @Autowired
    private RightsSettingBiz rightsSettingBiz;

    @PostMapping("addRightsSetting")
    public ResponseDto<Long> addRightsSetting( @RequestHeader("token") String token,
            @RequestBody @Validated RightsSetting rightsSetting ) throws PermissionException {
        Map<String,Object> map = SessionUtil.getToken4Redis(token);
        Long agentId = (Long) map.get(SessionUtil.RAY_AGENT_ID);
        rightsSetting.setAgentId(agentId==null?0L:agentId);
        Long userId = (Long) map.get(SessionUtil.USER_ID);
        rightsSetting.setCreateUserId(userId);
        return new ResponseDto<Long>(rightsSettingBiz.addRightsSetting(rightsSetting));
    }

    @GetMapping("deleteRightsSetting")
    public ResponseDto<?> deleteRightsSetting( @RequestHeader("token") String token, @RequestParam("id") Long id ) throws PermissionException {
        SessionUtil.getToken4Redis(token);
        rightsSettingBiz.deleteRightsSetting(id);
        return new ResponseDto<>();
    }

    @PostMapping("updateRightsSetting")
    public ResponseDto<?> updateRightsSetting( @RequestHeader("token") String token,
            @RequestBody @Validated RightsSetting rightsSetting ) throws PermissionException {
        Map<String,Object> map = SessionUtil.getToken4Redis(token);
        Long userId = (Long) map.get(SessionUtil.USER_ID);
        rightsSetting.setUpdateUserId(userId);
        rightsSettingBiz.updateRightsSetting(rightsSetting);
        return new ResponseDto<>();
    }

    @GetMapping("getRightsSetting")
    public ResponseDto<RightsSetting> getRightsSetting(
            @RequestHeader("token") String token,
            @RequestParam("id") Long id ) throws PermissionException {
        SessionUtil.getToken4Redis(token);
        return new ResponseDto<RightsSetting>(rightsSettingBiz.getRightsSetting(id));
    }

    @GetMapping("listRightsSettingPage")
    public ResponseDto<PageBeanNew<RightsSettingDto>> listRightsSettingPage( @RequestHeader("token") String token,
                                                                             @RequestParam("currentPage") Integer currentPage,
                                                                             @RequestParam("numPerPage") Integer numPerPage,
                                                                             @RequestParam(value = "firstClassify", required = false) Long firstClassify,
                                                                             @RequestParam(value = "secondClassify", required = false) Long secondClassify,
                                                                             @RequestParam(value = "thirdClassify", required = false) Long thirdClassify,
                                                                             @RequestParam(value = "gradeLabelId", required = false) Long gradeLabelId,
                                                                             @RequestParam(value = "subjectLabelId", required = false) Long subjectLabelId, @RequestParam(value = "rightsSettingType", required = false, defaultValue = "1") Integer rightsSettingType,
                                                                             @RequestParam(value = "bookQuery", required = false) String bookQuery,
                                                                             @RequestParam(value = "volLabelId", required = false) Long volLabelId,
                                                                             @RequestParam(value = "verLabelId", required = false) Long verLabelId,
                                                                             @RequestParam(value = "agentId", required = false) Long agentId

    ) throws PermissionException {
        Map<String,Object> map = SessionUtil.getToken4Redis(token);
        if (null == agentId) {
           agentId = (Long) map.get(SessionUtil.RAY_AGENT_ID);
        }
        RightsSetting rightsSetting = new RightsSetting();
        rightsSetting.setFirstClassify(firstClassify);
        rightsSetting.setSecondClassify(secondClassify);
        rightsSetting.setGradeLabelId(gradeLabelId);
        rightsSetting.setSubjectLabelId(subjectLabelId);
        rightsSetting.setRightsSettingType(rightsSettingType);
        rightsSetting.setBookQuery(bookQuery);
        rightsSetting.setVolLabelId(volLabelId);
        rightsSetting.setAgentId(agentId);
        rightsSetting.setVerLabelId(verLabelId);
        rightsSetting.setThirdClassify(thirdClassify);
        return new ResponseDto<PageBeanNew<RightsSettingDto>>(rightsSettingBiz.listRightsSettingPage(currentPage, numPerPage, rightsSetting));
    }

    @ApiOperation("获取读者数量-每天自增")
    @GetMapping("getUserCount")
    public ResponseDto<Integer> getUserCount() {
        return new ResponseDto<>(rightsSettingBiz.getUserCount());
    }

    @ApiOperation("新增每周/长期权益")
    @PostMapping("addRightsSettingItem")
    public ResponseDto<?> addRightsSettingItem( @RequestBody List<RightsSettingItem> rightsSettingItems,
                                                @RequestParam("rightsSettingId") Long rightsSettingId, @RequestParam("rightsType") String rightsType ) {
        rightsSettingBiz.batchInsertRightsSettingItem(rightsSettingItems, rightsSettingId, rightsType);
        return new ResponseDto<>();
    }

    @ApiOperation("小程序首页权益基本信息查询")
    @GetMapping("getRightsSettingByBookId4AppletHome")
    public ResponseDto<?> getRightsSettingByBookId4AppletHome(
            @CookieValue("userInfo") String userInfo, @RequestParam("adviserId") Long adviserId,
            @RequestParam("bookId") Long bookId, @RequestParam("channelId") Long channelId ) {
        Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        if (null == adviserId || null == bookId || null == channelId) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数缺失！");
        }
        return new ResponseDto<>(rightsSettingBiz.getRightsSettingByBookId4AppletHome(bookId, adviserId, channelId));
    }

    @ApiOperation("小程序首页本周/长期权益查询")
    @GetMapping("getItemByRightsSettingId4AppletHome")
    public ResponseDto<?> getItemByRightsSettingId4AppletHome(
            @CookieValue("userInfo") String userInfo,
            @RequestParam("rightsSettingId") Long rightsSettingId,
            @RequestParam(value = "bookId", required = false) Long bookId,
            @RequestParam(value = "adviserId", required = false) Long adviserId,
            @RequestParam(value = "channelId", required = false) Long channelId,
            @RequestParam(value = "rightsType", required = false) String rightsType,
            @RequestParam(value = "readType",required = false)@ApiParam("阅读方式1轻松2高效3深度") Integer readType,
            @RequestParam(value = "currentPage",required = false) Integer currentPage,
            @RequestParam(value = "numPerPage",required = false) Integer numPerPage) {
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        Long officialAccountsId = Cookie.getId(userInfo, Cookie._OFFICIAL_ACCOUNTS_ID);
        if (null == rightsSettingId || StringUtil.isEmpty(rightsType)) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数缺失！");
        }
        return new ResponseDto<>(rightsSettingBiz.getItemByRightsSettingId4AppletHome(rightsSettingId, wechatUserId, rightsType, readType, bookId, adviserId, channelId, currentPage, numPerPage,officialAccountsId));
    }

    @ApiOperation("所有权益分类")
    @GetMapping("getAllRightsClassify")
    public ResponseDto<List<RightsSettingClassify>> getAllRightsClassify(
            @RequestParam(value = "rightsType", required = false) String rightsType ) {
        return new ResponseDto<>(rightsSettingBiz.getAllRightsClassify(rightsType));
    }

    @ApiOperation("根据权益id获取即享权益项")
    @GetMapping("getRightsSettingRightsNowItems")
    public ResponseDto<RightsSetting> getRightsSettingRightsNowItems(
            @CookieValue("userInfo") String userInfo,
            @RequestParam("rightsSettingId") Long rightsSettingId
    ) throws PermissionException {
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        if (null == rightsSettingId) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数缺失！");
        }
        return new ResponseDto<>(rightsSettingBiz.getRightsSettingRightsNowItems(rightsSettingId, wechatUserId));
    }

    @SneakyThrows
    @ApiOperation("根据权益id和类型获取即享权益项")
    @GetMapping("getRightsSettingRightsNowItemsByType")
    public ResponseDto<RightsSetting> getRightsSettingRightsNowItemsByType(@CookieValue("userInfo") String userInfo,
                                                                           @RequestParam("rightsSettingId") @Min(value = 1,
                                                                                   message = "权益id不能小于1") Long rightsSettingId,
                                                                           @RequestParam("rightsSettingType") @Min(value = 1,
                                                                                   message = "权益类型不能小于1") Integer rightsSettingType,
                                                                           @RequestParam(value = "adviserId", required = false) Long adviserId,
                                                                           @RequestParam(value = "bookId", required = false) Long bookId,
                                                                           @RequestParam(value = "channelId", required = false) Long channelId,
                                                                           @RequestParam(value = "readType", required = false) @ApiParam("阅读方式1轻松2高效3深度") Integer readType,
                                                                           @RequestParam(value = "numPerPage", required = false) Integer numPerPage,
                                                                           @RequestParam(value = "currentPage", required = false) Integer currentPage
    ) {
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        Long officialAccountsId = Cookie.getId(userInfo, Cookie._OFFICIAL_ACCOUNTS_ID);
        return new ResponseDto<>(rightsSettingBiz.getRightsSettingRightsNowItemsByType(rightsSettingId, wechatUserId, rightsSettingType, adviserId, bookId, channelId, readType, currentPage, numPerPage,officialAccountsId));
    }

    @ApiOperation("根据权益id获取即享权益项专享礼包")
    @GetMapping("getRightsSettingGiftCoupons")
    public ResponseDto<RightsSetting> getRightsSettingGiftCoupons(
            @CookieValue("userInfo") String userInfo,
            @RequestParam("rightsSettingId") Long rightsSettingId,
            @RequestParam(value = "readType",required = false)@ApiParam("阅读方式1轻松2高效3深度") Integer readType
    ) throws PermissionException {
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        if (null == rightsSettingId) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数缺失！");
        }
        return new ResponseDto<>(rightsSettingBiz.getRightsSettingGiftCoupons(rightsSettingId, wechatUserId, readType));
    }

    @ApiOperation("根据权益id获取即享权益项补充咨询")
    @GetMapping("getFillRightsSettingApplets")
    public ResponseDto<?> getFillRightsSettingApplets(
            @CookieValue("userInfo") String userInfo,
            @RequestParam("rightsSettingId") Long rightsSettingId
    ) throws PermissionException {
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        Long officialAccountsId = Cookie.getId(userInfo, Cookie._OFFICIAL_ACCOUNTS_ID);
        if (null == rightsSettingId) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数缺失！");
        }
        return new ResponseDto<>(rightsSettingBiz.getFillRightsSettingApplets(rightsSettingId, wechatUserId, null, null, null, officialAccountsId));
    }

    @ApiOperation("根据权益id获取即享权益配套资料分组集合")
    @GetMapping("getRightsItemGroups")
    public ResponseDto<?> getRightsItemGroups(
            @CookieValue("userInfo")String userInfo,
            @RequestParam("rightsSettingId") Long rightsSettingId,
            @RequestParam("adviserId") Long adviserId,
            @RequestParam("bookId")Long bookId,
            @RequestParam("channelId")Long channelId,
            @RequestParam(value = "readType",required = false)@ApiParam("阅读方式1轻松2高效3深度") Integer readType
    ) throws PermissionException {
        Long wechatUserId = Cookie.getId(userInfo,Cookie._WECHAT_USER_ID);
        if (null==rightsSettingId){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数缺失！");
        }
        return new ResponseDto<>(rightsSettingBiz.getRightsItemGroups(rightsSettingId, adviserId, bookId, channelId, true,readType, wechatUserId,false));
    }

    @ApiOperation("根据书刊的分类获取对应的分类权益信息")
    @GetMapping("getRightSettingByBookId")
    public ResponseDto<?> getRightSettingByBookId(
        @RequestHeader("token") String token,
        @RequestParam("bookId")Long bookId,
        @RequestParam("adviserId") Long adviserId,
        @RequestParam("channelId")Long channelId
    ) throws PermissionException {
        SessionUtil.getToken4Redis(token);
        return new ResponseDto<>(rightsSettingBiz.getRightSettingByBookId(bookId, adviserId, channelId));
    }

    @ApiOperation("获取即享权益默认图片库")
    @GetMapping("getAllDefaultRightsNowPics")
    public ResponseDto<?> getAllDefaultRightsNowPics(
            @RequestHeader("token") String token,
            @RequestParam(value = "type", required = false) @ApiParam("图片类型(1立享权益2资讯3书单4书刊分类)") Integer type
    ) throws PermissionException {
        SessionUtil.getToken4Redis(token);
        return new ResponseDto<>(rightsSettingBiz.getAllDefaultRightsNowPics(type));
    }

    @ApiOperation("新增即享权益图片")
    @PostMapping("addRightsNowPic")
    public ResponseDto<?> addRightsNowPic(
            @RequestHeader("token") String token,
            @RequestBody RightsNowPic rightsNowPic
    ) throws PermissionException {
        Map<String, Object> map = SessionUtil.getToken4Redis(token);
        Long agentId = (Long) map.get(SessionUtil.RAY_AGENT_ID);
        rightsNowPic.setAgentId(agentId);
        rightsSettingBiz.addRightsNowPic(rightsNowPic);
        return new ResponseDto<>();
    }

    @ApiOperation("获取即享权益图片列表")
    @GetMapping("getRightsNowPics")
    public ResponseDto<?> getRightsNowPics(
            @RequestHeader("token") String token,
            @RequestParam("currentPage") Integer currentPage,
            @RequestParam("numPerPage") Integer numPerPage,
            @RequestParam(value = "type", required = false) @ApiParam("图片类型(1立享权益2资讯3书单4书刊分类)") Integer type
    ) throws PermissionException {
        Map<String, Object> map = SessionUtil.getToken4Redis(token);
        Long agentId = (Long) map.get(SessionUtil.RAY_AGENT_ID);
        return new ResponseDto<>(rightsSettingBiz.getRightsNowPics(currentPage,numPerPage,type, agentId));
    }

    @ApiOperation("删除即享权益图片")
    @GetMapping("deleteRightsNowPic")
    public ResponseDto<?> deleteRightsNowPic(
            @RequestHeader("token") String token,
            @RequestParam("rightsNowPicId") Long rightsNowPicId
    ) throws PermissionException {
        SessionUtil.getToken4Redis(token);
        rightsSettingBiz.deleteRightsNowPic(rightsNowPicId);
        return new ResponseDto<>();
    }

    @ApiOperation("增加上下册分类权益")
    @PostMapping("copyRightsSetting")
    public ResponseDto<?> copyRightsSetting(@RequestBody List<Long> volLabelIds){
        rightsSettingBiz.copyRightsSetting(volLabelIds);
        return new ResponseDto<>();
    }

    @ApiOperation("获取当前图书的阅读方式")
    @GetMapping("getReadType4Book")
    public ResponseDto<RightsSettingDto> getReadType4Book(
            @CookieValue("userInfo") String userInfo,
            @RequestParam("bookId") Long bookId,
            @RequestParam("channelId") Long channelId,
            @RequestParam("adviserId") Long adviserId
    ) throws PermissionException {
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        RightsSettingDto rightsSettingDto = rightsSettingBiz.getReadType4Book(wechatUserId,bookId,channelId,adviserId);
        return new ResponseDto<>(rightsSettingDto);
    }

    @ApiOperation("批量上下架")
    @PostMapping("batchUpdateShowState")
    public ResponseDto<?> batchUpdateShowState(
            @RequestHeader("token") String token,
            @RequestBody RightsSettingShowStateDTO rightsSettingShowStateDTO) throws PermissionException {
        SessionUtil.getInfoToken4Redis(token);
        if (null == rightsSettingShowStateDTO || ListUtils.isEmpty(rightsSettingShowStateDTO.getRightsSettingIds()) || null == rightsSettingShowStateDTO.getShowState()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少参数");
        }
        rightsSettingBiz.batchUpdateShowState(rightsSettingShowStateDTO);
        return new ResponseDto<>();
    }

    @ApiOperation("要弹出的资源")
    @GetMapping("getPopupResourceInfoByBook")
    public ResponseDto<?> getPopupResourceInfoByBook(
            @CookieValue("userInfo") String userInfo,
            @RequestParam("bookId") Long bookId,
            @RequestParam("channelId")Long channelId,
            @RequestParam("adviserId")Long adviserId,
            @RequestParam(value = "rightsSettingId", required = false)Long rightsSettingId,
            @RequestParam(value = "readType", required = false) Integer readType){
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        return new ResponseDto<>(rightsSettingBiz.getPopupResourceInfoByBook(wechatUserId,bookId,channelId,adviserId,rightsSettingId,readType));
    }

    @ApiOperation("资源弹窗记录埋点")
    @PostMapping("addPopupRecord")
    public ResponseDto<?> addPopupRecord(@CookieValue("userInfo") String userInfo, @RequestBody @ApiParam RightsNowPopup rightsNowPopup){
        if (null == rightsNowPopup){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少参数");
        }
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        rightsNowPopup.setWechatUserId(wechatUserId);
        rightsSettingBiz.addPopupRecord(rightsNowPopup);
        return new ResponseDto<>();
    }

    @ApiOperation("答案引流资源和权益")
    @GetMapping("getResourceListByBook4Answer")
    public ResponseDto<?> getResourceListByBook4Answer(
            @CookieValue("userInfo") String userInfo,
            @RequestParam(value = "bookId", required = false) Long bookId,
            @RequestParam(value = "channelId", required = false)Long channelId,
            @RequestParam(value = "adviserId", required = false)Long adviserId,
            @RequestParam(value = "sceneId", required = false) Long sceneId){
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        return new ResponseDto<>(rightsSettingBiz.getResourceListByBook4Answer(wechatUserId,bookId,channelId,adviserId,sceneId));
    }

    @ApiOperation("根据权益id获取即享权益配套资料分组集合")
    @GetMapping("getRightsItemGroupsByBookGroup")
    public ResponseDto<?> getRightsItemGroupsByBookGroup(
            @CookieValue("userInfo")String userInfo,
            @RequestParam("bookGroupId") Long bookGroupId
    ) throws PermissionException {
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        if (null == bookGroupId) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数缺失！");
        }
        return new ResponseDto<>(rightsSettingBiz.getRightsItemGroupsByBookGroup(bookGroupId, wechatUserId));
    }

    @ApiOperation("平台端更新权益设置-新版")
    @PostMapping("updateRightsSettingNew")
    public ResponseDto<?> updateRightsSettingNew( @RequestHeader("token") String token,
                                               @RequestBody @Validated RightsSetting rightsSetting ) throws PermissionException {
        Map<String,Object> map = SessionUtil.getToken4Redis(token);
        Long userId = (Long) map.get(SessionUtil.USER_ID);
        rightsSetting.setUpdateUserId(userId);
        rightsSettingBiz.updateRightsSettingNew(rightsSetting);
        return new ResponseDto<>();
    }

    @ApiOperation("平台端根据id查权益-新版")
    @GetMapping("getRightsSettingNew")
    public ResponseDto<RightsSetting> getRightsSettingNew(
            @RequestHeader("token") String token,
            @RequestParam("id") Long id ) throws PermissionException {
        SessionUtil.getToken4Redis(token);
        return new ResponseDto<>(rightsSettingBiz.getRightsSettingNew(id));
    }

    @SneakyThrows
    @ApiOperation("获取即享权益项-新版")
    @PostMapping("getRightsSettingItemsByTypeListNew")
    public ResponseDto<RightsSetting> getRightsSettingItemsByTypeListNew(
            @CookieValue("userInfo") String userInfo, @RequestBody RightsSettingQueryDTO rightsSettingQueryDTO) {
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        rightsSettingQueryDTO.setWechatUserId(wechatUserId);
        return new ResponseDto<>(rightsSettingBiz.getRightsSettingItemsByTypeListNew(rightsSettingQueryDTO));
    }

    @ApiOperation("所有权益分类-新版")
    @GetMapping("getAllRightsClassifyNew")
    public ResponseDto<List<RightsSettingClassify>> getAllRightsClassifyNew() {
        return new ResponseDto<>(rightsSettingBiz.getAllRightsClassifyNew());
    }

    @ApiOperation("处理权益模块旧数据")
    @PostMapping("handleRightsSettingOld")
    public ResponseDto<?> handleRightsSettingOld(@RequestBody List<Long> rightsSettingIdList){
        rightsSettingBiz.handleRightsSettingOld(rightsSettingIdList);
        return new ResponseDto<>();
    }
}