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

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.content.api.dto.material.ContentGoodsDTO;
import com.gic.content.api.dto.material.ContentMaterialLandingPageInfoDTO;
import com.gic.content.api.dto.material.MaterialLinkDTO;
import com.gic.content.api.dto.material.ProductInfoDTO;
import com.gic.content.api.qdto.material.ContentMaterialLandingPageQDTO;
import com.gic.content.api.qdto.share.MaterialLinkShareQDTO;
import com.gic.content.api.service.ContentMaterialShareApiService;
import com.gic.haoban.manage.api.dto.anaylsis.ClerkShareGoodsLogDTO;
import com.gic.haoban.manage.api.dto.content.log.ClerkShareMaterialLogDTO;
import com.gic.haoban.manage.api.enums.content.ShareBizType;
import com.gic.haoban.manage.api.service.content.MaterialShareLogApiService;
import com.gic.haoban.manage.web.qo.content.ContentMaterialBaseQO;
import com.gic.haoban.manage.web.qo.content.log.MaterialShareLogQO;
import com.gic.haoban.manage.web.qo.content.log.RecommendShareLogQO;
import com.gic.haoban.manage.web.qo.content.share.ContentLinkShareQO;
import com.gic.haoban.manage.web.vo.content.ContentMaterialInfoVO;
import com.gic.haoban.manage.web.vo.content.SimpleGoodsInfoVO;
import com.gic.haoban.manage.web.vo.content.share.ContentMaterialLandingPageVO;
import com.gic.member.api.constant.MemberExtKeyEnum;
import com.gic.member.api.dto.member.req.MemberExtraPropertyReq;
import com.gic.member.api.service.extra.MemberExtraPropertyApiService;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 好办-导购分享素材与素材落地页
 */
@RestController
public class ClerkMaterialShareController {

    private static final Logger log = LoggerFactory.getLogger(ClerkMaterialShareController.class);

    @Autowired
    private MaterialShareLogApiService materialShareLogApiService;

    @Autowired
    private ContentMaterialShareApiService contentMaterialShareApiService;

    @Autowired
    private MemberExtraPropertyApiService memberExtraPropertyApiService;

    /**
     * 导购分享素材日志
     *
     * @return
     */
    @RequestMapping(path = "/clerk/share/material/log", method = RequestMethod.POST)
    public RestResponse<Long> clerkShareMaterialLog(@RequestBody MaterialShareLogQO materialShareLogQo) {

        if (materialShareLogQo.getContentMaterialId() == null || StringUtils.isBlank(materialShareLogQo.getClerkId())) {
            log.info("参数缺失 {}", JSON.toJSONString(materialShareLogQo));
            return RestResponse.failure("-1", "参数异常");
        }
        ClerkShareMaterialLogDTO temp = new ClerkShareMaterialLogDTO();
        temp.setEnterpriseId(materialShareLogQo.getEnterpriseId());
        temp.setWxEnterpriseId(materialShareLogQo.getWxEnterpriseId());
        temp.setClerkId(materialShareLogQo.getClerkId());
        temp.setStaffId(materialShareLogQo.getStaffId());
        temp.setShareType(materialShareLogQo.getShareType());
        temp.setBizId(materialShareLogQo.getContentMaterialId() + "");
        temp.setBizType(ShareBizType.MATERIAL.getCode());
        temp.setStoreId(materialShareLogQo.getStoreId());
        temp.setExternalUserId(materialShareLogQo.getExternalUserId());
        temp.setExtend(materialShareLogQo.getExtend());
        ServiceResponse<Long> serviceResponse = materialShareLogApiService.saveClerkShareMaterialLog(temp);
        if (serviceResponse.isSuccess()) {
            return RestResponse.successResult(serviceResponse.getResult());
        }
        return RestResponse.failure("-701", "系统异常");
    }


    /**
     * 导购分享推荐商品日志
     * *
     *
     * @param recommendShareLogQO
     * @return
     */
    @RequestMapping(path = "/clerk/share/recommend/log", method = RequestMethod.POST)
    public RestResponse<Void> clerkShareRecommendLog(@RequestBody RecommendShareLogQO recommendShareLogQO) {

        if (CollectionUtils.isEmpty(recommendShareLogQO.getGoodsIdList())
                || CollectionUtils.isEmpty(recommendShareLogQO.getMemberInfoList())
                || StringUtils.isBlank(recommendShareLogQO.getClerkId())) {
            log.info("参数缺失 {}", JSON.toJSONString(recommendShareLogQO));
            return RestResponse.failure("-1", "参数异常");
        }
        log.info("saveClerkShareMaterialLog 保存导购分享推荐商品日志 clerkId:{},  recommendShareLogQO{}", recommendShareLogQO.getClerkId(), JSON.toJSONString(recommendShareLogQO));

        List<ClerkShareGoodsLogDTO> list = Lists.newArrayList();
        List<String> memberIdList = Lists.newArrayList();
        List<String> goodsIdList = recommendShareLogQO.getGoodsIdList();
        List<RecommendShareLogQO.MemberInfo> externalUserIdList = recommendShareLogQO.getMemberInfoList();

        for (RecommendShareLogQO.MemberInfo memberInfo : externalUserIdList) {
            for (String goodsId : goodsIdList) {
                ClerkShareGoodsLogDTO temp = new ClerkShareGoodsLogDTO();
                temp.setEnterpriseId(recommendShareLogQO.getEnterpriseId());
                temp.setWxEnterpriseId(recommendShareLogQO.getWxEnterpriseId());
                temp.setClerkId(recommendShareLogQO.getClerkId());
                temp.setExternalUserId(memberInfo.getExternalUserId());
                temp.setMemberId(memberInfo.getMemberId());
                if(StringUtils.isNotEmpty(memberInfo.getMemberId())){
                    memberIdList.add(memberInfo.getMemberId());
                }
                temp.setBizId(goodsId);
                temp.setBizType(ShareBizType.GOODS.getCode());
                temp.setStoreId(recommendShareLogQO.getStoreId());
                temp.setExtend(recommendShareLogQO.getExtend());
                temp.setStaffId(recommendShareLogQO.getStaffId());
                list.add(temp);
            }
        }

        ServiceResponse<Long> serviceResponse = materialShareLogApiService.saveClerkShareRecommendLog(list);

        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure("-701", "系统异常");
        }
        //更新会员推荐时间更新
        if(CollectionUtils.isNotEmpty(memberIdList)){
            for (String memberId : memberIdList) {
                MemberExtraPropertyReq memberExtraPropertyReq = new MemberExtraPropertyReq();
                memberExtraPropertyReq.setEnterpriseId(recommendShareLogQO.getEnterpriseId());
                memberExtraPropertyReq.setMemberId(memberId);
                memberExtraPropertyReq.setExtraKey(MemberExtKeyEnum.MEMBER_GOODS_SUGGEST_TIME.key());
                memberExtraPropertyReq.setExtraValue(new Date());
                memberExtraPropertyApiService.updateMemberExtraProperty(memberExtraPropertyReq);
            }
        }

