/**
 * 
 */
package com.pcloud.book.book.facade.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.pcloud.book.base.dto.CountDto;
import com.pcloud.book.book.biz.BookAdviserBiz;
import com.pcloud.book.book.dto.AdviserManageDto;
import com.pcloud.book.book.dto.BookAdviserDto;
import com.pcloud.book.book.dto.BookCountDto;
import com.pcloud.book.book.dto.BookDataStatisticsDTO;
import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.book.dto.BookQrcodeStatisticsDTO;
import com.pcloud.book.book.dto.BookResourceStatisticsDTO;
import com.pcloud.book.book.dto.MapResourceTotalCountDTO;
import com.pcloud.book.book.dto.QrcodeStatisticsDTO;
import com.pcloud.book.book.entity.BookAdviser;
import com.pcloud.book.book.facade.BookAdviserFacade;
import com.pcloud.book.book.vo.AgentBookStatsDetailVO;
import com.pcloud.book.book.vo.PcloudAdviserBookVO;
import com.pcloud.book.book.vo.QrCodeVO;
import com.pcloud.common.dto.ResponseDto;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.permission.PermissionException;
import com.pcloud.common.utils.ParamChecker;
import com.pcloud.common.utils.SessionUtil;
import com.pcloud.common.utils.cookie.Cookie;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @描述：顾问书籍管理接口实现类
 * @作者：songx
 * @创建时间：2016年12月30日,下午6:03:13 @版本：1.0
 */
@RequestMapping("/bookAdviser")
@RestController("bookAdviserFacade")
public class BookAdviserFacadeImpl implements BookAdviserFacade {

	@Autowired
	private BookAdviserBiz bookAdviserBiz;

	/**
	 * 创建顾问和书籍的联系
	 */
	@Override
	@RequestMapping(value = "create", method = RequestMethod.POST)
	public ResponseDto<BookAdviserDto> create(@RequestHeader("token") String token,
			@RequestBody BookAdviser bookAdviser) throws BizException, PermissionException, JsonParseException {
		Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
		bookAdviser.setAdviserId(adviserId);
		bookAdviserBiz.create(bookAdviser);

		BookAdviserDto bookAdviserDto = new BookAdviserDto();
		bookAdviserDto.setBookAdviserId(bookAdviser.getBookAdviserId());
		return new ResponseDto<>(bookAdviserDto);
	}

	/**
	 * 编辑管理--获取编辑列表（平台端）
	 */
	@Override
	@RequestMapping(value = "listAdviser", method = RequestMethod.GET)
	public ResponseDto<?> getAdviserList(@RequestHeader("token") String token,
			@RequestParam(value = "bookId", required = false) Long bookId)
			throws BizException, PermissionException, JsonParseException {
		SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
		List<AdviserManageDto> adviserManageDtos = bookAdviserBiz.getAdviserList(bookId);
		return new ResponseDto<List<AdviserManageDto>>(
				adviserManageDtos == null ? new ArrayList<>() : adviserManageDtos);
	}

	/**
	 * 编辑管理--删除副编辑
	 */
	@Override
	@RequestMapping(value = "batDelViceAdviser", method = RequestMethod.POST)
	public ResponseDto<?> delViceAdviser(@RequestHeader("token") String token,
			@RequestBody List<BookAdviser> bookAdvisers) throws BizException, PermissionException, JsonParseException {
		SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
		bookAdviserBiz.delViceAdviser(bookAdvisers);
		return new ResponseDto<>();
	}

	/**
	 * 编辑 - 是否有默认Ray纸书
	 */
	@Override
	@RequestMapping(value = "getDefaultBook", method = RequestMethod.GET)
	public ResponseDto<?> getDefaultBook(@RequestHeader("token") String token,
			@RequestParam(value = "channelId", required = false) Long channelId)
			throws BizException, PermissionException, JsonParseException {
		Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
		BookAdviserDto bookAdviserDto = bookAdviserBiz.getDefaultBook(channelId, adviserId);
		return new ResponseDto<>(bookAdviserDto == null ? new BookAdviserDto() : bookAdviserDto);
	}

