package com.slodon.b2b2c.controller.statistics.seller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.slodon.b2b2c.business.example.OrderExample;
import com.slodon.b2b2c.business.example.OrderReturnExample;
import com.slodon.b2b2c.core.constant.*;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.enums.StatsConstant;
import com.slodon.b2b2c.enums.StatsTimeType;
import com.slodon.b2b2c.goods.example.GoodsExample;
import com.slodon.b2b2c.member.example.MemberEnquiryExample;
import com.slodon.b2b2c.member.pojo.MemberEnquiry;
import com.slodon.b2b2c.model.business.OrderModel;
import com.slodon.b2b2c.model.business.OrderReturnModel;
import com.slodon.b2b2c.model.goods.GoodsModel;
import com.slodon.b2b2c.model.member.advich.MemberEnquiryModel;
import com.slodon.b2b2c.model.system.BillModel;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.system.example.BillExample;
import com.slodon.b2b2c.util.SellerPresentDataUtil;
import com.slodon.b2b2c.util.StatsModelUtil;
import com.slodon.b2b2c.vo.member.MemberEnquiryVO;
import com.slodon.b2b2c.vo.statistics.*;
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.springframework.data.redis.core.RedisTemplate;
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.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "seller-概况")
@Slf4j
@RestController
@RequestMapping("v3/statistics/seller/overview/analysis")
public class SellerOverviewController extends BaseController {

    @Resource
    private StatsModelUtil statsModelUtil;
    @Resource
    private RedisTemplate<String, Object> objectRedisTemplate;
    @Resource
    private SellerPresentDataUtil sellerPresentDataUtil;
    @Resource
    private GoodsModel goodsModel;
    @Resource
    private OrderReturnModel orderReturnModel;
    @Resource
    private BillModel billModel;
    @Resource
    private OrderModel orderModel;
    @Resource
    private MemberEnquiryModel memberEnquiryModel;

