package cn.pluss.platform.controller;

import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.PageVO;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.ProjectConstant;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.memberOrder.MemberOrderService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantMenber.MerchantMenberService;
import cn.pluss.platform.merchantMenberComsume.MerchantMenberComsumeService;
import cn.pluss.platform.merchantMenberRecharge.MerchantMenberRechargeService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.vo.MemberOrderNumberVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RequiredArgsConstructor
@RestController
@RequestMapping("/memberOrder")
@Transactional
@Api(value = "MemberOrder控制类", tags = {"MemberOrder接口"})
public class MemberOrderController {

    private final MemberOrderService memberOrderService;

    private final MerchantMenberService merchantMenberService;

    private final MerchantMenberComsumeService merchantMenberComsumeService;

    private final MerchantMenberRechargeService merchantMenberRechargeService;

    private final MerchantBaseInfoService merchantBaseInfoService;

    private final UserAppService userAppService;

    @GetMapping
    @ApiOperation(value = "获取全部", notes = "返回分页过后的数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "查询页码", paramType = "query", dataType = "Integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query", dataType = "Integer", defaultValue = "0"),
            @ApiImplicitParam(name = "memberCode", value = "要查询的会员编码", paramType = "query", dataType = "String", required = true)})
    public Result<PageInfo<MemberOrder>> list(@RequestParam(defaultValue = "1") Integer page,
                                              @RequestParam(defaultValue = "10") Integer size, @RequestParam String memberCode) {
        if (size == null || size == 0) {
            size = ProjectConstant.PAGE_SIZE;
        }
        if (page == null || page == 0) {
            page = 1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", size);
        map.put("offset", (page - 1) * size);
        map.put("memberCode", memberCode);
        map.put("orderStatus", "1");
        List<MemberOrder> memberOrderList = memberOrderService.queryMemberOrderPage(map);
        for (MemberOrder memberOrder : memberOrderList) {
            if ("1".equals(memberOrder.getOrderType())) {
                MerchantMenberRecharge merchantMenberRecharge = new MerchantMenberRecharge();
                merchantMenberRecharge.setOrderNumber(memberOrder.getOrderNumber());
                merchantMenberRecharge = merchantMenberRechargeService.queryMerchantMenberRecharge(merchantMenberRecharge);
                if (null != merchantMenberRecharge) {
                    memberOrder.setGiveMoney(StringUtil.bigDecimal(merchantMenberRecharge.getGiveMoney() == null ? new Double(0) : merchantMenberRecharge.getGiveMoney()) + "");
                }
            } else if ("0".equals(memberOrder.getOrderType())) {
                MerchantMenberComsume menberComsume = new MerchantMenberComsume();
                menberComsume.setOrderNumber(memberOrder.getOrderNumber());
                menberComsume = merchantMenberComsumeService.queryMerchantMenberComsume(menberComsume);
                if (null != menberComsume) {
                    memberOrder.setGiveMoney(StringUtil.bigDecimal(menberComsume.getGiveMoney() == null ? new Double(0) : menberComsume.getGiveMoney()) + "");
                }
            }

            MemberOrder.updateOrderTypeDesc(memberOrder);
        }
        Integer count = memberOrderService.queryMemberOrderPageCount(map);
        // 返回参数
        PageInfo<MemberOrder> pager = new PageInfo<>(count.longValue(), (long) StringUtil.getPageCount(count,size), page.longValue(), size.longValue(),
                memberOrderList);
        return ResultGenerator.genSuccessResult(pager);
    }

    @PostMapping
    @ApiOperation(value = "添加数据", notes = "添加新的数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MemberOrder", value = "待添加的MemberOrder实例", paramType = "body", dataType = "MemberOrder", required = true)})
    public Result add(@RequestBody MemberOrder memberOrder) {
        memberOrderService.saveMemberOrder(memberOrder);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/queryMemberOrderCensusData")
    @ApiOperation(value = "查询会员订单统计数据", notes = "查询会员订单统计数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MemberOrder", value = "需要查询的会员信息", paramType = "body", dataType = "MemberOrder", required = true)})
    public Result queryMemberOrderCensusData(@RequestBody MemberOrder memberOrder) throws ParseException {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        memberOrder.setMerchantCode(tokenUa.getMerchantCode());

        if (StringUtil.isEmpty(memberOrder.getMerchantCode())) {
            return ResultGenerator.genFailResult("无商家编码！");
        }

        Map<String, Object> queryMap = new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //校验查询条件
        if (!StringUtil.isEmpty(memberOrder.getStartTime()) && !DateUtils.isDate(memberOrder.getStartTime(), "yyyy-MM-dd HH:mm")) {
            return ResultGenerator.genFailResult("初始时间不正确！");
        }
        if (!StringUtil.isEmpty(memberOrder.getEndTime()) && !DateUtils.isDate(memberOrder.getEndTime(), "yyyy-MM-dd HH:mm")) {

            return ResultGenerator.genFailResult("结束时间不正确！");
        }

        if (memberOrder.getSize() == null || memberOrder.getSize() == 0) {
            memberOrder.setSize(ProjectConstant.PAGE_SIZE);
        }
        if (memberOrder.getPage() == null || memberOrder.getPage() == 0) {
            memberOrder.setPage(1);
        }


        if (StringUtil.isEmpty(memberOrder.getStartTime())) {
            queryMap.put("startTime", DateUtils.getDayBegin());
        } else {
            queryMap.put("startTime", DateUtils.getDayStartTime(sdf.parse(memberOrder.getStartTime())));
        }

        if (StringUtil.isEmpty(memberOrder.getEndTime())) {
            queryMap.put("endTime", DateUtils.getDayEnd());
        } else {
            queryMap.put("endTime", DateUtils.getDayEndTime(sdf.parse(memberOrder.getEndTime())));
        }
        queryMap.put("merchantCode", memberOrder.getMerchantCode());
        queryMap.put("pageSize", memberOrder.getSize());
        queryMap.put("offset", (memberOrder.getPage() - 1) * memberOrder.getSize());
        List<MemberOrder> memberOrderList = memberOrderService.queryMemberOrderPageByTime(queryMap);
        Integer count = memberOrderService.queryMemberOrderPageCountByTime(queryMap);
        // 返回参数
        PageInfo pager = new PageInfo<>(count.longValue(), (long) StringUtil.getPageCount(count, memberOrder.getSize()), memberOrder.getPage().longValue(), memberOrder.getSize().longValue(),
                memberOrderList);

        //查询会员充值金额
        queryMap.put("orderType", 1);
        Double totalRechargeFee = memberOrderService.queryMemberOrderTotalOrderFeeByTime(queryMap);

        //查询会员消费金额
        queryMap.put("orderType", 0);
        Double totalConsumeFee = memberOrderService.queryMemberOrderTotalOrderFeeByTime(queryMap);


        Map<String, Object> result = new HashMap<>();
        result.put("totalRechargeFee", totalRechargeFee);
        result.put("totalConsumeFee", totalConsumeFee);
        result.put("pager", pager);
        return ResultGenerator.genSuccessResult(result);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据", notes = "根据id删除数据", httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id实例", paramType = "path", dataType = "Integer", required = true)})
    public Result delete(@PathVariable Integer id) {
        MemberOrder memberOrder = new MemberOrder();
        memberOrder.setId(id);
        memberOrderService.deleteMemberOrder(memberOrder);
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping
    @ApiOperation(value = "更新数据", notes = "根据内容更新数据", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MemberOrder", value = "更新的MemberOrder实例", paramType = "body", dataType = "MemberOrder", required = true)})
    public Result update(@RequestBody MemberOrder memberOrder) {
        memberOrderService.updateMemberOrder(memberOrder);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "获取单个值", notes = "查看单个项目的内容", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id", paramType = "path", required = true, dataType = "Integer", defaultValue = "0")})
    public Result detail(@PathVariable Long id) {
        MemberOrder memberOrder = new MemberOrder();
        memberOrder.setId(id.intValue());
        memberOrder = memberOrderService.queryMemberOrder(memberOrder);
        return ResultGenerator.genSuccessResult(memberOrder);
    }


    @PostMapping("/queryMemberOrderList")
    @ApiOperation(tags = {"页面-账单_会员"}, value = "查询当前商家会员订单集合", notes = "查询当前商家会员订单集合", httpMethod = "POST")
    public Result<PageVO<MemberOrderNumberVO>> queryMemberOrderList(@RequestBody MemberOrder memberOrder) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        memberOrder.setMerchantCode(tokenUa.getMerchantCode());

        if (StringUtil.isEmpty(memberOrder.getMerchantCode())) {
            return ResultGenerator.genFailResult("无商家编码！");
        }

        Map<String, Object> queryMap = new HashMap<>();
        SimpleDateFormat sdfLong = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtil.isNotEmpty(memberOrder.getStartTime())) {
            queryMap.put("startTime", memberOrder.getStartTime());
        } else {
            queryMap.put("startTime", sdfLong.format(DateUtils.getDayBegin()));
        }
        if (StringUtil.isNotEmpty(memberOrder.getEndTime())) {
            queryMap.put("endTime", memberOrder.getEndTime());
        } else {
            queryMap.put("endTime", sdfLong.format(DateUtils.getDayEnd()));
        }
        if (StringUtil.isNotEmpty(memberOrder.getOrderType())) {//订单类型 0：会员消费  1：会员充值
            queryMap.put("orderType", memberOrder.getOrderType());
        }
        if (StringUtil.isNotEmpty(memberOrder.getRechargeType())) {
            queryMap.put("rechargeType", memberOrder.getRechargeType());
        }
        if (StringUtil.isNotEmpty(memberOrder.getMerchantCode())) {
            queryMap.put("merchantCode", memberOrder.getMerchantCode());
        }
        if (memberOrder.getSize() == null || memberOrder.getSize() == 0) {
            memberOrder.setSize(ProjectConstant.PAGE_SIZE);
        }
        if (memberOrder.getPage() == null || memberOrder.getPage() == 0) {
            memberOrder.setPage(1);
        }
        if (StringUtil.isNotEmpty(memberOrder.getStaffCode())) {//员工集合
            String[] staffCode = memberOrder.getStaffCode().split(",");
            List<String> staffCodeList = new ArrayList<>(Arrays.asList(staffCode));
            queryMap.put("staffCodeList", staffCodeList);
        }
        if (StringUtil.isNotEmpty(memberOrder.getStoreId())) {//门店集合
            String[] storeId = memberOrder.getStoreId().split(",");
            List<String> storeIdList = new ArrayList<>(Arrays.asList(storeId));
            queryMap.put("storeIdList", storeIdList);
        }
        queryMap.put("pageSize", memberOrder.getSize());
        queryMap.put("orderStatus", "1");
        queryMap.put("offset", (memberOrder.getPage() - 1) * memberOrder.getSize());
        List<MemberOrder> memberOrderList = memberOrderService.queryMemberOrderPageByTime(queryMap);
        List<MemberOrder> orderList = new ArrayList<>();

        if (memberOrderList != null && memberOrderList.size() > 0) {
            MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
            merchantBaseInfo.setMerchantCode(memberOrderList.get(0).getMerchantCode());
            merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);

            UserApp userApp = new UserApp();
            userApp.setUserType("promoter");
            userApp.setMerchantCode(memberOrderList.get(0).getMerchantCode());
            userApp = userAppService.queryUserApp(userApp);

            for (MemberOrder o : memberOrderList) {
                //待支付剔除
                if ("0".equals(o.getOrderStatus())) {
                    continue;
                }

                MerchantMenber member = new MerchantMenber();
                member.setMemberCode(o.getMemberCode());
                member = merchantMenberService.queryMerchantMenber(member);
                if (member != null && StringUtil.isNotEmpty(member.getLogo())) {
                    o.setLogo(member.getLogo());
                }
                String orderType = o.getOrderType();
                if (StringUtil.isNotEmpty(orderType)) {
                    if ("1".equals(orderType)) {
                        MerchantMenberRecharge merchantMenberRecharge = new MerchantMenberRecharge();
                        merchantMenberRecharge.setOrderNumber(o.getOrderNumber());
                        merchantMenberRecharge = merchantMenberRechargeService.queryMerchantMenberRecharge(merchantMenberRecharge);
                        if (null != merchantMenberRecharge) {
                            o.setGiveMoney(StringUtil.bigDecimal(merchantMenberRecharge.getGiveMoney() == null ? new Double(0) : merchantMenberRecharge.getGiveMoney()) + "");
                        }
                    } else if ("0".equals(orderType)) {
                        MerchantMenberComsume menberComsume = new MerchantMenberComsume();
                        menberComsume.setOrderNumber(o.getOrderNumber());
                        menberComsume = merchantMenberComsumeService.queryMerchantMenberComsume(menberComsume);
                        if (null != menberComsume) {
                            o.setGiveMoney(StringUtil.bigDecimal(menberComsume.getGiveMoney() == null ? new Double(0) : menberComsume.getGiveMoney()) + "");
                        }
                    }
                }

                o.setAlias(merchantBaseInfo.getAlias());
                MemberOrder.updateStaffName(o, userApp);
                MemberOrder.updateOrderTypeDesc(o);
                orderList.add(o);
            }
        }

        queryMap.put("isPay", "isPay");
//        Integer count = memberOrderService.queryMemberOrderPageCountByTime(queryMap);
        Map<String, Map<String, Object>> countMap = memberOrderService.queryMemberOrderCountByTimeGroupData(queryMap);
        Map<String, Object> countMap1 = countMap.get("1");
        Map<String, Object> countMap0 = countMap.get("0");
        int chargeCount;
        if (countMap1 != null) {
            chargeCount = countMap1.get("count") == null? 0: Integer.parseInt(countMap1.get("count") + "");
        } else {
            chargeCount = 0;
        }

        int consumeCount;
        if (countMap0 != null) {
            consumeCount = countMap0.get("count") == null? 0: Integer.parseInt(countMap0.get("count") + "");
        } else {
            consumeCount = 0;
        }

        val count = chargeCount + consumeCount;
        Double orderCount = 0d;
        if ("0".equals(memberOrder.getOrderType())) {
            queryMap.put("orderType", "0");
            //消费总金额
            orderCount = memberOrderService.sumMemberOrderMoney(queryMap);
        } else if (StringUtil.isEmpty(memberOrder.getOrderType())) {
            queryMap.put("orderType", "0");
            //消费总金额
            orderCount = memberOrderService.sumMemberOrderMoney(queryMap);
        }
        Double totalOrderFee = 0d;
        if ("1".equals(memberOrder.getOrderType())) {
            queryMap.put("orderType", "1");
            //充值总金额
            totalOrderFee = memberOrderService.sumMemberOrderMoney(queryMap);
        } else if (StringUtil.isEmpty(memberOrder.getOrderType())) {
            queryMap.put("orderType", "1");
            //充值总金额
            totalOrderFee = memberOrderService.sumMemberOrderMoney(queryMap);
        }
        MemberOrderNumberVO vo = new MemberOrderNumberVO();
        vo.setOrderCount(StringUtil.bigDecimal(orderCount == null ? new Double(0) : orderCount) + "");
        vo.setTotalOrderFee(StringUtil.bigDecimal(totalOrderFee == null ? new Double(0) : totalOrderFee) + "");
        vo.setMemberOrderList(orderList);
        vo.setChargeCount(chargeCount + "");
        vo.setConsumeCount(consumeCount + "");
        //返回参数
        PageVO<MemberOrderNumberVO> pageVO = new PageVO<>(count, StringUtil.getPageCount(count, memberOrder.getSize()), memberOrder.getPage(), memberOrder.getSize(), vo);
        return ResultGenerator.genSuccessResult(pageVO);
    }
}
