package com.gic.haoban.manage.web.controller.content;

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.BasePageInfo;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.content.api.dto.column.ContentColumnListDTO;
import com.gic.content.api.dto.material.ContentMaterialDTO;
import com.gic.content.api.dto.material.ContentMaterialLikeDTO;
import com.gic.content.api.dto.material.ContentMaterialShareInfoDTO;
import com.gic.content.api.enums.ColumnEnum;
import com.gic.content.api.qdto.column.ContentColumnClerkQDTO;
import com.gic.content.api.qdto.like.ContentMaterialLikeQDTO;
import com.gic.content.api.qdto.material.ContentMaterialPageQDTO;
import com.gic.content.api.qdto.material.ContentMaterialShareQDTO;
import com.gic.content.api.service.ContentColumnApiService;
import com.gic.content.api.service.ContentMaterialApiService;
import com.gic.content.api.service.ContentMaterialShareApiService;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.manage.api.dto.content.MaterialConvertDTO;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.web.controller.commission.CommissionManager;
import com.gic.haoban.manage.api.service.content.MaterialShareLogApiService;
import com.gic.haoban.manage.web.controller.content.adaptor.ClerkStoreAdaptor;
import com.gic.haoban.manage.web.controller.content.adaptor.MaterialDataAdaptor;
import com.gic.haoban.manage.web.controller.goods.GoodsInfoAdaptor;
import com.gic.haoban.manage.web.qo.content.ContentColumnClerkViewQO;
import com.gic.haoban.manage.web.qo.content.ContentMaterialListQO;
import com.gic.haoban.manage.web.qo.content.ContentMaterialQO;
import com.gic.haoban.manage.web.qo.content.ContentMaterialShareQO;
import com.gic.haoban.manage.web.vo.content.ContentColumnInfoVO;
import com.gic.haoban.manage.web.vo.content.ContentMaterialInfoVO;
import com.gic.haoban.manage.web.vo.content.ContentMaterialShareInfoVO;
import com.gic.haoban.manage.web.vo.content.MaterialConvertVO;
import com.gic.haoban.manage.web.vo.content.SimpleGoodsInfoVO;
import com.gic.haoban.manage.web.qo.content.*;
import com.gic.haoban.manage.web.qo.content.like.ContentMaterialLikeQO;
import com.gic.haoban.manage.web.vo.content.*;
import com.gic.haoban.manage.web.vo.content.statistics.ContentMaterialKnowVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 好办-素材
 */
@RestController
public class ContentMaterialController {

    private static final Logger log = LoggerFactory.getLogger(ContentMaterialController.class);
    @Autowired
    private ContentColumnApiService contentColumnApiService;
    @Autowired
    private ContentMaterialApiService contentMaterialApiService;
    @Autowired
    private ContentMaterialShareApiService contentMaterialShareApiService;
    @Autowired
    private ClerkStoreAdaptor clerkStoreAdaptor;
    @Autowired
    private GoodsInfoAdaptor goodsInfoAdaptor;
    @Autowired
    MaterialShareLogApiService materialShareLogApiService;
    @Autowired
    private CommissionManager commissionManager;
    @Autowired
    private MaterialDataAdaptor materialDataAdaptor;


    /**
     * 栏目列表
     *
     * @param enterpriseId  企业id
     * @param wxEnterpriseId 微信企业id
     * @param storeId   门店id
     * @param clerkId 导购id
     * @param columnType 1营销2商品3社区4知识库
     * @return
     */
    @RequestMapping(path = "/column-list")
    public RestResponse<List<ContentColumnInfoVO>> queryContentColumn(String enterpriseId, String storeId, String wxEnterpriseId, String clerkId,
                                                                      Integer columnType) {
        List<String> storeIdList = new ArrayList<>();
        if (StringUtils.isBlank(storeId)) {
            // 区经 获取管辖的权限
            List<String> storeIds = this.clerkStoreAdaptor.queryClerkStoreIds(clerkId, wxEnterpriseId);
            storeIdList.addAll(storeIds);
        } else {
            storeIdList.add(storeId);
        }
        if (columnType == null) {
            columnType = ColumnEnum.MATERIAL.value;
        }
        ServiceResponse<List<ContentColumnListDTO>> serviceResponse = contentColumnApiService.listColumnFront(enterpriseId, columnType, storeIdList, clerkId);
        if (!serviceResponse.isSuccess() || CollectionUtils.isEmpty(serviceResponse.getResult())) {
            return RestResponse.successResult(Collections.emptyList());
        }
        List<ContentColumnInfoVO> contentColumnInfos = EntityUtil.changeEntityListByJSON(ContentColumnInfoVO.class, serviceResponse.getResult());
        return RestResponse.successResult(contentColumnInfos);
    }