    @ApiOperation("首页概况实时统计数据")
    @ApiImplicitParam(name = "webSite", value = "站点来源 1:海外站 2:国内站")
    @GetMapping("presentData")
    public JsonResult<SellerPresentIndexVO> indexPresentData(HttpServletRequest request, @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        SellerPresentDataVO sellerPresentDataVO;
        //查询缓存数据
        Object presentData = objectRedisTemplate.opsForHash().get(StatsConstant.SELLER_PRESENT_REDIS_KEY + "_" + webSite, vendor.getStoreId() + "");
        if (presentData == null) {
            //无缓存数据，重新计算实时统计，并缓存
            //截止当前时间
            Date endTime = new Date();
            //今日0时开始
            DateTime startTime = DateUtil.beginOfDay(endTime);

            //计算实时统计数据
            sellerPresentDataVO = sellerPresentDataUtil.calculatePresentData(startTime, endTime, webSite, vendor.getStoreId());

            //缓存数据
            objectRedisTemplate.opsForHash().put(StatsConstant.SELLER_PRESENT_REDIS_KEY + "_" + webSite, vendor.getStoreId() + "", sellerPresentDataVO);
        } else {
            sellerPresentDataVO = JSON.parseObject(JSON.toJSONString(presentData), SellerPresentDataVO.class);
        }

        SellerPresentIndexVO result = new SellerPresentIndexVO();
        result.setStatsTime(sellerPresentDataVO.getStatsTime());
        result.setSellerSummary(sellerPresentDataVO.getSellerSummary());
        result.setSellerTodaySummary(sellerPresentDataVO.getSellerTodaySummary());

        //待办事项
        SellerPresentIndexVO.SellerWaitDeal sellerWaitDeal = new SellerPresentIndexVO.SellerWaitDeal();
        //待发货订单数
        OrderExample orderExample = new OrderExample();
        orderExample.setStoreId(vendor.getStoreId());
        orderExample.setOrderState(OrderConst.ORDER_STATE_20);
        sellerWaitDeal.setDeliverOrderNum(orderModel.getOrderCount(orderExample));
        //正在进行的售后单数
        OrderReturnExample orderReturnExample = new OrderReturnExample();
        orderReturnExample.setStoreId(vendor.getStoreId());
        //过滤已拒绝和已完成
        orderReturnExample.setStateNotIn(OrdersAfsConst.RETURN_STATE_202 + "," + OrdersAfsConst.RETURN_STATE_300);
        sellerWaitDeal.setOrderReturnNum(orderReturnModel.getOrderReturnCount(orderReturnExample));
        //违规商品数
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setStoreId(vendor.getStoreId());
        goodsExample.setWebSite(webSite);
        goodsExample.setState(GoodsConst.GOODS_STATE_LOWER_BY_SYSTEM);
        goodsExample.setIsDelete(GoodsConst.GOODS_IS_DELETE_NO);
        sellerWaitDeal.setSysLowerGoodsNum(goodsModel.getGoodsCount(goodsExample));

//        //站点违规商品数
//        goodsExample = new GoodsExample();
//        goodsExample.setWebSite(webSite);
//        goodsExample.setStoreId(vendor.getStoreId());
//        goodsExample.setState(GoodsConst.GOODS_STATE_LOWER_BY_SYSTEM);
//        goodsExample.setIsDelete(GoodsConst.GOODS_IS_DELETE_NO);
//        sellerWaitDeal.setSysWebSiteLowerGoodsNum(goodsModel.getGoodsCount(goodsExample));

        //待确认结算单数
        BillExample billExample = new BillExample();
        billExample.setStoreId(vendor.getStoreId());
        billExample.setState(BillConst.STATE_1);
        sellerWaitDeal.setConfirmBillNum(billModel.getBillCount(billExample));

        //询盘数据
        List<String> itemTypes = new ArrayList<>();
        itemTypes.add(EnquiryConst.ENQUIRY_ITEM_TYPE_GOODS);
        itemTypes.add(EnquiryConst.ENQUIRY_ITEM_TYPE_SHOP);
        String itemTypeStr = StringUtil.listToString(itemTypes);

        //询盘总数
        MemberEnquiryExample memberEnquiryTotalExample = new MemberEnquiryExample();
        memberEnquiryTotalExample.setWebSite(webSite);
        memberEnquiryTotalExample.setStoreId(vendor.getStoreId());
        memberEnquiryTotalExample.setStatusNotEqual(EnquiryConst.ENQUIRY_DELETE);
        memberEnquiryTotalExample.setItemTypeIn(itemTypeStr);
        sellerWaitDeal.setEnquiryTotalNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryTotalExample));

        //新增询盘数
        Date enquiryEndTime = new Date();
        DateTime enquiryStartTime = DateUtil.beginOfDay(enquiryEndTime);
        MemberEnquiryExample memberEnquiryNewExample = new MemberEnquiryExample();
        memberEnquiryNewExample.setWebSite(webSite);
        memberEnquiryNewExample.setStoreId(vendor.getStoreId());
        memberEnquiryNewExample.setCreateTimeGte(com.slodon.b2b2c.core.util.DateUtil.dateToString(enquiryStartTime, com.slodon.b2b2c.core.util.DateUtil.DATE_FORMAT_FIVE));
        memberEnquiryNewExample.setCreateTimeLte(com.slodon.b2b2c.core.util.DateUtil.dateToString(enquiryEndTime, com.slodon.b2b2c.core.util.DateUtil.DATE_FORMAT_FIVE));
        memberEnquiryNewExample.setStatusNotEqual(EnquiryConst.ENQUIRY_DELETE);
        memberEnquiryNewExample.setItemTypeIn(itemTypeStr);
        sellerWaitDeal.setEnquiryNewNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryNewExample));

        //有效询盘数
        MemberEnquiryExample memberEnquiryValidExample = new MemberEnquiryExample();
        memberEnquiryValidExample.setWebSite(webSite);
        memberEnquiryValidExample.setStoreId(vendor.getStoreId());
        memberEnquiryValidExample.setValidStatus(EnquiryConst.ENQUIRY_VALID);
        memberEnquiryValidExample.setStatusNotEqual(EnquiryConst.ENQUIRY_DELETE);
        memberEnquiryValidExample.setItemTypeIn(itemTypeStr);
        sellerWaitDeal.setValidInquiryNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryValidExample));

        //待分配询盘数
        MemberEnquiryExample memberEnquiryToAssignExample = new MemberEnquiryExample();
        memberEnquiryToAssignExample.setWebSite(webSite);
        memberEnquiryToAssignExample.setStoreId(vendor.getStoreId());
        memberEnquiryToAssignExample.setStatusEqual(EnquiryConst.ENQUIRY_NEW);
        memberEnquiryToAssignExample.setItemTypeIn(itemTypeStr);
        sellerWaitDeal.setEnquiryToBeAssignNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryToAssignExample));

