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

import com.alibaba.fastjson.JSON;
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.material.ContentMaterialBaseDTO;
import com.gic.haoban.manage.api.dto.content.PotentialCustomerDTO;
import com.gic.haoban.manage.api.dto.qdto.content.PotentialCustomerMarkRecordDTO;
import com.gic.haoban.manage.api.dto.qdto.content.PotentialCustomerQDTO;
import com.gic.haoban.manage.api.enums.content.ShareBizType;
import com.gic.haoban.manage.api.service.content.PotentialCustomerApiService;
import com.gic.haoban.manage.web.controller.content.adaptor.ContentMaterialAdaptor;
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.potential.PotentialCustomerMarkRecordVO;
import com.gic.haoban.manage.web.qo.content.potential.PotentialCustomerQO;
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.potential.PotentialCustomerVO;
import com.gic.store.goods.dto.goods.GoodsInfoSimpleDTO;
import com.gic.store.goods.dto.goods.GoodsSpuInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
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.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 好办-销售线索
 **/
@Slf4j
@RestController
@RequestMapping(path = "/potential/customer")
public class PotentialCustomerController {

    @Autowired
    private PotentialCustomerApiService potentialCustomerApiService;
    @Autowired
    ContentMaterialAdaptor contentMaterialAdaptor;
    @Autowired
    MaterialDataAdaptor materialDataAdaptor;
    @Autowired
    private GoodsInfoAdaptor goodsInfoAdaptor;


