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

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
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.enums.StatsConstant;
import com.slodon.b2b2c.enums.StatsTimeType;
import com.slodon.b2b2c.goods.example.GoodsBrandExample;
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.OrderReturnModel;
import com.slodon.b2b2c.model.goods.GoodsBrandModel;
import com.slodon.b2b2c.model.goods.GoodsModel;
import com.slodon.b2b2c.model.member.advich.MemberEnquiryModel;
import com.slodon.b2b2c.model.seller.StoreApplyModel;
import com.slodon.b2b2c.model.statistics.BrandDayModel;
import com.slodon.b2b2c.model.system.BillModel;
import com.slodon.b2b2c.seller.example.StoreApplyExample;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.statistics.example.BrandDayExample;
import com.slodon.b2b2c.statistics.pojo.base.BrandBase;
import com.slodon.b2b2c.statistics.pojo.base.CategoryBase;
import com.slodon.b2b2c.system.example.BillExample;
import com.slodon.b2b2c.util.PlatformPresentDataUtil;
import com.slodon.b2b2c.util.StatsModelUtil;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author slodon
 */
@Api(tags = "admin-概况")
@RestController
@RequestMapping("v3/statistics/admin/overview/analysis")
@Slf4j
public class AdminOverviewController extends BaseController {

    @Resource
    private BrandDayModel brandDayModel;
    @Resource
    private StatsModelUtil statsModelUtil;
    @Resource
    private RedisTemplate<String, Object> objectRedisTemplate;
    @Resource
    private PlatformPresentDataUtil platformPresentDataUtil;
    @Resource
    private StoreApplyModel storeApplyModel;
    @Resource
    private GoodsModel goodsModel;
    @Resource
    private GoodsBrandModel goodsBrandModel;
    @Resource
    private OrderReturnModel orderReturnModel;
    @Resource
    private BillModel billModel;
    @Resource
    private MemberEnquiryModel memberEnquiryModel;

