package com.pcloud.book.copyright.facade.impl;

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.copyright.biz.BookAuthCodeBiz;
import com.pcloud.book.copyright.biz.BookExportRecordBiz;
import com.pcloud.book.copyright.biz.BookSceneAuthBiz;
import com.pcloud.book.copyright.dto.BookAuthCodeDTO;
import com.pcloud.book.copyright.dto.BookExportRecordDTO;
import com.pcloud.book.copyright.dto.DeleteAuthCodeDTO;
import com.pcloud.book.copyright.entity.BookExportRecord;
import com.pcloud.book.copyright.facade.BookAuthCodeFacade;
import com.pcloud.book.copyright.vo.AuthOpenVO;
import com.pcloud.book.copyright.vo.CheckAppServeVO;
import com.pcloud.book.copyright.vo.CheckAuthCodeVO;
import com.pcloud.book.copyright.vo.CheckCodeParam;
import com.pcloud.book.copyright.vo.CheckIsAuthServeParam;
import com.pcloud.book.copyright.vo.CodeUseStatusVO;
import com.pcloud.book.copyright.vo.FileVO;
import com.pcloud.book.copyright.vo.GenerateCodeVO;
import com.pcloud.book.copyright.vo.ImportRecordVO;
import com.pcloud.book.copyright.vo.UseAuthCodeVO;
import com.pcloud.common.dto.ResponseDto;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
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 org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import io.swagger.annotations.ApiOperation;

/**
 * @author lily
 * @date 2018/11/29 16:59
 */
@RequestMapping("bookAuthCode")
@RestController("bookAuthCodeFacade")
public class BookAuthCodeFacadeImpl implements BookAuthCodeFacade {

    @Autowired
    private BookAuthCodeBiz bookAuthCodeBiz;

    @Autowired
    private BookExportRecordBiz bookExportRecordBiz;

    @Autowired
    private BookSceneAuthBiz bookSceneAuthBiz;

    @Override
    @RequestMapping(value = "checkCode", method = RequestMethod.POST)
    public ResponseDto<CodeUseStatusVO> checkCode(@CookieValue("userInfo") String userInfo, @RequestBody CheckCodeParam checkCodeParam) throws PermissionException, BizException {
        Long channelId = checkCodeParam.getChannelId();
        if(channelId == null){
            channelId = Cookie.getId(userInfo, Cookie._CHANNEL_ID);
        }
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        Integer codeUseStatus = bookAuthCodeBiz.checkCode(checkCodeParam, channelId, wechatUserId);
        CodeUseStatusVO codeUseStatusVO = new CodeUseStatusVO();
        codeUseStatusVO.setCodeUseStatus(codeUseStatus);
        return new ResponseDto<>(codeUseStatusVO);
    }

    @Override
    @PostMapping("checkServe")
    public ResponseDto<Boolean> checkServe(@CookieValue("userInfo") String userInfo, @RequestBody CheckIsAuthServeParam checkIsAuthServeParam) throws PermissionException, BizException {
        Long channelId = checkIsAuthServeParam.getChannelId();
        if(channelId == null){
            channelId = Cookie.getId(userInfo, Cookie._CHANNEL_ID);
        }
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        Boolean code = bookAuthCodeBiz.checkServe(checkIsAuthServeParam, channelId, wechatUserId);
        return new ResponseDto<>(code == null ? false : code);
    }

    @Override
    @PostMapping("importCode")
    public ResponseDto<?> importCode(@RequestHeader("token") String token, @RequestBody FileVO fileVO) throws PermissionException, BizException {
        Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        bookAuthCodeBiz.importCode(fileVO, adviserId);
        return  new ResponseDto<>();
    }

    @Override
    @GetMapping("importCodeRecord")
    public ResponseDto<PageBeanNew<ImportRecordVO>> importCodeRecord(@RequestHeader("token")String token, @RequestParam("bookId") Long bookId,
                                                                     @RequestParam("channelId") Long channelId, @RequestParam(value = "authBookType", required = false) Integer authBookType,
                                                                     @RequestParam("currentPage") Integer currenPage, @RequestParam("numPerPage") Integer numPerPage) throws PermissionException, BizException {
        Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        PageBeanNew<ImportRecordVO> pageBean = bookAuthCodeBiz.importCodeRecord(bookId, channelId, adviserId, authBookType, currenPage, numPerPage);
        return new ResponseDto<>(pageBean);
    }