    /**
     * 素材列表
     *
     * @return
     */
    @RequestMapping(path = "/content-material-list")
    public RestResponse<Page<ContentMaterialInfoVO>> queryContentMaterialList(@RequestBody ContentMaterialQO contentMaterialQO) {

        if (StringUtils.isBlank(contentMaterialQO.getEnterpriseId())) {
            log.info("企业id未传 {}", JSON.toJSONString(contentMaterialQO));
            return RestResponse.failure("-777", "参数异常");
        }
        List<Integer> goodsShowStatus = goodsInfoAdaptor.getGoodsShowStatus(contentMaterialQO.getEnterpriseId());
        ContentMaterialPageQDTO pageQDTO = new ContentMaterialPageQDTO();
        pageQDTO.setQueryScene(contentMaterialQO.getQueryScene());
        pageQDTO.setEnterpriseId(contentMaterialQO.getEnterpriseId());
        pageQDTO.setSearch(contentMaterialQO.getSearch());
        pageQDTO.setContentColumnId(contentMaterialQO.getContentColumnId());
        pageQDTO.setMaterialType(contentMaterialQO.getMaterialType());
        pageQDTO.setClerkId(contentMaterialQO.getClerkId());

        if (contentMaterialQO.getSortType() != null) {
            if (contentMaterialQO.getSortType() == 2) {
                pageQDTO.setHotFlag(1);
            }
        }
        if (StringUtils.isBlank(contentMaterialQO.getStoreId())) {
            // 区经 获取管辖的权限
            List<String> storeIds = this.clerkStoreAdaptor.queryClerkStoreIds(contentMaterialQO.getClerkId(), contentMaterialQO.getWxEnterpriseId());
            pageQDTO.setStoreIdList(storeIds);
        } else {
            pageQDTO.setStoreIdList(Collections.singletonList(contentMaterialQO.getStoreId()));
        }
        if (contentMaterialQO.getSearchType() != null && contentMaterialQO.getSearchType().equals(1)) {
            if (StringUtils.isNotBlank(contentMaterialQO.getSearch())) {
                // 搜索条件需要置为空
                pageQDTO.setSearch(null);
                List<String> goodsIds = goodsInfoAdaptor.queryGoodsIdWithSearch(contentMaterialQO.getEnterpriseId(), contentMaterialQO.getSearch());
                if (CollectionUtils.isEmpty(goodsIds)) {
                    log.info("搜索商品不存在 {}", contentMaterialQO.getSearch());
                    return RestResponse.successResult(new Page<>());
                }
                pageQDTO.setGoodsIdList(goodsIds);
            }
        }
        BasePageInfo pageInfo = new BasePageInfo();
        pageInfo.setPageNum(contentMaterialQO.getPageNum());
        pageInfo.setPageSize(contentMaterialQO.getPageSize());
        ServiceResponse<Page<ContentMaterialDTO>> serviceResponse = contentMaterialApiService.pageMaterial(pageQDTO, pageInfo);
        if (!serviceResponse.isSuccess() || CollectionUtils.isEmpty(serviceResponse.getResult().getResult())) {
            return RestResponse.successResult(new Page<>());
        }
        Page<ContentMaterialDTO> responseResult = serviceResponse.getResult();
        Page<ContentMaterialInfoVO> result = new Page<>();
        result.setTotalCount(responseResult.getTotalCount());
        List<String> goodsIds = responseResult.getResult()
                .stream()
                .filter(item -> CollectionUtils.isNotEmpty(item.getContentGoodsList()))
                .map(item -> item.getContentGoodsList().get(0).getGoodsId())
                .distinct()
                .collect(Collectors.toList());
        Map<String, BigDecimal> commissionMap = commissionManager.calcGoodsCommission(contentMaterialQO.getEnterpriseId(), contentMaterialQO.getStoreId(),
                contentMaterialQO.getClerkId(), goodsIds);
        List<ContentMaterialInfoVO> contentMaterialInfos = responseResult.getResult().stream()
                .map(item -> getContentMaterialInfoVO(goodsShowStatus, item, commissionMap))
                .collect(Collectors.toList());
        result.setResult(contentMaterialInfos);
        result.setCurrentPage(contentMaterialQO.getPageNum());
        result.setPageSize(contentMaterialQO.getPageSize());
        return RestResponse.successResult(result);
    }