    /**
     * 销售线索列表
     *
     * @param potentialCustomerQO
     * @return
     */
    @RequestMapping(path = "/list")
    public RestResponse<Page<PotentialCustomerVO>> queryPotentialCustomerList(@RequestBody PotentialCustomerQO potentialCustomerQO) {
        if(StringUtils.isBlank(potentialCustomerQO.getStoreId())) {
            log.info("区经");
            return RestResponse.successResult();
        }
        PotentialCustomerQDTO searchQDTO = new PotentialCustomerQDTO();
        BeanUtils.copyProperties(potentialCustomerQO, searchQDTO);
        ServiceResponse<Page<PotentialCustomerDTO>> serviceResponse =
                potentialCustomerApiService.queryPotentialCustomer(searchQDTO);
        if (!serviceResponse.isSuccess()) {
            log.info("查询销售线索异常 {}", JSON.toJSONString(serviceResponse));
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        if (CollectionUtils.isEmpty(serviceResponse.getResult().getResult())) {
            log.info("查询销售线索为空 params: {}", JSON.toJSONString(potentialCustomerQO));
            return RestResponse.successResult();
        }
        List<PotentialCustomerDTO> customerDTOS = serviceResponse.getResult().getResult();
        List<PotentialCustomerVO> customerVOS = this.buildContentInfo(potentialCustomerQO, customerDTOS);
        this.buildGoodsInfo(searchQDTO.getEnterpriseId(), customerVOS);
        Page<PotentialCustomerVO> result = new Page<>();
        result.setTotalCount(serviceResponse.getResult().getTotalCount());
        result.setResult(customerVOS);
        result.setCurrentPage(potentialCustomerQO.getPageNum());
        result.setPageSize(potentialCustomerQO.getPageSize());
        return RestResponse.successResult(result);
    }

    private List<PotentialCustomerVO> buildContentInfo(PotentialCustomerQO potentialCustomerQO, List<PotentialCustomerDTO> customerDTOS) {
        // 素材信息
        List<Long> materialIds = customerDTOS
                .stream()
                .filter(item -> ShareBizType.MATERIAL.getCode().equals(item.getBizType()))
                .map(item -> Long.parseLong(item.getBizId()))
                .collect(Collectors.toList());
        Map<Long, ContentMaterialBaseDTO> materialInfoMap = contentMaterialAdaptor.queryMaterialInfoMap(potentialCustomerQO.getEnterpriseId(), materialIds);

        // 会员最近30天访问
        List<String> memberIds = customerDTOS
                .stream()
                .filter(item -> ShareBizType.MATERIAL.getCode().equals(item.getBizType()))
                .map(PotentialCustomerDTO::getMemberId)
                .collect(Collectors.toList());
        Map<String, Integer> memberVisitMap =
                materialDataAdaptor.queryMemberVisitMap(potentialCustomerQO.getEnterpriseId(), null, potentialCustomerQO.getClerkId(), memberIds, potentialCustomerQO.getWithData());
        List<PotentialCustomerVO> customerVOS = customerDTOS
                .stream()
                .map(item -> {
                    PotentialCustomerVO temp = new PotentialCustomerVO();
                    BeanUtils.copyProperties(item, temp);
                    temp.setPotentialCustomerId(item.getPotentialCustomerId());
                    if (ShareBizType.MATERIAL.getCode().equals(item.getBizType())) {
                        ContentMaterialBaseDTO contentMaterialBaseDTO = materialInfoMap.get(Long.parseLong(item.getBizId()));
                        if (contentMaterialBaseDTO != null) {
                            ContentMaterialInfoVO contentMaterialInfoVO = new ContentMaterialInfoVO();
                            BeanUtils.copyProperties(contentMaterialBaseDTO, contentMaterialInfoVO);
                            if (StringUtils.isNotBlank(contentMaterialBaseDTO.getMaterialImageUrls())) {
                                String[] split = StringUtils.split(contentMaterialBaseDTO.getMaterialImageUrls(), ",");
                                List<String> imageUrls = Arrays.stream(split).collect(Collectors.toList());
                                contentMaterialInfoVO.setMaterialImageUrls(imageUrls);
                            }
                            if (StringUtils.isNotBlank(contentMaterialBaseDTO.getMaterialThumbnailImageUrls())) {
                                String[] split = StringUtils.split(contentMaterialBaseDTO.getMaterialThumbnailImageUrls(), ",");
                                List<String> imageUrls = Arrays.stream(split).collect(Collectors.toList());
                                contentMaterialInfoVO.setMaterialThumbnailImageUrls(imageUrls);
                            }
                            temp.setContentMaterialInfoVO(contentMaterialInfoVO);
                        }
                        Integer visitNum = memberVisitMap.get(item.getMemberId());
                        temp.setVisitNum(Optional.ofNullable(visitNum).orElse(0));
                    }
                    return temp;
                })
                .collect(Collectors.toList());
        return customerVOS;
    }

    private void buildGoodsInfo(String enterpriseId, List<PotentialCustomerVO> customerVos) {
        if (CollectionUtils.isEmpty(customerVos)) {
            return;
        }
        List<String> goodsIds = customerVos
                .stream()
                .filter(item -> ShareBizType.GOODS.getCode().equals(item.getBizType()))
                .map(PotentialCustomerVO::getBizId)
                .distinct()
                .collect(Collectors.toList());

        Map<String, GoodsInfoSimpleDTO> goodsInfoMap = goodsInfoAdaptor.queryGoodsInfo(enterpriseId, goodsIds);
        Map<String, GoodsSpuInfoDTO> goodsSpuInfoMap = goodsInfoAdaptor.queryGoodsMinPrice(enterpriseId, goodsIds);
        for (PotentialCustomerVO customerVo : customerVos) {
            GoodsInfoSimpleDTO goodsInfoSimpleDTO = goodsInfoMap.get(customerVo.getBizId());
            if (goodsInfoSimpleDTO == null) {
                continue;
            }
            SimpleGoodsInfoVO simpleGoodsInfoVO = new SimpleGoodsInfoVO();
            simpleGoodsInfoVO.setGoodsId(customerVo.getBizId());
            simpleGoodsInfoVO.setGoodsCode(goodsInfoSimpleDTO.getGoodsCode());
            simpleGoodsInfoVO.setGoodsName(goodsInfoSimpleDTO.getGoodsName());
            simpleGoodsInfoVO.setSourceType(goodsInfoSimpleDTO.getSourceType());
            simpleGoodsInfoVO.setGoodsImg(goodsInfoSimpleDTO.getGoodsImageUrl());
            simpleGoodsInfoVO.setSalePrice(goodsInfoSimpleDTO.getSalePrice());
            GoodsSpuInfoDTO goodsSpuInfoDTO = goodsSpuInfoMap.get(customerVo.getBizId());
            if (goodsSpuInfoDTO != null && goodsSpuInfoDTO.getMinPrice() != null) {
                simpleGoodsInfoVO.setSalePrice(goodsSpuInfoDTO.getMinPrice());
            }
            customerVo.setSimpleGoodsInfoVO(simpleGoodsInfoVO);
        }
    }


    /**
     * 标记销售线索为已看
     *
     * @return
     */
    @RequestMapping(path = "/mark/record/see")
    public RestResponse<?> markRecordSee(@RequestBody PotentialCustomerMarkRecordVO potentialCustomerMarkRecordVO) {

        PotentialCustomerMarkRecordDTO markRecord = new PotentialCustomerMarkRecordDTO();
        BeanUtils.copyProperties(potentialCustomerMarkRecordVO, markRecord);
        ServiceResponse<Long> serviceResponse = potentialCustomerApiService.markPotentialCustomer(markRecord);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        return RestResponse.successResult();
    }

    /**
     * 标记客户为星标客户
     *
     * @return
     */
    @RequestMapping(path = "/mark/member/star")
    public RestResponse<?> markMemberStar(@RequestBody PotentialCustomerMarkRecordVO potentialCustomerMarkRecordVO) {
        PotentialCustomerMarkRecordDTO markRecord = new PotentialCustomerMarkRecordDTO();
        BeanUtils.copyProperties(potentialCustomerMarkRecordVO, markRecord);
        ServiceResponse<Long> serviceResponse = potentialCustomerApiService.markPotentialCustomer(markRecord);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        return RestResponse.successResult();
    }
}