    @Override
    @GetMapping("getCodeList")
    public ResponseDto<PageBeanNew<BookAuthCodeDTO>> getCodeList(@RequestHeader("token")String token,
                                                                 @RequestParam(required = false,value = "bookId") Long bookId,
                                                                 @RequestParam(required = false,value = "channelId")Long channelId,
                                                                 @RequestParam(required = false,value = "keyword")String keyword,
                                                                 @RequestParam(required = false,value = "state")Integer state,
                                                                 @RequestParam(required = false,value = "authBookType")Integer authBookType,
                                                                 @RequestParam(required = false,value = "currentPage")Integer currentPage,
                                                                 @RequestParam(required = false,value = "numPerPage")Integer numPerPage) throws PermissionException, BizException {
        Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        if(null == bookId || null == channelId){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        if(null == currentPage || null == numPerPage){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        PageParam pageParam = new PageParam(currentPage,numPerPage);
        return new ResponseDto<>(bookAuthCodeBiz.getCodeList(bookId,channelId,adviserId,keyword,state, authBookType, pageParam));
    }

    /**
     * 批量删除正版授权码
     * @param token
     * @param ids
     * @return
     * @throws PermissionException
     * @throws BizException
     */
    @Override
    public ResponseDto<PageBeanNew<BookAuthCodeDTO>> batchDeleteCode(@RequestHeader String token,
                                                                     @RequestBody List<Long> ids) throws PermissionException, BizException {
        if(ListUtils.isEmpty(ids)){
            return new ResponseDto<>();
        }
        bookAuthCodeBiz.batchDeleteCode(ids);
        return new ResponseDto<>();
    }

    @Override
    @RequestMapping(value = "/exportCode", method = RequestMethod.GET)
    public ResponseDto<?> exportCode(@RequestHeader("token") String token,
                                     @RequestParam(required = false, value ="bookId") Long bookId,
                                     @RequestParam(required = false, value ="codeIds") String codeIds,
                                     @RequestParam(required = false, value ="channelId") Long channelId,
                                     @RequestParam(required = false, value ="status") Long status,
                                     @RequestParam(required = false,value = "authBookType")Integer authBookType)
            throws PermissionException, JsonParseException, BizException {
        String systemCode = (String) SessionUtil.getVlaue(token, SessionUtil.SYSTEM_CODE);
        Long partyId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        //校验参数
        if (null == status || null == bookId || null == channelId) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数错误");
        }
        Map<String, Object> map = bookAuthCodeBiz.getCodeExcel(bookId,codeIds, channelId, status, systemCode, partyId, authBookType);
        return new ResponseDto<>(map);
    }

    /**
     *一键删除未使用的授权码
     */
    @PostMapping("deleteNoUsedAuthCode")
    public ResponseDto<?> deleteNoUsedAuthCode(@RequestHeader("token")String token,
                                                                 @RequestBody DeleteAuthCodeDTO deleteAuthCodeDTO) throws PermissionException, BizException {
        Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        if(null==deleteAuthCodeDTO || null == deleteAuthCodeDTO.getBookId() || null == deleteAuthCodeDTO.getChannelId()){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        bookAuthCodeBiz.deleteNoUsedAuthCode(deleteAuthCodeDTO,adviserId);
        return new ResponseDto<>();
    }

    /**
     * 查看授权码生成记录
     */
    @GetMapping("getGenerateCodeHistory")
    public ResponseDto<?> getGenerateCodeHistory(@RequestHeader("token")String token,
                                                 @RequestParam(required = false, value ="bookId") Long bookId,
                                                 @RequestParam(required = false, value ="channelId") Long channelId,
                                                 @RequestParam(required = false, value ="sceneId") Long sceneId,
                                                 @RequestParam(required = false,value = "currentPage")Integer currentPage,
                                                 @RequestParam(required = false,value = "numPerPage")Integer numPerPage) throws PermissionException, BizException {
        Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        PageParam pageParam = new PageParam(currentPage,numPerPage);
        PageBeanNew<BookExportRecordDTO> result=bookExportRecordBiz.getGenerateCodeHistory(bookId,adviserId,channelId,sceneId,pageParam);
        return new ResponseDto<>(result);
    }

    /**
     * 新版二维码自动生成版权保护二维码
     */
    @PostMapping("autoGenerateAuthCode")
    public ResponseDto<?> autoGenerateAuthCode(@RequestHeader("token") String token, @RequestBody GenerateCodeVO generateCodeVO) throws PermissionException, BizException {
        Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        bookSceneAuthBiz.autoGenerateAuthCode(generateCodeVO, adviserId);
        return new ResponseDto<>();
    }

    /**
     * 二维码下授权码列表
     */
    @GetMapping("listSceneAuthCode")
    public ResponseDto<?> listSceneAuthCode(@RequestHeader("token") String token,
                                            @RequestParam(required = false, value ="bookId") Long bookId,
                                            @RequestParam(required = false, value ="channelId") Long channelId,
                                            @RequestParam(required = false, value ="sceneId") Long sceneId,
                                            @RequestParam(required = false,value = "keyword")String keyword,
                                            @RequestParam(required = false,value = "state")Integer state,
                                            @RequestParam(required = false,value = "authBookType")Integer authBookType,
                                            @RequestParam(required = false,value = "currentPage")Integer currentPage,
                                            @RequestParam(required = false,value = "numPerPage")Integer numPerPage
                                            ) throws PermissionException, BizException {
        Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        PageBeanNew<BookAuthCodeDTO> result=bookSceneAuthBiz.listSceneAuthCode(bookId,channelId,sceneId,keyword,state,authBookType,currentPage,numPerPage, adviserId);
        return new ResponseDto<>(result);
    }

    /**
     * 批量删除正版授权码
     * @param token
     * @param ids
     * @return
     * @throws PermissionException
     * @throws BizException
     */
    @PostMapping("deleteSceneAuthCode")
    public ResponseDto<?> deleteSceneAuthCode(@RequestHeader String token,
                                              @RequestBody List<Long> ids) throws PermissionException, BizException {
        if(ListUtils.isEmpty(ids)){
            return new ResponseDto<>();
        }
        bookSceneAuthBiz.deleteSceneAuthCode(ids);
        return new ResponseDto<>();
    }

    /**
     *一键删除未使用的授权码
     */
    @PostMapping("clearNoUsedAuthCode")
    public ResponseDto<?> clearNoUsedAuthCode(@RequestHeader("token")String token,
                                               @RequestBody DeleteAuthCodeDTO deleteAuthCodeDTO) throws PermissionException, BizException {
        Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        if(null==deleteAuthCodeDTO || null == deleteAuthCodeDTO.getBookId() || null == deleteAuthCodeDTO.getChannelId() || null==deleteAuthCodeDTO.getSceneId()){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        bookSceneAuthBiz.clearNoUsedAuthCode(deleteAuthCodeDTO,adviserId);
        return new ResponseDto<>();
    }

    /**
     *  升级用户扫描授权码之后
     */
    @PostMapping("checkSceneAuthCode")
    public ResponseDto<?> checkSceneAuthCode(@CookieValue("userInfo") String userInfo, @RequestBody UseAuthCodeVO useAuthCodeVO) throws PermissionException, BizException {
        if(null==userInfo || null==useAuthCodeVO.getAuthCode()){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        Long channelId = useAuthCodeVO.getChannelId();
        if(channelId == null){
            channelId = Cookie.getId(userInfo, Cookie._CHANNEL_ID);
        }
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        CheckAuthCodeVO codeUseStatus = bookSceneAuthBiz.checkSceneAuthCode(useAuthCodeVO, channelId, wechatUserId);
        return new ResponseDto<>(codeUseStatus);
    }

    /**
     *  导出选中授权码
     */
    @RequestMapping(value = "/exportSceneAuthCode", method = RequestMethod.GET)
    public ResponseDto<?> exportSceneAuthCode(@RequestHeader("token") String token,
                                     @RequestParam(required = false, value ="bookId") Long bookId,
                                     @RequestParam(required = false, value ="codeIds") String codeIds,
                                     @RequestParam(required = false, value ="channelId") Long channelId,
                                     @RequestParam(required = false, value ="sceneId") Long sceneId,
                                     @RequestParam(required = false, value ="status") Long status,
                                     @RequestParam(required = false,value = "authBookType")Integer authBookType)
            throws PermissionException, JsonParseException, BizException {
        String systemCode = (String) SessionUtil.getVlaue(token, SessionUtil.SYSTEM_CODE);
        Long partyId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
        //校验参数
        if (null == status || null == bookId || null == channelId) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数错误");
        }
        Map<String, Object> map = bookSceneAuthBiz.exportSceneAuthCode(bookId,codeIds, channelId,sceneId, status, systemCode, partyId, authBookType);
        return new ResponseDto<>(map);
    }

    /**
     *  扫应用里面单个资源码也要版权保护
     */
    @RequestMapping(value = "/checkAppServe", method = RequestMethod.POST)
    public ResponseDto<?> checkAppServe(@CookieValue("userInfo") String userInfo, @RequestBody CheckIsAuthServeParam checkIsAuthServeParam)
            throws PermissionException, JsonParseException, BizException {
        Long channelId = checkIsAuthServeParam.getChannelId();
        if(channelId == null){
            channelId = Cookie.getId(userInfo, Cookie._CHANNEL_ID);
        }
        Long wechatUserId = Cookie.getId(userInfo, Cookie._WECHAT_USER_ID);
        CheckAppServeVO result = bookAuthCodeBiz.checkAppServe(checkIsAuthServeParam, channelId, wechatUserId);
        return new ResponseDto<>(result);
    }

    @ApiOperation("清空授权码使用用户")
    @GetMapping("clearAuthCodeUser")
    public ResponseDto<?> clearAuthCodeUser(@RequestParam("adviserId") Long adviserId,@RequestParam("bookId") Long bookId, @RequestParam("fullCode") String fullCode) {
        bookAuthCodeBiz.clearAuthCodeUser(adviserId,fullCode,bookId);
        return new ResponseDto<>();
    }
}