	/**
	 * 出版社下编辑的所有书刊的数目
	 * 
	 * @param token
	 * @return
	 * @throws BizException
	 * @throws PermissionException
	 * @throws JsonParseException
	 */
	@Override
	@RequestMapping(value = "getBookCount", method = RequestMethod.GET)
	public ResponseDto<CountDto> getBookCount(@RequestHeader("token") String token)
			throws BizException, PermissionException, JsonParseException {
		Long agentId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
		Integer bookCount = bookAdviserBiz.getBookCount(agentId);
		CountDto count = new CountDto();
		count.setCount(bookCount);
		return new ResponseDto<>(count);
	}

	/**
	 * 每日新增书刊数-出版
	 */
	@Override
	@RequestMapping(value = "listBookCountByDate4Agent", method = RequestMethod.GET)
	public ResponseDto<List<BookCountDto>> listBookCountByDate4Agent(@RequestHeader("token") String token)
			throws BizException, PermissionException, JsonParseException {
		Long agentId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
		List<BookCountDto> booksCount = bookAdviserBiz.listBookCountByDate4Agent(agentId);
		return new ResponseDto<>(booksCount == null ? new ArrayList<>() : booksCount);
	}

	/**
	 * 删除书籍（编辑端）
	 */
	@Override
	@RequestMapping(value = "deleteBook4Adviser", method = RequestMethod.GET)
	public ResponseDto<?> deleteBook4Adviser(@RequestHeader("token") String token,
			@RequestParam("bookId") Long bookId,
			@RequestParam("channelId") Long channelId)
			throws BizException, PermissionException, JsonParseException {
		Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
		bookAdviserBiz.deleteBook4Adviser(bookId, adviserId, channelId);
		return new ResponseDto<>();
	}

	/**
	 * 恢复书籍-编辑
	 */
	@Override
	@RequestMapping(value = "recoverBook4Adviser", method = RequestMethod.GET)
	public ResponseDto<?> recoverBook4Adviser(@RequestHeader("token") String token,
			@RequestParam(value = "bookId", required = false) Long bookId,
			@RequestParam(value = "channelId", required = false) Long channelId)
			throws BizException, PermissionException, JsonParseException {
		Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
		bookAdviserBiz.recoverBook4Adviser(bookId, adviserId, channelId, null,null, null, null, null, null, true, null);
		return new ResponseDto<>();
	}
	
	/**
	 * 获取编辑的图书总数
	 */
	@Override
	@RequestMapping(value = "getAdviserBookCount", method = RequestMethod.GET)
	public ResponseDto<CountDto> getAdviserBookCount(@RequestHeader("token") String token)
			throws PermissionException, JsonParseException, BizException {
		Long adviserId = (Long) SessionUtil.getVlaue(token, SessionUtil.PARTY_ID);
		CountDto countDto = bookAdviserBiz.getAdviserBookCount(adviserId);
		return new ResponseDto<>(countDto);
	}

	/**
	 * 获取编辑书刊列表(ERP项目用)
	 */
	@Override
	@RequestMapping(value = "listAdviserBook4Erp", method = RequestMethod.GET)
	public ResponseDto<?> listAdviserBook4Erp(@RequestHeader("token") String token,
											  @RequestParam(value = "isbn", required = false) String isbn,
											  @RequestParam(value = "uniqueNumber", required = false) String uniqueNumber,
											  @RequestParam(value = "adviserName", required = false) String adviserName,
											  @RequestParam(value = "agentId", required = false) Long agentId,
											  @RequestParam(value = "currentPage") Integer currentPage,
											  @RequestParam(value = "numPerPage") Integer numPerPage)
			throws PermissionException, JsonParseException, BizException {
		return new ResponseDto<>(bookAdviserBiz.listAdviserBook4Erp(isbn, uniqueNumber, adviserName, agentId, currentPage, numPerPage));
	}

	/**
	 * 导出编辑书刊列表(ERP项目用)
	 */
	@RequestMapping(value = "exportAdviserBook4Erp", method = RequestMethod.GET)
	public ResponseDto<?> exportAdviserBook4Erp(@RequestHeader("token") String token,
											  @RequestParam(value = "isbn", required = false) String isbn,
											  @RequestParam(value = "uniqueNumber", required = false) String uniqueNumber,
											  @RequestParam(value = "adviserName", required = false) String adviserName,
											  @RequestParam(value = "agentId", required = false) Long agentId)
			throws PermissionException, JsonParseException, BizException {
		return new ResponseDto<>(bookAdviserBiz.exportAdviserBook4Erp(isbn, uniqueNumber, adviserName, agentId));
	}