    /**
     * 对象转换
     *
     * @param goodsShowStatus
     * @param item
     * @return
     */
    private ContentMaterialInfoVO getContentMaterialInfoVO(List<Integer> goodsShowStatus, ContentMaterialDTO item, Map<String, BigDecimal> commissionMap) {
        ContentMaterialInfoVO contentMaterialInfoVO = new ContentMaterialInfoVO();
        BeanUtils.copyProperties(item, contentMaterialInfoVO);
        if (CollectionUtils.isNotEmpty(item.getContentGoodsList())) {
            List<SimpleGoodsInfoVO> goodsInfoVOS = item.getContentGoodsList()
                    .stream()
                    .filter(temp -> goodsShowStatus.contains(temp.getStatus()))
                    .map(temp -> {
                        SimpleGoodsInfoVO simpleGoodsInfoVO = new SimpleGoodsInfoVO();
                        BeanUtils.copyProperties(temp, simpleGoodsInfoVO);
                        simpleGoodsInfoVO.setGoodsImg(temp.getGoodsImageUrl());
                        BigDecimal commission = commissionMap.get(temp.getGoodsId());
                        simpleGoodsInfoVO.setCommission(commission);
                        return simpleGoodsInfoVO;
                    }).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(goodsInfoVOS)) {
                contentMaterialInfoVO.setContentGoodsList(goodsInfoVOS);
            }
        }
        contentMaterialInfoVO.setPublishTime(item.getPublishBeginTime());
        contentMaterialInfoVO.convertMaterialImages(item.getMaterialImageUrls(),item.getMaterialThumbnailImageUrls());
        return contentMaterialInfoVO;
    }

    /**
     * 素材详情
     * @param enterpriseId 企业id
     * @param contentMaterialId 素材id
     * @param clerkId 导购id
     * @return
     */
    @ResponseBody
    @RequestMapping("/get-material")
    public RestResponse<ContentMaterialInfoVO> getMaterialMember(String enterpriseId,Long contentMaterialId,String clerkId) {
        ServiceResponse<ContentMaterialDTO> response = contentMaterialApiService.getMaterialMember(enterpriseId, contentMaterialId, clerkId, "");
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        ContentMaterialDTO result = response.getResult();
        ContentMaterialInfoVO detailVO = com.gic.commons.util.EntityUtil.changeEntityNew(ContentMaterialInfoVO.class, result);
        detailVO.setPublishTime(result.getPublishBeginTime());
        detailVO.convertMaterialImages(result.getMaterialImageUrls(),result.getMaterialThumbnailImageUrls());
        return RestResponse.successResult(detailVO);
    }

    /**
     * 分享商品素材
     *
     * @param contentMaterialShareQO
     * @return
     */
    @RequestMapping(path = "/share-content-material")
    public RestResponse<ContentMaterialShareInfoVO> shareContentMaterial(ContentMaterialShareQO contentMaterialShareQO) {

        if (StringUtils.isBlank(contentMaterialShareQO.getEnterpriseId())) {
            return RestResponse.failure("-777", "企业参数异常");
        }
        if (contentMaterialShareQO.getContentMaterialId() == null) {
            // 无素材id 不生成参数
            return RestResponse.successResult();
        }
        ContentMaterialShareQDTO contentMaterialShareQDTO = new ContentMaterialShareQDTO();
        BeanUtils.copyProperties(contentMaterialShareQO, contentMaterialShareQDTO);
        ServiceResponse<ContentMaterialShareInfoDTO> serviceResponse = contentMaterialShareApiService.shareContentMaterial(contentMaterialShareQDTO);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        ContentMaterialShareInfoVO shareInfoVO = new ContentMaterialShareInfoVO();
        BeanUtils.copyProperties(serviceResponse.getResult(), shareInfoVO);
        return RestResponse.successResult(shareInfoVO);
    }

    /**
     * 导购栏目最后访问记录
     *
     * @param contentColumnClerkViewQO qo
     * @return
     */
    @RequestMapping(path = "/column-clerk")
    public RestResponse<Void> viewColumnClerk(@RequestBody ContentColumnClerkViewQO contentColumnClerkViewQO) {
        if (StringUtils.isBlank(contentColumnClerkViewQO.getEnterpriseId())) {
            return RestResponse.failure("-777", "企业参数异常");
        }
        ContentColumnClerkQDTO columnClerkQDTO = EntityUtil.changeEntityByJSON(ContentColumnClerkQDTO.class, contentColumnClerkViewQO);
        ServiceResponse<Void> serviceResponse = contentColumnApiService.saveOrUpdateColumnClerk(columnClerkQDTO);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        return RestResponse.successResult();
    }

    @RequestMapping(path = "/share-convert")
    public RestResponse<?> shareConvert(@RequestBody MaterialConvertVO materialConvertVO) {
        MaterialConvertDTO materialConvertDTO = new MaterialConvertDTO();
        BeanUtils.copyProperties(materialConvertVO, materialConvertDTO);
        ServiceResponse<List<String>> serviceResponse = materialShareLogApiService.convertMaterialId(materialConvertDTO);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        return RestResponse.successResult(serviceResponse.getResult());
    }

    /**
     * 素材数量查询
     * @param search    search
     * @return
     */
    @ResponseBody
    @RequestMapping("/count-material")
    public RestResponse<Long> countMaterial(@RequestBody ContentMaterialListQO search) {
        ContentMaterialPageQDTO pageQDTO = EntityUtil.changeEntityByOrika(ContentMaterialPageQDTO.class, search);
        ServiceResponse<Long> response = contentMaterialApiService.countMaterialBySearch(pageQDTO);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        return RestResponse.successResult(response.getResult());
    }

    /**
     * 点赞素材
     * @param likeQO  qdto
     * @return
     */
    @ResponseBody
    @RequestMapping("/like-material")
    public RestResponse<Integer> likeMaterial(@RequestBody ContentMaterialLikeQO likeQO) {
        ContentMaterialLikeQDTO likeQDTO = EntityUtil.changeEntityByOrika(ContentMaterialLikeQDTO.class, likeQO);
        ServiceResponse<Integer> response = contentMaterialApiService.likeMaterial(likeQDTO);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        return RestResponse.successResult(response.getResult());
    }

    /**
     * 素材列表数据
     * @return
     */
    @ResponseBody
    @RequestMapping("/list-material-data")
    public RestResponse<List<ContentMaterialDataVO>> listMaterialData(@RequestBody ContentMaterialClerkQO qo) {
        List<Long> contentMaterialIdList = qo.getContentMaterialIdList();
        String clerkId = qo.getClerkId();
        String enterpriseId = qo.getEnterpriseId();
        ServiceResponse<List<ContentMaterialLikeDTO>> response = contentMaterialApiService.listMaterialLike(enterpriseId, clerkId, contentMaterialIdList);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        //点赞数据
        Map<Long, ContentMaterialLikeDTO> likeMap = new HashMap<>();
        List<ContentMaterialLikeDTO> likeList = response.getResult();
        if (CollectionUtils.isNotEmpty(likeList)) {
            likeMap = likeList.stream().collect(Collectors.toMap(ContentMaterialLikeDTO::getContentMaterialId, t -> t));
        }
        //阅读、评论数据
        List<ContentMaterialKnowVO> knowList = materialDataAdaptor.queryKnowData(enterpriseId, clerkId,contentMaterialIdList);
        Map<Long, ContentMaterialKnowVO> knowMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(knowList)) {
            knowMap = knowList.stream().collect(Collectors.toMap(ContentMaterialKnowVO::getContentMaterialId, t -> t));
        }
        List<ContentMaterialDataVO> dataList = new ArrayList<>();
        ContentMaterialDataVO dataVO = null;
        for (Long materialId : contentMaterialIdList) {
            dataVO = new ContentMaterialDataVO();
            dataVO.setContentMaterialId(materialId);
            ContentMaterialLikeDTO likeDTO = likeMap.get(materialId);
            if (likeDTO != null) {
                Long likeCount = likeDTO.getLikeCount();
                dataVO.setLikeCount(likeCount == null ? 0 : likeCount.intValue());
                dataVO.setLikeFlag(likeDTO.getLikeFlag());
            }
            ContentMaterialKnowVO knowVO = knowMap.get(materialId);
            if (knowVO != null) {
                dataVO.setCmtCnt(knowVO.getCmtCnt());
                dataVO.setReadCnt(knowVO.getReadCnt());
            }
            dataList.add(dataVO);
        }
        return RestResponse.successResult(dataList);
    }
}
