package com.platform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.CanUserUpdateRecord;
import com.platform.entity.*;
import com.platform.enums.ResultCodeEnum;
import com.platform.exception.CommonBaseException;
import com.platform.service.custom.GoodsVisitHistoryService;
import com.platform.service.custom.SceneCensusService;
import com.platform.service.custom.TmBrandAdminService;
import com.platform.service.impl.BrandServiceImpl;
import com.platform.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * @author abnerhou
 * @date 2020/7/15 12:22
 * @desciption
 */
@Slf4j
@Api(tags = "小程序统计相关的接口")
@Controller
@RequestMapping("/app/census")
public class AppCensusController {

    @Autowired
    private BrandServiceImpl brandService;

    @Autowired
    private SceneCensusService sceneCensusService;


    @Autowired
    private UserServiceImpl userService;


    @Autowired
    private GoodsVisitHistoryService goodsVisitHistoryService;

    @Autowired
    private TmBrandAdminService tmBrandAdminService;


    @Value("${4dkankan.host}")
    private String kankanHost;

    @ApiOperation(value = "获取场景统计")
    @GetMapping("/getSceneCensus")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "guideId", value = "管理员ID", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "startDate", value = "日期-不能获取当天的，只能获取昨天以及昨天之前的", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "size", value = "历史前多少天", paramType = "query", required = true, dataType = "Integer")
    })
    public Result getSceneCensus(@RequestParam(name = "guideId") Integer guideId,
                                 @RequestParam(name = "brandId") Integer brandId,
                                 String startDate,
                                 Integer size) {
        if (null == guideId || null == brandId) {
            throw new CommonBaseException(ResultCodeEnum.D3001, "管理员ID或者店铺ID不能为空");
        }
        LocalDate stasticEndDate = null;
        LocalDate stasticStartDate = null;
        DateTimeFormatter localDateFormat  = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        int offset = 7;
        if (null != size) {
            offset = size;
        }
        if (StringUtils.isNotBlank(startDate)) {
            stasticEndDate = LocalDate.parse(startDate, localDateFormat);
        }
        if (null == stasticEndDate) {
            stasticEndDate = LocalDate.now().plusDays(-1);
            log.info("接口没上送统计日期，默认获取当前的前一天日期:{}", stasticEndDate);
        }
        stasticStartDate = stasticEndDate.plusDays(0 - (offset - 1));
        log.info("统计日期为:{} -- {}", stasticStartDate, stasticEndDate);

        UserEntity guide = userService.queryObject(guideId);
        if(null == guide){
            throw new CommonBaseException(ResultCodeEnum.D101 , "管理员不存在");
        }

       TmBrandAdmin brandAdmin = tmBrandAdminService.getByAdminIdAndBrandId(guideId , brandId);
        if(null == brandAdmin){
            throw new CommonBaseException(ResultCodeEnum.D101 , "管理员未绑定商铺");
        }
        final LocalDate finalStasticEndDate = stasticEndDate;
        final LocalDate finalStasticStartDate = stasticStartDate;
        BrandEntity brandEntity = brandService.queryObject(brandAdmin.getBrandId());
        TmSceneCensus tmSceneCensus = new TmSceneCensus();
        if(null != brandEntity && !StringUtils.isBlank(brandEntity.getSceneNum())){
            tmSceneCensus = sceneCensusService.getCensusBySceneNumForUpdate(brandEntity.getSceneNum(), finalStasticEndDate);
            if (null != tmSceneCensus && StringUtils.isNoneBlank(tmSceneCensus.getPvHistory(),
                    tmSceneCensus.getUvHistory(), tmSceneCensus.getHotVisitHistory(), tmSceneCensus.getTalkHistory())) {
                //已经存在直接返回，不去调看看的接口
                if(null != tmSceneCensus.getCensusSize() && tmSceneCensus.getCensusSize() == size){
                    log.info("场景[{}]在统计日期:[{}]的统计范围[{}]已经存在，不再重新获取" , brandEntity.getSceneNum() , finalStasticEndDate , size);
                    return Result.success(tmSceneCensus);
                }

            }
            log.info("本地未存储数据，将要去四维看看获取统计数据");
            Map<String, Object> pvUvMap = sceneCensusService.getPvUvHistoryFromKankan(finalStasticStartDate, finalStasticEndDate, brandEntity.getSceneNum());
            List<Map<String, Object>> scenePvList = (List<Map<String, Object>>) pvUvMap.get("pv");
            List<Map<String, Object>> sceneUvList = (List<Map<String, Object>>) pvUvMap.get("uv");
            List<Map<String, Object>> hotVisitList = sceneCensusService.getHotHistoryFromKankan(finalStasticStartDate, finalStasticEndDate, brandEntity.getSceneNum());
            long totalVisitTalk = goodsVisitHistoryService.countTotalBySceneNum(brandEntity.getSceneNum());
            List<Map<String, Object>> talkHistory = goodsVisitHistoryService.getHistoryByRangeTwo(finalStasticStartDate, size, brandEntity.getSceneNum());
            String talkHistoryStr = JSON.toJSONString(talkHistory);
            if(CollectionUtils.isEmpty(scenePvList) || CollectionUtils.isEmpty(sceneUvList)
                    || CollectionUtils.isEmpty(hotVisitList)){
                log.info("店铺[{}]四维看看返回pv,uv,hot数据为空，跳过" , brandAdmin.getBrandId());
                return Result.failure("四维看看返回pv,uv,hot数据为空");
            }
            if (null != tmSceneCensus) {
                tmSceneCensus.setPvHistory(JSON.toJSONString(scenePvList));
                tmSceneCensus.setUvHistory(JSON.toJSONString(sceneUvList));
                tmSceneCensus.setHotVisitHistory(JSON.toJSONString(hotVisitList));
                tmSceneCensus.setLastModifyDatetime(LocalDateTime.now());
                if(null == tmSceneCensus.getTotalTalkNum()){
                    tmSceneCensus.setTotalTalkNum(totalVisitTalk);
                }
                if(StringUtils.isBlank(tmSceneCensus.getTalkHistory())){
                    tmSceneCensus.setTalkHistory(talkHistoryStr);
                }
                tmSceneCensus.setCensusSize(size);
                //TODO:这里添加商品成交量、商品详情页PV的逻辑
                int update = sceneCensusService.updateCensus(tmSceneCensus);
                if (update != 1) {
                    log.warn("更新场景统计的pv,uv,hot历史数据失败");
                }
            } else {
                tmSceneCensus = new TmSceneCensus();
                tmSceneCensus.setCompanyId(brandEntity.getId().toString());
                tmSceneCensus.setCompanyName(brandEntity.getName());
                tmSceneCensus.setSceneNum(brandEntity.getSceneNum());
                tmSceneCensus.setCensusDate(finalStasticEndDate);
                tmSceneCensus.setPvHistory(JSON.toJSONString(scenePvList));
                if(!CollectionUtils.isEmpty(scenePvList)){
                    long scenePvTotalNum = 0;
                    for(int i = 0 ; i <scenePvList.size() ; i++){
                        Map<String, Object> mp = scenePvList.get(i);
                        if(!CollectionUtils.isEmpty(mp)){
                            for(Map.Entry entry : mp.entrySet()){
                                long num = null != entry.getValue() ? ((Integer) entry.getValue()).longValue() : 0;
                                scenePvTotalNum += num;
                            }
                        }
                    }
                    tmSceneCensus.setPvTotalNum(scenePvTotalNum);
                }
                tmSceneCensus.setUvHistory(JSON.toJSONString(sceneUvList));
                if(!CollectionUtils.isEmpty(sceneUvList)){
                    long sceneUvTotalNum = 0;
                    for(int i = 0 ; i <sceneUvList.size() ; i++){
                        Map<String, Object> mp = sceneUvList.get(i);
                        if(!CollectionUtils.isEmpty(mp)){
                            for(Map.Entry entry : mp.entrySet()){
                                long num = null != entry.getValue() ? ((Integer) entry.getValue()).longValue() : 0;
                                sceneUvTotalNum += num;
                            }
                        }
                    }
                    tmSceneCensus.setUvTotalNum(sceneUvTotalNum);
                }
                //TODO:这里添加商品成交量、商品详情页PV的逻辑
                tmSceneCensus.setHotVisitHistory(JSON.toJSONString(hotVisitList));
                tmSceneCensus.setLastModifyDatetime(LocalDateTime.now());
                tmSceneCensus.setCreateTime(LocalDateTime.now());
                tmSceneCensus.setCensusSize(size);
                tmSceneCensus.setTotalTalkNum(goodsVisitHistoryService.countTotalBySceneNum(brandEntity.getSceneNum()));
                tmSceneCensus.setTalkHistory(talkHistoryStr);
                int insert = sceneCensusService.addSceneCensus(tmSceneCensus);
                if (insert != 1) {
                    log.warn("新增场景统计失败");
                }
            }
        }else{
            log.info("店铺[{}]不存在或者店铺没有场景码，不返回起统计数据" , brandAdmin.getBrandId());
        }

        return Result.success(tmSceneCensus);
    }

    @CanUserUpdateRecord
    @ApiOperation(value = "增加询盘数量")
    @GetMapping("/addGoodsQueryNum")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "展品ID", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "viewId", value = "观众ID", paramType = "query", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "sceneNum", value = "场景码", paramType = "query", required = true, dataType = "String")
    })
    public Result addGoodsQueryNum(@RequestParam(name = "goodsId") Integer goodsId,
                                   @RequestParam(name = "viewId") Integer viewId,
                                   @RequestParam(name = "sceneNum") String sceneNum) {
        if (!StringUtils.isNoneBlank(sceneNum)) {
            throw new CommonBaseException(ResultCodeEnum.D3001);
        }
        BrandEntity brandEntity = brandService.queryByScene(sceneNum);
        if (null == brandEntity) {
            log.error("场景[{}]没有绑定公司", sceneNum);
            throw new CommonBaseException(ResultCodeEnum.D101, "场景没有绑定公司");
        }
        LocalDate today = LocalDate.now();
        //新增展品访问记录
        UserEntity tmViewer = userService.queryObject(viewId);
        String goodsIdStr = null != goodsId ? goodsId.toString() : "";
        String viewIdStr = null != viewId ? viewId.toString() : "";
        TmGoodsVisitHistory goodsVisitHistory  = new TmGoodsVisitHistory();
        goodsVisitHistory.setVisiterId(viewIdStr);
        goodsVisitHistory.setGoodsId(goodsIdStr);
        goodsVisitHistory.setVisitDate(today);
        if(null != tmViewer){
            goodsVisitHistory.setVisiterGender(tmViewer.getGender());
            goodsVisitHistory.setVisiterName(tmViewer.getNickname());
            goodsVisitHistory.setVisterRegion(tmViewer.getCity());
        }
        goodsVisitHistory.setSceneNum(sceneNum);
        goodsVisitHistoryService.addNewHistory(goodsVisitHistory);
        return Result.success();
    }

}