	@Override
	@RequestMapping(value = "listAdviserBook4Pcloud", method = RequestMethod.GET)
	public ResponseDto<PageBeanNew<PcloudAdviserBookVO>> listAdviserBook4Pcloud(@RequestHeader("token") String token,
																   @RequestParam(value = "keyword", required = false) String keyword,
																   @RequestParam(value = "currentPage") Integer currentPage,
																   @RequestParam(value = "numPerPage") Integer numPerPage)
			throws PermissionException, JsonParseException, BizException {
		return new ResponseDto<>(bookAdviserBiz.listAdviserBook4Pcloud(keyword, currentPage, numPerPage));
	}

	/**
     * 设置书刊是否已下印状态
     */
    @Override
    @RequestMapping(value = "setIsPrint", method = RequestMethod.POST)
    public ResponseDto<?> setIsPrint(@RequestHeader("token") String token,
            @RequestBody BookAdviser bookAdviser) throws BizException, PermissionException, JsonParseException {
        SessionUtil.getToken4Redis(token);
        bookAdviserBiz.setIsPrint(bookAdviser);
        return new ResponseDto<>();
    }

	/**
	 * 获取某本书关联的二维码列表
	 */
	@RequestMapping(value = "getQrList", method = RequestMethod.GET)
	public ResponseDto<PageBeanNew<QrCodeVO>> getQrList(@RequestParam(value = "bookId") Long bookId,
														@RequestParam(value = "adviserId") Long adviserId,
														@RequestParam(value = "channelId") Long channelId,
														@RequestParam(value = "currentPage") Integer currentPage,
														@RequestParam(value = "numPerPage") Integer numPerPage) throws BizException {
		PageBeanNew<QrCodeVO> qrCodeVOPageBeanNew = bookAdviserBiz.getQrList(bookId, adviserId, channelId, currentPage, numPerPage);
		return new ResponseDto<>(qrCodeVOPageBeanNew);
	}

	@Override
	@PostMapping("mapResourceTotalCount")
	public ResponseDto<Map<String, BookResourceStatisticsDTO>> mapResourceTotalCount(@RequestBody MapResourceTotalCountDTO mapResourceTotalCountDTO) {
		return new ResponseDto<>(bookAdviserBiz.mapResourceTotalCount(mapResourceTotalCountDTO.getAdviserIds(), mapResourceTotalCountDTO.getBookIds(), mapResourceTotalCountDTO.getChannelIds()));
	}

	@Override
	public ResponseDto<Map<String, BookDataStatisticsDTO>> mapBookDataStatistics(@RequestBody MapResourceTotalCountDTO mapResourceTotalCountDTO) {
		return new ResponseDto<>(bookAdviserBiz.mapBookDataStatistics(mapResourceTotalCountDTO.getAdviserIds(), mapResourceTotalCountDTO.getBookIds(), mapResourceTotalCountDTO.getChannelIds()));
	}

	@Override
	public ResponseDto<Map<String, BookQrcodeStatisticsDTO>> mapBookQrcodeStatistics(@RequestBody MapResourceTotalCountDTO mapResourceTotalCountDTO){
		return new ResponseDto<>(bookAdviserBiz.mapBookQrcodeStatistics(mapResourceTotalCountDTO.getAdviserIds(), mapResourceTotalCountDTO.getBookIds(), mapResourceTotalCountDTO.getChannelIds()));
	}

	@ApiModelProperty("分页获取疑似未印刷二维码")
	@GetMapping("getBookQrcodeStatistics")
	public ResponseDto<PageBeanNew<QrcodeStatisticsDTO>> getBookQrcodeStatistics(@RequestParam("adviserId") Long adviserId,
																				 @RequestParam("bookId") Long bookId,
																				 @RequestParam("channelId") Long channelId,
																				 @RequestParam("currentPage") Integer currentPage,
																				 @RequestParam("numPerPage") Integer numPerPage){
		return new ResponseDto<>(bookAdviserBiz.getBookQrcodeStatistics(adviserId, bookId, channelId, currentPage, numPerPage));
	}


	@Override
	@GetMapping("getRayBookCountAndRate")
	public ResponseDto<?> getRayBookCountAndRate(@RequestParam(value = "showRate", defaultValue = "false") Boolean showRate){
		return new ResponseDto<>(bookAdviserBiz.getRayBookCountAndRate(showRate));
	}

