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

import cn.hutool.core.date.DateUtil;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.UserUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.enums.StatsTimeType;
import com.slodon.b2b2c.model.statistics.StoreDayModel;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.statistics.example.StoreDayExample;
import com.slodon.b2b2c.statistics.pojo.StoreDay;
import com.slodon.b2b2c.statistics.pojo.base.GoodsBase;
import com.slodon.b2b2c.statistics.pojo.base.StoreBase;
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 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 javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Api(tags = "seller-交易分析")
@RestController
@RequestMapping("v3/statistics/seller/trade/analysis")
public class SellerTradeAnalysisController extends BaseController {

    @Resource
    private StoreDayModel storeDayModel;
    @Resource
    private StatsModelUtil statsModelUtil;

    @ApiOperation("交易总览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("tradeOverview")
    public JsonResult<TradeOverviewVO> tradeOverview(HttpServletRequest request, Date startTime, Date endTime,@RequestParam(name = "webSite", required = false,defaultValue = "1") String webSite) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, false);
        TradeOverviewVO vo = new TradeOverviewVO();
        List<? extends StoreBase> list = statsModelUtil.getStoreList(timeType, startTime, endTime, webSite,1, "sale", vendor.getStoreId(), null);
        if (!CollectionUtils.isEmpty(list)) {
            StoreBase storeBase = list.get(0);
            //上期数据
            StoreBase previousData = null;
            Date preStartTime;
            Date preEndTime;
            int differentDay = StatsTimeType.getDifferentDay(startTime, endTime);
            if (timeType == StatsTimeType.DAY && differentDay != 1) {
                preStartTime = StatsTimeType.getPreStartTime(startTime, differentDay);
                preEndTime = StatsTimeType.getPreEndTime(endTime, differentDay);
            } else {
                preStartTime = StatsTimeType.getStartTime(startTime, timeType);
                preEndTime = StatsTimeType.getEndTime(endTime, timeType);
            }
            if (preStartTime != null) {
                List<? extends StoreBase> previousList = statsModelUtil.getStoreList(timeType, preStartTime, preEndTime, webSite,1, "sale", vendor.getStoreId(), null);
                if (!CollectionUtils.isEmpty(previousList)) {
                    previousData = previousList.get(0);
                }
            }
            if (storeBase != null) {
                vo = new TradeOverviewVO(storeBase, previousData);
            }
        }
        return SldResponse.success(vo);
    }

    @ApiOperation("近30天变化趋势")
    @GetMapping("changeTrend")
    public JsonResult<List<ChangeTrendVO>> changeTrend(HttpServletRequest request) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        //获取当前时间30天之前的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -30);
        Date startTime = DateUtil.beginOfDay(calendar.getTime());
        StoreDayExample example = new StoreDayExample();
        example.setStatsTimeAfter(startTime);
        example.setStoreId(vendor.getStoreId());
        example.setOrderBy("stats_time ASC");
        List<StoreDay> list = storeDayModel.getStoreDayList(example, null);
        List<ChangeTrendVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(storeDay -> {
                vos.add(new ChangeTrendVO(storeDay));
            });
        }
        return SldResponse.success(vos);
    }

    @ApiOperation("商品销售排行-TOP10")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name="webSite",value = "站点"),
            @ApiImplicitParam(name = "sort", value = "排序:1-销售额；2-销量 默认不传按销售额降序")
    })
    @GetMapping("goodsSalesRank")
    public JsonResult<List<GoodsRankVO>> goodsSalesRank(HttpServletRequest request, Date startTime, Date endTime,@RequestParam(name = "webSite", required = false,defaultValue = "1") String webSite, Integer sort) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        StatsTimeType timeType = StatsTimeType.checkTimeType(startTime, endTime, false);
        List<? extends GoodsBase> list = statsModelUtil.getGoodsList(timeType, startTime, endTime,webSite, sort, "sale", vendor.getStoreId());
        List<GoodsRankVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(goodsBase -> {
                //销量和销售额二者必须有一个满足条件
                if (goodsBase.getSaleNum() > 0 || goodsBase.getSaleAmount().compareTo(BigDecimal.ZERO) > 0) {
                    vos.add(new GoodsRankVO(goodsBase.getGoodsId(), goodsBase.getGoodsName(), goodsBase.getGoodsImage(), goodsBase.getSaleAmount(), goodsBase.getSaleNum()));
                }
            });
        }
        return SldResponse.success(vos);
    }

    @ApiOperation("订单趋势")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "webSite", value = "站点")
    })
    @GetMapping("orderTrend")
    public JsonResult<OrderTrendVO> orderTrend(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());
        OrderTrendVO vo = new OrderTrendVO();
        //支付订单数列表
        List<OrderTrendVO.OrderPayNumVO> orderPayNumList = new ArrayList<>();
        //下单数列表
        List<OrderTrendVO.OrderSubmitNumVO> orderSubmitNumList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(trendVO -> {
                //支付订单数
                OrderTrendVO.OrderPayNumVO orderPayNumVO = new OrderTrendVO.OrderPayNumVO();
                orderPayNumVO.setStatsTime(trendVO.getStatsTime());
                orderPayNumVO.setOrderPayNum(trendVO.getOrderPayNum());
                orderPayNumList.add(orderPayNumVO);
                //下单数
                OrderTrendVO.OrderSubmitNumVO orderSubmitNumVO = new OrderTrendVO.OrderSubmitNumVO();
                orderSubmitNumVO.setStatsTime(trendVO.getStatsTime());
                orderSubmitNumVO.setOrderSubmitNum(trendVO.getOrderSubmitNum());
                orderSubmitNumList.add(orderSubmitNumVO);
            });
            vo.setOrderPayNumList(orderPayNumList);
            vo.setOrderSubmitNumList(orderSubmitNumList);
        }
        return SldResponse.success(vo);
    }

    @ApiOperation("交易报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "type", value = "排序类型；desc-降序;asc-升序;默认类型为降序"),
            @ApiImplicitParam(name = "sort", value = "排序:stats_time-时间;order_submit_num-下单数;order_submit_member_num-下单人数;" +
                    "order_submit_amount-下单金额;order_pay_num-支付订单数;order_pay_member_num-支付人数;order_pay_amount-支付金额;" +
                    "submit_pay_rate-支付转化率;默认按时间降序排序"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("tradeReport")
    public JsonResult<PageVO<TradeReportVO>> tradeReport(HttpServletRequest request, Date startTime, Date endTime,
                                                         @RequestParam(value = "type", required = false, defaultValue = "desc") String type,
                                                         @RequestParam(value = "sort", required = false, defaultValue = "stats_time") String sort) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);

        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        StoreDayExample example = new StoreDayExample();
        example.setStatsTimeAfter(startTime);
        example.setStatsTimeBefore(endTime);
        example.setStoreId(vendor.getStoreId());
        example.setOrderBy(sort + " " + type);
        List<StoreDay> list = storeDayModel.getStoreDayList(example, pager);
        List<TradeReportVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(platformDay -> {
                vos.add(new TradeReportVO(platformDay));
            });
        }
        return SldResponse.success(new PageVO<>(vos, pager));
    }

    @ApiOperation("导出报表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true),
            @ApiImplicitParam(name = "type", value = "排序类型；desc-降序;asc-升序;默认类型为降序"),
            @ApiImplicitParam(name = "sort", value = "排序:stats_time-时间;order_submit_num-下单数;order_submit_member_num-下单人数;" +
                    "order_submit_amount-下单金额;order_pay_num-支付订单数;order_pay_member_num-支付人数;order_pay_amount-支付金额;" +
                    "submit_pay_rate-支付转化率;默认按时间降序排序")
    })
    @GetMapping("export")
    public JsonResult export(HttpServletRequest request, HttpServletResponse response, Date startTime, Date endTime,
                             @RequestParam(value = "type", required = false, defaultValue = "desc") String type,
                             @RequestParam(value = "sort", required = false, defaultValue = "stats_time") String sort) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        StoreDayExample example = new StoreDayExample();
        example.setStoreId(vendor.getStoreId());
        example.setStatsTimeAfter(startTime);
        example.setStatsTimeBefore(endTime);
        example.setOrderBy(sort + " " + type);
        storeDayModel.tradeReportExport(request, response, example);
        return null;
    }

}