    @ApiOperation("首页概况-待办事项")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("waitDeal")
    public JsonResult<AdminPresentIndexVO.AdminWaitDeal> waitDeal(HttpServletRequest request,@RequestParam(value = "webSite", required = false,defaultValue = "1") String webSite) {
        //待办事项
        AdminPresentIndexVO.AdminWaitDeal adminWaitDeal = new AdminPresentIndexVO.AdminWaitDeal();
        //待审核店铺
        StoreApplyExample storeApplyExample = new StoreApplyExample();
        storeApplyExample.setState(StoreConst.STATE_1_SEND_APPLY);
        adminWaitDeal.setAuditStoreNum(storeApplyModel.getStoreApplyCount(storeApplyExample));
        //待审核商品
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.setStateIn(GoodsConst.GOODS_STATE_SELL_NOW_TO_AUDIT + "," + GoodsConst.GOODS_STATE_WAREHOUSE_TO_AUDIT);
        adminWaitDeal.setAuditGoodsNum(goodsModel.getGoodsCount(goodsExample));

        //站点待审核商品
        goodsExample = new GoodsExample();
        goodsExample.setWebSite(webSite);
        goodsExample.setStateIn(GoodsConst.GOODS_STATE_SELL_NOW_TO_AUDIT + "," + GoodsConst.GOODS_STATE_WAREHOUSE_TO_AUDIT);
        adminWaitDeal.setWebSiteAuditGoodsNum(goodsModel.getGoodsCount(goodsExample));

        //站点待审核店铺
        storeApplyExample = new StoreApplyExample();
        goodsExample.setWebSite(webSite);
        storeApplyExample.setState(StoreConst.STATE_1_SEND_APPLY);
        adminWaitDeal.setWebSiteAuditStoreNum(storeApplyModel.getStoreApplyCount(storeApplyExample));

        //待审核品牌
        GoodsBrandExample goodsBrandExample = new GoodsBrandExample();
        goodsBrandExample.setState(GoodsConst.BRAND_STATE_2);
        adminWaitDeal.setAuditBrandNum(goodsBrandModel.getBrandCount(goodsBrandExample));

        //站点待审核品牌
        goodsBrandExample = new GoodsBrandExample();
        goodsBrandExample.setWebSite(webSite);
        goodsBrandExample.setState(GoodsConst.BRAND_STATE_2);
        adminWaitDeal.setWebSiteAuditBrandNum(goodsBrandModel.getBrandCount(goodsBrandExample));

        //待确认退款单
        OrderReturnExample orderReturnExample = new OrderReturnExample();
        orderReturnExample.setStateIn(OrdersAfsConst.RETURN_STATE_200 + "," + OrdersAfsConst.RETURN_STATE_203);
        adminWaitDeal.setConfirmReturnNum(orderReturnModel.getOrderReturnCount(orderReturnExample));
        //待处理结算单
        BillExample billExample = new BillExample();
        //待审核和待打款
        billExample.setStateIn(BillConst.STATE_2 + "," + BillConst.STATE_3);
        adminWaitDeal.setDealBillNum(billModel.getBillCount(billExample));
        //待分配询盘数
        MemberEnquiryExample memberEnquiryToAssignExample = new MemberEnquiryExample();
        memberEnquiryToAssignExample.setStatusEqual(EnquiryConst.ENQUIRY_NEW);
        memberEnquiryToAssignExample.setItemType(EnquiryConst.ENQUIRY_ITEM_TYPE_MALL);
        adminWaitDeal.setEnquiryToBeAssignNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryToAssignExample));

        //站点待分配询盘数
        memberEnquiryToAssignExample = new MemberEnquiryExample();
        memberEnquiryToAssignExample.setWebSite(webSite);
        memberEnquiryToAssignExample.setStatusEqual(EnquiryConst.ENQUIRY_NEW);
        memberEnquiryToAssignExample.setItemType(EnquiryConst.ENQUIRY_ITEM_TYPE_MALL);
        adminWaitDeal.setWebSiteEnquiryToBeAssignNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryToAssignExample));

        return SldResponse.success(adminWaitDeal);
    }

    @ApiOperation("首页概况-今日交易概况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "refresh", value = "true-刷新,默认false", defaultValue = "false"),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("tradeInfo")
    public JsonResult<AdminPresentIndexVO.AdminTradeInfo> tradeInfo(HttpServletRequest request,
                                                                    @RequestParam(value = "refresh", required = false, defaultValue = "false") Boolean refresh,
                                                                    @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        AdminPresentDataVO adminPresentDataVO;
        if (refresh) {
            //刷新请求，重新计算实时统计，并缓存
            //截止当前时间
            Date endTime = new Date();
            //今日0时开始
            DateTime startTime = DateUtil.beginOfDay(endTime);

            //计算实时统计数据
            adminPresentDataVO = platformPresentDataUtil.calculatePresentData(startTime, endTime, webSite);

            //缓存数据
            objectRedisTemplate.opsForHash().put(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, adminPresentDataVO);
        } else {
            //查询缓存数据
            Object presentData = objectRedisTemplate.opsForHash().get(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite);
            if (presentData == null) {
                //无缓存数据，重新计算实时统计，并缓存
                //截止当前时间
                Date endTime = new Date();
                //今日0时开始
                DateTime startTime = DateUtil.beginOfDay(endTime);

                //计算实时统计数据
                adminPresentDataVO = platformPresentDataUtil.calculatePresentData(startTime, endTime, webSite);

                //缓存数据
                objectRedisTemplate.opsForHash().put(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, adminPresentDataVO);
            } else {
                //有缓存数据
                adminPresentDataVO = JSON.parseObject(JSON.toJSONString(presentData), AdminPresentDataVO.class);
            }
        }

        return SldResponse.success(new AdminPresentIndexVO.AdminTradeInfo(adminPresentDataVO));
    }

    @ApiOperation("首页概况-今日流量概况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "refresh", value = "true-刷新,默认false", defaultValue = "false"),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("viewInfo")
    public JsonResult<AdminPresentIndexVO.AdminViewInfo> viewInfo(HttpServletRequest request,
                                                                  @RequestParam(value = "refresh", required = false, defaultValue = "false") Boolean refresh,
                                                                  @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        AdminPresentDataVO adminPresentDataVO;
        if (refresh) {
            //刷新请求，重新计算实时统计，并缓存
            //截止当前时间
            Date endTime = new Date();
            //今日0时开始
            DateTime startTime = DateUtil.beginOfDay(endTime);

            //计算实时统计数据
            adminPresentDataVO = platformPresentDataUtil.calculatePresentData(startTime, endTime, webSite);

            //缓存数据
            objectRedisTemplate.opsForHash().put(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, adminPresentDataVO);
        } else {
            //查询缓存数据
            Object presentData = objectRedisTemplate.opsForHash().get(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite);
            if (presentData == null) {
                //无缓存数据，重新计算实时统计，并缓存
                //截止当前时间
                Date endTime = new Date();
                //今日0时开始
                DateTime startTime = DateUtil.beginOfDay(endTime);

                //计算实时统计数据
                adminPresentDataVO = platformPresentDataUtil.calculatePresentData(startTime, endTime, webSite);

                //缓存数据
                objectRedisTemplate.opsForHash().put(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, adminPresentDataVO);
            } else {
                //有缓存数据
                adminPresentDataVO = JSON.parseObject(JSON.toJSONString(presentData), AdminPresentDataVO.class);
            }
        }

        return SldResponse.success(new AdminPresentIndexVO.AdminViewInfo(adminPresentDataVO));
    }

    @ApiOperation("首页概况-今日商品概况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "refresh", value = "true-刷新,默认false", defaultValue = "false"),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("goodsInfo")
    public JsonResult<AdminPresentIndexVO.AdminGoodsInfo> goodsInfo(HttpServletRequest request,
                                                                    @RequestParam(value = "refresh", required = false, defaultValue = "false") Boolean refresh,
                                                                    @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        AdminPresentDataVO adminPresentDataVO;
        if (refresh) {
            //刷新请求，重新计算实时统计，并缓存
            //截止当前时间
            Date endTime = new Date();
            //今日0时开始
            DateTime startTime = DateUtil.beginOfDay(endTime);

            //计算实时统计数据
            adminPresentDataVO = platformPresentDataUtil.calculatePresentData(startTime, endTime,webSite);

            //缓存数据
            objectRedisTemplate.opsForHash().put(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, adminPresentDataVO);
        } else {
            //查询缓存数据
            Object presentData = objectRedisTemplate.opsForHash().get(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite);
            if (presentData == null) {
                //无缓存数据，重新计算实时统计，并缓存
                //截止当前时间
                Date endTime = new Date();
                //今日0时开始
                DateTime startTime = DateUtil.beginOfDay(endTime);

                //计算实时统计数据
                adminPresentDataVO = platformPresentDataUtil.calculatePresentData(startTime, endTime,webSite);

                //缓存数据
                objectRedisTemplate.opsForHash().put(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, adminPresentDataVO);
            } else {
                //有缓存数据
                adminPresentDataVO = JSON.parseObject(JSON.toJSONString(presentData), AdminPresentDataVO.class);
            }
        }

        return SldResponse.success(new AdminPresentIndexVO.AdminGoodsInfo(adminPresentDataVO));
    }

    @ApiOperation("首页概况-今日用户概况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "refresh", value = "true-刷新,默认false", defaultValue = "false"),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("userInfo")
    public JsonResult<AdminPresentIndexVO.AdminUserInfo> userInfo(HttpServletRequest request,
                                                                  @RequestParam(value = "refresh", required = false, defaultValue = "false") Boolean refresh,
                                                                  @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        AdminPresentDataVO adminPresentDataVO;
        if (refresh) {
            //刷新请求，重新计算实时统计，并缓存
            //截止当前时间
            Date endTime = new Date();
            //今日0时开始
            DateTime startTime = DateUtil.beginOfDay(endTime);

            //计算实时统计数据
            adminPresentDataVO = platformPresentDataUtil.calculatePresentData(startTime, endTime,webSite);

            //缓存数据
            objectRedisTemplate.opsForHash().put(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, adminPresentDataVO);
        } else {
            //查询缓存数据
            Object presentData = objectRedisTemplate.opsForHash().get(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite);
            if (presentData == null) {
                //无缓存数据，重新计算实时统计，并缓存
                //截止当前时间
                Date endTime = new Date();
                //今日0时开始
                DateTime startTime = DateUtil.beginOfDay(endTime);

                //计算实时统计数据
                adminPresentDataVO = platformPresentDataUtil.calculatePresentData(startTime, endTime,webSite);

                //缓存数据
                objectRedisTemplate.opsForHash().put(StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, StatsConstant.ADMIN_PRESENT_REDIS_KEY + "_" + webSite, adminPresentDataVO);
            } else {
                //有缓存数据
                adminPresentDataVO = JSON.parseObject(JSON.toJSONString(presentData), AdminPresentDataVO.class);
            }
        }

        return SldResponse.success(new AdminPresentIndexVO.AdminUserInfo(adminPresentDataVO));
    }

    @ApiOperation("支付或下单金额趋势")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("payOrderTrend")
    public JsonResult<PlatformSalesVO> payOrderTrend(HttpServletRequest request, Date startTime, Date endTime,@RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, true);
        List<MovableGoodsVO> list = statsModelUtil.getPlatformTrendList(timeType, startTime, endTime, webSite);
        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 = "站点")
    })
    @GetMapping("flowTrend")
    public JsonResult<FlowTrendVO> flowTrend(HttpServletRequest request, Date startTime, Date endTime, @RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, true);
        List<MovableGoodsVO> list = statsModelUtil.getPlatformTrendList(timeType, startTime, endTime, webSite);
        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);
    }

    @ApiOperation("会员或店铺新增趋势")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("newTrend")
    public JsonResult<PlatformTrendVO> newTrend(HttpServletRequest request, Date startTime, Date endTime,@RequestParam(value = "webSite", required = false, defaultValue = "1") String webSite) {
        StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, true);
        List<MovableGoodsVO> list = statsModelUtil.getPlatformTrendList(timeType, startTime, endTime, webSite);
        PlatformTrendVO vo = new PlatformTrendVO();
        //新增会员数列表
        List<PlatformTrendVO.NewMemberNumVO> memberList = new ArrayList<>();
        //新增店铺数列表
        List<PlatformTrendVO.NewStoreNumVO> storeList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(trendVO -> {
                //新增会员数
                PlatformTrendVO.NewMemberNumVO memberNumVO = new PlatformTrendVO.NewMemberNumVO();
                memberNumVO.setStatsTime(trendVO.getStatsTime());
                memberNumVO.setNewMemberNum(trendVO.getNewMemberNum());
                memberList.add(memberNumVO);
                //新增店铺数
                PlatformTrendVO.NewStoreNumVO storeNumVO = new PlatformTrendVO.NewStoreNumVO();
                storeNumVO.setStatsTime(trendVO.getStatsTime());
                storeNumVO.setNewStoreNum(trendVO.getNewStoreNum());
                storeList.add(storeNumVO);
            });
            vo.setMemberList(memberList);
            vo.setStoreList(storeList);
        }
        return SldResponse.success(vo);
    }

    @ApiOperation("品类销售排行-TOP10")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "sort", value = "排序:1-销售额；2-销量 默认不传按销售额降序")
    })
    @GetMapping("categoryRank")
    public JsonResult<List<CategoryRankVO>> categoryRank(HttpServletRequest request, Date startTime, Date endTime, Integer sort) {
        StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, false);
        List<? extends CategoryBase> list = statsModelUtil.getCategoryList(timeType, startTime, endTime, sort, "sale");
        List<CategoryRankVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(categoryBase -> {
                //销量和销售额二者必须有一个满足条件
                if (categoryBase.getSaleNum() > 0 || categoryBase.getSaleAmount().compareTo(BigDecimal.ZERO) > 0) {
                    vos.add(new CategoryRankVO(categoryBase));
                }
            });
        }
        return SldResponse.success(vos);
    }

    @ApiOperation("品牌销售占比")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "webSite", value = "站点"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "sort", value = "排序:1-销售额；2-销量 默认不传按销售额降序")
    })
    @GetMapping("brandSalesPercent")
    public JsonResult<BrandPercentVO> brandSalesPercent(HttpServletRequest request,String webSite, Date startTime, Date endTime, Integer sort) {
        StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, false);
        List<? extends BrandBase> list;
        if (timeType.equals(StatsTimeType.DAY)) {
            BrandDayExample example = new BrandDayExample();
            example.setStatsTimeAfter(startTime);
            example.setStatsTimeBefore(endTime);
            example.setWebSite(webSite);
            if (!StringUtil.isNullOrZero(sort) && sort == 2) {
                example.setOrderBy("saleNum DESC");
            } else {
                example.setOrderBy("saleAmount DESC");
            }
            list = brandDayModel.getBrandList(example, null);
        } else {
            list = statsModelUtil.getBrandList(timeType, webSite, startTime, endTime, sort, null);
        }
        BrandPercentVO vo = getBrandSalesPercent(list);
        return SldResponse.success(vo);
    }

    /**
     * 品牌销售占比
     *
     * @param list 品牌列表
     */
    public BrandPercentVO getBrandSalesPercent(List<? extends BrandBase> list) {
        BrandPercentVO result = new BrandPercentVO();
        //销售额列表
        List<BrandPercentVO.SaleAmountVO> saleAmountList = new ArrayList<>();
        //销量列表
        List<BrandPercentVO.SaleNumVO> saleNumList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            //总销量，用于计算各省份占比
            Integer totalNum = 0;
            //总销售额，用于计算各省份占比
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (BrandBase brandBase : list) {
                totalNum += brandBase.getSaleNum();
                totalAmount = totalAmount.add(brandBase.getSaleAmount());
            }
            if (totalNum == 0 && totalAmount.compareTo(BigDecimal.ZERO) == 0) {
                return result;
            }

            //循环列表,构造返回数据
            if (list.size() <= 10) {
                //省份少于等于10个，直接记录各省份的销售占比
                for (BrandBase brandBase : list) {
                    if (totalNum != 0 && brandBase.getSaleNum() != 0) {
                        BrandPercentVO.SaleNumVO vo = new BrandPercentVO.SaleNumVO();
                        vo.setBrandName(brandBase.getBrandName());
                        vo.setSaleNum(brandBase.getSaleNum());
                        BigDecimal numPer = new BigDecimal(brandBase.getSaleNum()).multiply(new BigDecimal(100)).divide(new BigDecimal(totalNum), 2, BigDecimal.ROUND_HALF_UP);
                        vo.setSaleNumPercent(numPer.toString() + "%");
                        saleNumList.add(vo);
                    }
                    if (totalAmount.compareTo(BigDecimal.ZERO) != 0 && brandBase.getSaleAmount().compareTo(BigDecimal.ZERO) != 0) {
                        BrandPercentVO.SaleAmountVO vo = new BrandPercentVO.SaleAmountVO();
                        vo.setBrandName(brandBase.getBrandName());
                        vo.setSaleAmount(brandBase.getSaleAmount());
                        BigDecimal per = brandBase.getSaleAmount().multiply(new BigDecimal(100)).divide(totalAmount, 2, BigDecimal.ROUND_HALF_UP);
                        vo.setSaleAmountPercent(per.toString() + "%");
                        saleAmountList.add(vo);
                    }
                }
            } else {
                //省份大于10，记录前10个，剩余记为其他
                //其他省份金额
                int otherNum = totalNum;
                BigDecimal otherAmount = totalAmount;
                //其他省份占比
                BigDecimal otherNumPer = new BigDecimal(100);
                BigDecimal otherPer = new BigDecimal(100);
                for (int i = 0; i < list.size() && i < 10; i++) {
                    BrandBase brandBase = list.get(i);

                    Integer saleNum = brandBase.getSaleNum();
                    BigDecimal saleAmount = brandBase.getSaleAmount();

                    if (totalNum != 0 && saleNum != 0) {
                        BrandPercentVO.SaleNumVO vo = new BrandPercentVO.SaleNumVO();
                        vo.setBrandName(brandBase.getBrandName());
                        vo.setSaleNum(saleNum);
                        BigDecimal numPer = new BigDecimal(saleNum).multiply(new BigDecimal(100)).divide(new BigDecimal(totalNum), 2, BigDecimal.ROUND_HALF_UP);
                        vo.setSaleNumPercent(numPer.toString() + "%");
                        saleNumList.add(vo);

                        //数据计算
                        otherNum = otherNum - saleNum;
                        otherNumPer = otherNumPer.subtract(numPer);
                    }
                    if (totalAmount.compareTo(BigDecimal.ZERO) != 0 && saleAmount.compareTo(BigDecimal.ZERO) != 0) {
                        BrandPercentVO.SaleAmountVO vo = new BrandPercentVO.SaleAmountVO();
                        vo.setBrandName(brandBase.getBrandName());
                        vo.setSaleAmount(saleAmount);
                        BigDecimal per = saleAmount.multiply(new BigDecimal(100)).divide(totalAmount, 2, BigDecimal.ROUND_HALF_UP);
                        vo.setSaleAmountPercent(per.toString() + "%");
                        saleAmountList.add(vo);

                        //数据计算
                        otherAmount = otherAmount.subtract(saleAmount);
                        otherPer = otherPer.subtract(per);
                    }
                }
                //其他
                if (otherNum > 0) {
                    BrandPercentVO.SaleNumVO saleNumVO = new BrandPercentVO.SaleNumVO();
                    saleNumVO.setBrandName("其他");
                    saleNumVO.setSaleNum(otherNum);
                    saleNumVO.setSaleNumPercent(otherNumPer.toString() + "%");
                    saleNumList.add(saleNumVO);
                }

                if (otherAmount.compareTo(BigDecimal.ZERO) > 0) {
                    BrandPercentVO.SaleAmountVO saleAmountVO = new BrandPercentVO.SaleAmountVO();
                    saleAmountVO.setBrandName("其他");
                    saleAmountVO.setSaleAmount(otherAmount);
                    saleAmountVO.setSaleAmountPercent(otherPer.toString() + "%");
                    saleAmountList.add(saleAmountVO);
                }
            }
            result.setSaleAmountList(saleAmountList);
            result.setSaleNumList(saleNumList);
        }
        return result;
    }

    /**
     * 首页概况-今日询盘概况
     *
     * @param request
     * @param refresh
     * @return
     */
    @ApiOperation("首页概况-今日询盘概况")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "refresh", value = "true-刷新,默认false", defaultValue = "false"),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("enquiryInfo")
    public JsonResult<AdminPresentIndexVO.AdminEnquiryInfo> enquiryInfo(HttpServletRequest request,
                                                                        @RequestParam(value = "refresh", required = false, defaultValue = "false") Boolean refresh,
                                                                        @RequestParam(value = "webSite", required = false,defaultValue ="1") String webSite) {
        AdminPresentDataVO.PlatformEnquiryTodayInfo platformEnquiryTodayInfo = new AdminPresentDataVO.PlatformEnquiryTodayInfo();

        Date now = new Date();
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(now);
        cal1.set(Calendar.MINUTE, 0);
        cal1.set(Calendar.SECOND, 0);
        cal1.set(Calendar.MILLISECOND, 0);
        Date endTime = com.slodon.b2b2c.core.util.DateUtil.formatDate(cal1.getTime(), com.slodon.b2b2c.core.util.DateUtil.DATE_FORMAT_FIVE);
        platformEnquiryTodayInfo.setStatsTime(endTime);

        //询盘总数
        MemberEnquiryExample memberEnquiryTotalExample = new MemberEnquiryExample();
        memberEnquiryTotalExample.setWebSite(webSite);
        memberEnquiryTotalExample.setStatusNotEqual(EnquiryConst.ENQUIRY_DELETE);
        memberEnquiryTotalExample.setItemType(EnquiryConst.ENQUIRY_ITEM_TYPE_MALL);
        platformEnquiryTodayInfo.setEnquiryTotalNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryTotalExample));

        //新增询盘数
        Date enquiryEndTime = new Date();
        DateTime enquiryStartTime = DateUtil.beginOfDay(enquiryEndTime);
        MemberEnquiryExample memberEnquiryNewExample = new MemberEnquiryExample();
        memberEnquiryNewExample.setWebSite(webSite);
        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.setItemType(EnquiryConst.ENQUIRY_ITEM_TYPE_MALL);
        platformEnquiryTodayInfo.setEnquiryNewNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryNewExample));

        //有效询盘数
        MemberEnquiryExample memberEnquiryValidExample = new MemberEnquiryExample();
        memberEnquiryValidExample.setWebSite(webSite);
        memberEnquiryValidExample.setValidStatus(EnquiryConst.ENQUIRY_VALID);
        memberEnquiryValidExample.setStatusNotEqual(EnquiryConst.ENQUIRY_DELETE);
        memberEnquiryValidExample.setItemType(EnquiryConst.ENQUIRY_ITEM_TYPE_MALL);
        platformEnquiryTodayInfo.setValidInquiryNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryValidExample));

        //待分配询盘数
        MemberEnquiryExample memberEnquiryToAssignExample = new MemberEnquiryExample();
        memberEnquiryToAssignExample.setWebSite(webSite);
        memberEnquiryToAssignExample.setStatusEqual(EnquiryConst.ENQUIRY_NEW);
        memberEnquiryToAssignExample.setItemType(EnquiryConst.ENQUIRY_ITEM_TYPE_MALL);
        platformEnquiryTodayInfo.setEnquiryToBeAssignNum(memberEnquiryModel.getMemberEnquiryCount(memberEnquiryToAssignExample));
        return SldResponse.success(new AdminPresentIndexVO.AdminEnquiryInfo(platformEnquiryTodayInfo));
    }

    /**
     * 询盘趋势
     *
     * @param request
     * @param startTime
     * @param endTime
     * @return
     */
    @ApiImplicitParam(name = "webSite", value = "站点")
    @GetMapping("enquiryTrend")
    public JsonResult<EnquiryTrendVO> getEnquiryTrend(HttpServletRequest request, Date startTime, Date endTime,@RequestParam(value = "webSite", required = false,defaultValue = "1")String webSite) throws Exception {
        EnquiryTrendVO vo = new EnquiryTrendVO();
        if (startTime != null && endTime != null) {
            StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, true);
            List<MemberEnquiry> list = memberEnquiryModel.getAdminEnquiryTrendList(timeType, startTime, endTime,webSite);
            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);
    }
}