        return RestResponse.successResult();
    }


    /**
     * 查询素材落地页信息
     *
     * @param contentMaterialBaseQO
     * @return
     */
    @RequestMapping(path = "/content/material/share/landing/page/info")
    public RestResponse<ContentMaterialLandingPageVO> queryMaterialLandingPage(ContentMaterialBaseQO contentMaterialBaseQO) {

        ContentMaterialLandingPageQDTO searchQo = new ContentMaterialLandingPageQDTO();
        BeanUtils.copyProperties(contentMaterialBaseQO, searchQo);
        ServiceResponse<ContentMaterialLandingPageInfoDTO> serviceResponse = contentMaterialShareApiService.queryMaterialLandPageInfo(searchQo);
        if (!serviceResponse.isSuccess()) {
            log.info("获取素材落地页异常 {}", JSON.toJSONString(serviceResponse));
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        ContentMaterialLandingPageVO materialLandingPageVO = EntityUtil.changeEntityByJSON(ContentMaterialLandingPageVO.class, serviceResponse.getResult());
        if (serviceResponse.getResult() != null && serviceResponse.getResult().getContentMaterialInfo() != null) {
            ContentMaterialInfoVO contentMaterialInfo = materialLandingPageVO.getContentMaterialInfo();
            if (StringUtils.isNotBlank(serviceResponse.getResult().getContentMaterialInfo().getMaterialImageUrls())) {
                contentMaterialInfo.setMaterialImageUrls(Splitter.on(",").splitToList(serviceResponse.getResult().getContentMaterialInfo().getMaterialImageUrls()));
            }
            if (StringUtils.isNotBlank(serviceResponse.getResult().getContentMaterialInfo().getMaterialThumbnailImageUrls())) {
                contentMaterialInfo.setMaterialThumbnailImageUrls(
                        Splitter.on(",").splitToList(serviceResponse.getResult().getContentMaterialInfo().getMaterialImageUrls()));
            }
        }
        List<ProductInfoDTO> goodsInfos = serviceResponse.getResult().getProductInfos();
        if (CollectionUtils.isNotEmpty(goodsInfos)) {
            List<SimpleGoodsInfoVO> goodsInfoVOS = goodsInfos.stream()
                    .map(item -> {
                        SimpleGoodsInfoVO temp = new SimpleGoodsInfoVO();
                        BeanUtils.copyProperties(item, temp);
                        temp.setGoodsId(item.getProId());
                        temp.setGoodsName(item.getProName());
                        temp.setSalePrice(item.getMinPrice());
                        temp.setGoodsImg(item.getImageUrl());
                        return temp;
                    })
                    .collect(Collectors.toList());
            materialLandingPageVO.setGoodsInfos(goodsInfoVOS);
        }
        return RestResponse.successResult(materialLandingPageVO);
    }

    /**
     * 生成素材外链跳转地址
     *
     * @param linkShareQO
     * @return
     */
    @RequestMapping(path = "/clerk/share-material-link", method = RequestMethod.POST)
    public RestResponse<MaterialLinkDTO> clerkShareMaterialLink(@RequestBody ContentLinkShareQO linkShareQO) {
        MaterialLinkShareQDTO linkShareQDTO = new MaterialLinkShareQDTO();
        linkShareQDTO.setClerkId(linkShareQO.getClerkId());
        linkShareQDTO.setStoreId(linkShareQO.getStoreId());
        linkShareQDTO.setContentMaterialId(linkShareQO.getContentMaterialId());
        linkShareQDTO.setEnterpriseId(linkShareQO.getEnterpriseId());
        linkShareQDTO.setClerkType(linkShareQO.getClerkType());
        linkShareQDTO.setChannelSource(linkShareQO.getChannelSource());
        ServiceResponse<MaterialLinkDTO> response = contentMaterialShareApiService.generateLink(linkShareQDTO);
        if (!response.isSuccess()) {
            return RestResponse.failure(response.getCode(), response.getMessage());
        }
        return RestResponse.successResult(response.getResult());
    }

}