	@Override
	@PostMapping("getBookInfoByBookIds")
	public ResponseDto<?> getBookInfoByBookIds(@RequestBody MapResourceTotalCountDTO mapResourceTotalCountDTO) {
		return new ResponseDto<>(bookAdviserBiz.getBookInfoByBookIds(mapResourceTotalCountDTO.getBookIds(), mapResourceTotalCountDTO.getAdviserIds(), mapResourceTotalCountDTO.getChannelIds()));
	}
    @Override
	@RequestMapping(value = "/getAgentBookStatsDetail", method = RequestMethod.GET)
	public ResponseDto<PageBeanNew<AgentBookStatsDetailVO>> getAgentBookStatsDetail(
			@RequestHeader("token") String token,
			@RequestParam(value = "agentId") Long agentId,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "startDate", required = false) String startDate,
			@RequestParam(value = "endDate", required = false) String endDate,
			@RequestParam(value = "isRay", required = false) Integer isRay,
			@RequestParam(value = "currentPage") Integer currentPage,
			@RequestParam(value = "numPerPage") Integer numPerPage
	) throws BizException {
		SessionUtil.getToken4Redis(token);
		ParamChecker.checkPageParamIsAbsent(currentPage,numPerPage,"分页参数错误");
		DateTime start = Objects.isNull(DateUtil.parse(startDate))?null: DateUtil.beginOfDay(DateUtil.parse(startDate));
		DateTime end =Objects.isNull(DateUtil.parse(endDate))?null:DateUtil.beginOfDay(DateUtil.parse(endDate));
		// 开始结束同一天 则结束时间后延一天
		if (Objects.nonNull(start) && Objects.equals(start,end)){
			end = DateUtil.offsetDay(end.toJdkDate(),1);
		}
		return new ResponseDto<>(bookAdviserBiz.getAgentBookStatsDetail(agentId, name, start, end, isRay, currentPage, numPerPage));
    }

    @Override
	@RequestMapping(value = "/exportAgentBookStatsDetail", method = RequestMethod.GET)
	public ResponseDto<?> exportAgentBookStatsDetail(
			@RequestHeader("token") String token,
			@RequestParam(value = "agentId") Long agentId,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "startDate", required = false) String startDate,
			@RequestParam(value = "endDate", required = false) String endDate,
			@RequestParam(value = "isRay", required = false) Integer isRay
	) throws BizException {
		SessionUtil.getToken4Redis(token);
		DateTime start = Objects.isNull(DateUtil.parse(startDate))?null: DateUtil.beginOfDay(DateUtil.parse(startDate));
		DateTime end =Objects.isNull(DateUtil.parse(endDate))?null:DateUtil.beginOfDay(DateUtil.parse(endDate));
		bookAdviserBiz.exportAgentBookStatsDetail(agentId, name, start, end, isRay);
		return new ResponseDto<>();
    }

	@ApiOperation(value = "丢书页面获取书刊及商铺信息", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userInfo", value = "Cookie", dataType = "string", paramType = "header"),
			@ApiImplicitParam(name = "bookId", value = "书籍标识", dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "channelId", value = "渠道标识", dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "adviserId", value = "编辑标识", dataType = "long", paramType = "query")})
	@RequestMapping(value = "getBookDetail4Buy", method = RequestMethod.GET)
	ResponseDto<BookDto> getBookDetail4Buy(@CookieValue("userInfo") String userInfo,
										   @RequestParam(value = "bookId") Long bookId,
										   @RequestParam(value = "channelId") Long channelId,
										   @RequestParam(value = "adviserId") Long adviserId)
			throws BizException, PermissionException, JsonParseException{
		Cookie.getUserInfo(userInfo);
		BookDto bookDto = bookAdviserBiz.getBookDetail4Buy(bookId, adviserId, channelId);
		return new ResponseDto<>(bookDto);

	}

	@Override
	@GetMapping("getAnswerServesByBook")
	public ResponseDto<?> getAnswerServesByBook(@RequestParam("bookId") Long bookId,
										@RequestParam("adviserId") Long adviserId,
										@RequestParam("channelId") Long channelId){
		return new ResponseDto<>(bookAdviserBiz.getAnswerServesByBook(bookId, adviserId, channelId));
	}
}