//        //站点待分配询盘数
//        memberEnquiryToAssignExample = new MemberEnquiryExample();
//        memberEnquiryToAssignExample.setWebSite(webSite);
//        memberEnquiryToAssignExample.setStoreId(vendor.getStoreId());
//        memberEnquiryToAssignExample.setStatusEqual(EnquiryConst.ENQUIRY_NEW);
//        memberEnquiryToAssignExample.setItemTypeIn(itemTypeStr);
//        sellerWaitDeal.setWebSiteEnquiryToBeAssignNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryToAssignExample));

        result.setSellerWaitDeal(sellerWaitDeal);

        return SldResponse.success(result);
    }

    @ApiOperation("支付或下单金额趋势")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "webSite", value = "站点来源 1:海外站 2:国内站")
    })
    @GetMapping("payOrderTrend")
    public JsonResult<PlatformSalesVO> payOrderTrend(HttpServletRequest request, Date startTime, Date endTime, @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, true);
        List<MovableGoodsVO> list = statsModelUtil.getStoreTrendList(timeType, startTime, endTime, webSite, vendor.getStoreId());
        PlatformSalesVO vo = new PlatformSalesVO();
        //支付金额列表
        List<PlatformSalesVO.PayAmountVO> payAmountList = new ArrayList<>();
        //下单金额列表
        List<PlatformSalesVO.OrderAmountVO> orderAmountList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(trendVO -> {
                //支付金额
                PlatformSalesVO.PayAmountVO payAmountVO = new PlatformSalesVO.PayAmountVO();
                payAmountVO.setStatsTime(trendVO.getStatsTime());
                payAmountVO.setOrderPayAmount(trendVO.getOrderPayAmount());
                payAmountList.add(payAmountVO);
                //下单金额
                PlatformSalesVO.OrderAmountVO orderAmountVO = new PlatformSalesVO.OrderAmountVO();
                orderAmountVO.setStatsTime(trendVO.getStatsTime());
                orderAmountVO.setOrderSubmitAmount(trendVO.getOrderSubmitAmount());
                orderAmountList.add(orderAmountVO);
            });
            vo.setPayAmountList(payAmountList);
            vo.setOrderAmountList(orderAmountList);
        }
        return SldResponse.success(vo);
    }

    @ApiOperation("流量趋势")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "webSite", value = "站点来源 1:海外站 2:国内站")
    })
    @GetMapping("flowTrend")
    public JsonResult<FlowTrendVO> flowTrend(HttpServletRequest request, Date startTime, Date endTime, @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, true);
        List<MovableGoodsVO> list = statsModelUtil.getStoreTrendList(timeType, startTime, endTime, webSite, vendor.getStoreId());
        FlowTrendVO vo = new FlowTrendVO();
        //访客数列表
        List<FlowTrendVO.VisitorNumVO> visitorNumList = new ArrayList<>();
        //访问量列表
        List<FlowTrendVO.ViewNumVO> viewNumList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(trendVO -> {
                //访客数
                FlowTrendVO.VisitorNumVO visitorNumVO = new FlowTrendVO.VisitorNumVO();
                visitorNumVO.setStatsTime(trendVO.getStatsTime());
                visitorNumVO.setVisitorNum(trendVO.getVisitorNum());
                visitorNumList.add(visitorNumVO);
                //访问量
                FlowTrendVO.ViewNumVO viewNumVO = new FlowTrendVO.ViewNumVO();
                viewNumVO.setStatsTime(trendVO.getStatsTime());
                viewNumVO.setViewNum(trendVO.getViewNum());
                viewNumList.add(viewNumVO);
            });
            vo.setVisitorNumList(visitorNumList);
            vo.setViewNumList(viewNumList);
        }
        return SldResponse.success(vo);
    }

    /**
     * 询盘趋势
     *
     * @param request
     * @param startTime
     * @param endTime
     * @return
     */
    @GetMapping("enquiryTrend")
    @ApiImplicitParam(name = "webSite", value = "站点来源 1:海外站 2:国内站")
    public JsonResult<EnquiryTrendVO> getEnquiryTrend(HttpServletRequest request, Date startTime, Date endTime, @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) throws Exception {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        EnquiryTrendVO vo = new EnquiryTrendVO();
        if (startTime != null && endTime != null) {
            StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, true);
            List<MemberEnquiry> list = memberEnquiryModel.getSellerEnquiryTrendList(timeType, startTime, endTime, webSite, vendor.getStoreId());
            List<EnquiryTrendVO.EnquiryNumVO> enquiryNumVOList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(list)) {
                list.forEach(memberEnquiry -> {
                    EnquiryTrendVO.EnquiryNumVO enquiryNumVO = new EnquiryTrendVO.EnquiryNumVO();
                    enquiryNumVO.setStatsTime(memberEnquiry.getEnquiryDay());
                    enquiryNumVO.setViewNum(memberEnquiry.getEnquiryNum());
                    enquiryNumVOList.add(enquiryNumVO);
                });
                vo.setEnquiryTrendList(enquiryNumVOList);
            }
        }
        return SldResponse.success(vo);
    }

}
