package com.ruoyi.web.controller.api;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JPushUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.vo.MallMemberLoginLog;
import com.ruoyi.mall.domain.vo.MallOrderGoodsVO;
import com.ruoyi.mall.mapper.MallMemberUserMapper;
import com.ruoyi.mall.service.*;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.controller.utils.XiaochengxuPayService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName ApiOrderController
 * @Description 请描述类的业务用途
 * @Author linlinee
 * @Date 2021/11/30 10:03 AM
 * @Version 1.0
 **/

@RestController
@RequestMapping("/api/order")
@ResponseBody
public class ApiOrderController {

    @Autowired
    IMallOrderOrderService orderService;

    @Autowired
    IMallGoodsGoodsService goodsService;

    @Autowired
    IMallGoodsProductService productService;

    @Autowired
    IMallGoodsSpecValueService specValueService;

    @Autowired
    IMallMemberAddressService addressService;

    @Autowired
    IMallMemberUserService memberUserService;

    @Autowired
    XiaochengxuPayService xiaochengxuPayService;

    @Autowired
    IMallOrderCommentService orderCommentService;

    @Autowired
    IMallOrderBackService orderBackService;

    @Autowired
    IMallOrderGoodsService orderGoodsService;

    @Autowired
    IMallMemberCartService memberCartService;

    @Autowired
    IMallTargetService mallTargetService;

    @Resource
    private IMallSeckillGoodsService mallSeckillGoodsService;

    @Resource
    private IMallCombineOrderLinkService mallCombineOrderLinkService;

    @Resource
    private IMallSalesmanAchievementService mallSalesmanAchievementService;

    @Resource
    private IMallMeetAddressService mallMeetAddressService;

    @Resource
    private MallMemberUserMapper mallMemberUserMapper;

    @Autowired
    private IMallMemberCouponService mallMemberCouponService;
    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private JPushUtils jPushUtils;

    /**
     * 再来一单
     *
     * @return
     */
    @PostMapping("/oneMoreOrder")
    public ApiResult oneMoreOrder(@RequestBody Map<String, Object> param) {
        if (!param.containsKey("orderId") || MapUtils.getLong(param, "orderId") == null) {
            return ApiResult.error("缺少orderId");
        }
        try {
            return orderService.oneMoreOrder(param);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("服务器异常");
        }
    }

    @PostMapping("/creatOrderByGoods")
    public ApiResult creatOrderByGoods(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId") || StringUtils.isEmpty(params.get("userId").toString())) {
            return ApiResult.error("用户Id为空");
        }
        if (!params.containsKey("goodId") || StringUtils.isEmpty(params.get("goodId").toString())) {
            return ApiResult.error("商品id为空");
        }
        // if (!params.containsKey("productId")||StringUtils.isEmpty(params.get("productId").toString())){
        //     return ApiResult.error("规格id为空");
        // }

        if (!params.containsKey("count") || Integer.parseInt(params.get("count").toString()) <= 0) {
            return ApiResult.error("商品数量不能为0");
        }
        if (!params.containsKey("buyerMsg")) {
            return ApiResult.error("缺少参数");
        }
        if (!params.containsKey("deliveryType") || StringUtils.isEmpty(params.get("deliveryType").toString())) {
            return ApiResult.error("缺少deliveryType 配送方式");
        }
        int deliveryType = Integer.parseInt(params.get("deliveryType").toString());
        if (deliveryType == 0) {
            if (!params.containsKey("addressId") || StringUtils.isEmpty(params.get("addressId").toString())) {
                return ApiResult.error("请填写收货地址");
            }

            MallMemberAddress address = addressService.selectMallMemberAddressById(Long.valueOf(params.get("addressId").toString()));
            if (StringUtils.isBlank(address.getAddress())) {
                return ApiResult.error("请选择接货地址");
            }
            // MallMeetAddress mallMeetAddress = mallMeetAddressService.selectMallMeetAddressByMeetId(address.getMeetId());
            // if (mallMeetAddress == null) {
            //     return ApiResult.error("请重新选择接货地址");
            // }

        }
        if (deliveryType == 1) {
            if (!params.containsKey("shopId") || StringUtils.isEmpty(params.get("shopId").toString())) {
                return ApiResult.error("自提请允许获取定位");
            }
        }


        BigDecimal couponPrice = new BigDecimal(0);
        if (params.containsKey("couponId")) {
            String couponId = params.get("couponId").toString();
            //查看优惠券是否可用
            if (!StringUtils.isEmpty(couponId)) {
                // Map<String, Object> map = memberUserService.checkCouponUsed(couponId,Long.valueOf(params.get("userId").toString()));
                MallMemberCoupon memberCoupon = mallMemberCouponService.checkCouponUsed(Long.valueOf(couponId), Long.valueOf(params.get("userId").toString()));
                if (memberCoupon == null) {
                    return ApiResult.error("优惠券异常");
                } else {
                    params.put("couponPrice", memberCoupon.getPrice());
                    params.put("memberCouponId", memberCoupon.getMemberCouponId());
                }
            }
        }

        try {

            if (params.containsKey("seckillGoodsId") && MapUtils.getInteger(params, "seckillGoodsId") != null) {
                MallSeckillGoods goodId = mallSeckillGoodsService.selectMallSeckillGoodsById(MapUtils.getInteger(params, "seckillGoodsId"));
                Integer count = MapUtils.getInteger(params, "count");
                if (count > goodId.getPurchaseLimits()) {
                    return ApiResult.error("秒杀商品每人限购" + goodId.getPurchaseLimits() + "件");
                }
                if (count > goodId.getStock()) {
                    return ApiResult.error("库存不足");
                }
            }

            // 拼团订单
            if (params.containsKey("orderType") && MapUtils.getInteger(params, "orderType") != null && MapUtils.getInteger(params, "orderType") == 2) {
                // 参与拼团
                if (params.containsKey("teamId") && MapUtils.getLong(params, "teamId") != null) {
                    MallCombineOrderLink combineOrderLink = mallCombineOrderLinkService.selectMallCombineOrderLinkByLinkId(Long.valueOf(params.get("teamId").toString()));
                    if (combineOrderLink == null || combineOrderLink.getEndTime().compareTo(DateUtils.getTime()) < 0) {
                        return ApiResult.error("参与拼团时间已到");
                    }
                }
            }

            MallGoodsGoods goods = goodsService.selectMallGoodsGoodsById(Long.valueOf(params.get("goodId").toString()));
            if (goods == null || "1".equals(goods.getStatus()) || goods.getCheckStatus() != 1) {
                return ApiResult.error("商品已下架");
            }
            int count = Integer.parseInt(params.get("count").toString());
            if (goods.getStock() < count) {
                return ApiResult.error("商品库存不足");
            }

            MallOrderOrder order = orderService.creatOrderByGoods(params);
            if (order == null) {
                return ApiResult.error("库存不足");
            } else {
                // 登陆记录
                MallMemberLoginLog mallMemberLoginLog = new MallMemberLoginLog();
                mallMemberLoginLog.setUserId(order.getUserId().intValue());
                mallMemberLoginLog.setLoginAt(DateUtils.getTime());
                mallMemberUserMapper.insertLoginLog(mallMemberLoginLog);
                // 登陆时间
                MallMemberUser mallMemberUser = new MallMemberUser();
                mallMemberUser.setId(order.getUserId());
                mallMemberUser.setLoginAt(DateUtils.getTime());
                mallMemberUserMapper.updateMallMemberUser(mallMemberUser);

                // 新增或修改业务员业绩
                mallSalesmanAchievementService.insertOrUpdateMallSalesmanAchievement(order.getId(), 0);
                Map<String, Object> map = new HashMap<>();
                //map.put("orderId",order.getId());
                map.put("orderId", order.getTotalOrderSn());
                map.put("price", order.getPayment());
                //map.put("orderNo",order.getOrderNo());
                map.put("orderNo", order.getTotalOrderSn());
                // api/Goods/getGoodsByParamsapi/Goods/getGoodsByParams支付类型: 0=未支付,1=微信,2=支付宝（未支付拉起支付）
                if (order.getPayType() != null) {
                    map.put("payType", order.getPayType());
                } else {
                    map.put("payType", "0");
                }

                return ApiResult.ok().put("data", map);
            }
        } catch (Exception e) {
            return ApiResult.error("下单失败");
        }
    }

    @PostMapping("/creatOrderByShopCarts")
    public ApiResult creatOrderByShopCarts(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("userId")) {
            return ApiResult.error("用户Id为空");
        }
        if (!params.containsKey("cartIds")) {
            return ApiResult.error("购物车Id为空");
        }
        if (!params.containsKey("addressId")) {
            return ApiResult.error("收货地址id为空");
        }
        if (!params.containsKey("buyerMsg")) {
            return ApiResult.error("缺少参数");
        }
        if (!params.containsKey("deliveryType") || StringUtils.isEmpty(params.get("deliveryType").toString())) {
            return ApiResult.error("缺少deliveryType 配送方式");
        }

        int deliveryType = Integer.parseInt(params.get("deliveryType").toString());
        if (deliveryType == 0) {
            if (!params.containsKey("addressId") || StringUtils.isEmpty(params.get("addressId").toString())) {
                return ApiResult.error("请填写收货地址");
            }

            MallMemberAddress address = addressService.selectMallMemberAddressById(Long.valueOf(params.get("addressId").toString()));
            if (StringUtils.isBlank(address.getAddress())) {
                return ApiResult.error("请选择接货地址");
            }
            // MallMeetAddress mallMeetAddress = mallMeetAddressService.selectMallMeetAddressByMeetId(address.getMeetId());
            // if (mallMeetAddress == null) {
            //     return ApiResult.error("请重新选择接货地址");
            // }
        }
        if (deliveryType == 1) {
            if (!params.containsKey("shopId") || StringUtils.isEmpty(params.get("shopId").toString())) {
                return ApiResult.error("自提请允许获取定位");
            }
        }

        if (params.containsKey("couponId")) {
            String couponId = params.get("couponId").toString();
            //查看优惠券是否可用
            if (!StringUtils.isEmpty(couponId)) {
                // Map<String, Object> map = memberUserService.checkCouponUsed(couponId,Long.valueOf(params.get("userId").toString()));
                MallMemberCoupon memberCoupon = mallMemberCouponService.checkCouponUsed(Long.valueOf(couponId), Long.valueOf(params.get("userId").toString()));
                if (memberCoupon == null) {
                    return ApiResult.error("优惠券异常");
                } else {
                    params.put("couponPrice", memberCoupon.getPrice());
                    params.put("memberCouponId", memberCoupon.getMemberCouponId());
                }
            }
        }

        try {
            List<MallOrderOrder> orderList = orderService.creatOrderByCartIds(params);
            if (orderList == null) {
                return ApiResult.error("库存不足");
            } else {
                // 登陆记录
                MallMemberLoginLog mallMemberLoginLog = new MallMemberLoginLog();
                mallMemberLoginLog.setUserId(orderList.get(0).getUserId().intValue());
                mallMemberLoginLog.setLoginAt(DateUtils.getTime());
                mallMemberUserMapper.insertLoginLog(mallMemberLoginLog);
                // 登陆时间
                MallMemberUser mallMemberUser = new MallMemberUser();
                mallMemberUser.setId(orderList.get(0).getUserId());
                mallMemberUser.setLoginAt(DateUtils.getTime());
                mallMemberUserMapper.updateMallMemberUser(mallMemberUser);

                // 新增或修改业务员业绩
                BigDecimal price = BigDecimal.ZERO;
                for (MallOrderOrder order : orderList) {
                    mallSalesmanAchievementService.insertOrUpdateMallSalesmanAchievement(order.getId(), 0);

                    price = price.add(order.getPayment());
                }


                Map<String, Object> map = new HashMap<>();
                map.put("orderId", orderList.get(0).getTotalOrderSn());
                map.put("price", price);
                map.put("orderNo", orderList.get(0).getTotalOrderSn());
                // 支付类型: 0=未支付,1=微信,2=支付宝（未支付拉起支付）
                if (orderList.get(0).getPayType() != null) {
                    map.put("payType", orderList.get(0).getPayType());
                } else {
                    map.put("payType", "0");
                }
                return ApiResult.ok().put("data", map);
            }
        } catch (Exception e) {
            return ApiResult.error("下单失败");
        }
    }

    /**
     * 微信小程序支付接口
     *
     * @param params
     * @param req
     * @return
     */
    @RequestMapping("/xiaochengxuPay")
    @ResponseBody
    public ApiResult xiaochengxuPay(@RequestBody Map<String, Object> params, HttpServletRequest req) {
        try {
            if (!params.containsKey("orderId") || !params.containsKey("userId")) {
                return ApiResult.error(100, "缺少参数");
            }
            String totalOrderSn = params.get("orderId").toString();
            String userId = params.get("userId").toString();
            MallMemberUser userDO = memberUserService.selectMallMemberUserById(Long.parseLong(userId));
            if (userDO == null) {
                return ApiResult.error(103, "用户异常");
            }
            List<MallOrderOrder> orderList = orderService.selectMallOrderOrderByTotalOrderSn(totalOrderSn);
            if (orderList.isEmpty()) {
                return ApiResult.error(101, "订单异常");
            }

            BigDecimal payment = BigDecimal.ZERO;
            for (MallOrderOrder order : orderList) {
                payment = payment.add(order.getPayment());
            }
            SortedMap<String, String> signMap = new TreeMap<>();

            //商品描述  必
            signMap.put("body", "千冻网商品");
            //商品描述  必
            signMap.put("attach", "千冻网商品");
            //商品详情  非
            signMap.put("openid", userDO.getOpenid());
            //商户订单号  必
            signMap.put("out_trade_no", totalOrderSn);
            float sessionmoney = Float.parseFloat(payment.toString());
            String finalmoney = String.format("%.2f", sessionmoney);
            finalmoney = finalmoney.replace(".", "");
            String newStr = finalmoney.replaceFirst("^0*", "");
            //总金额  必
            signMap.put("total_fee", newStr);
            //终端ip  用户端ip  必
            signMap.put("spbill_create_ip", StringUtils.getRemoteAddr(req));

            Map<String, Object> relMap = xiaochengxuPayService.getOrderSignature(signMap);
            return ApiResult.ok().put("data", relMap);

        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("返回调起微信支付参数失败!");
        }
    }

    /**
     * 取消订单
     *
     * @param params
     * @return
     */
    @PostMapping("/cancleOrder")
    public ApiResult cancleOrder(@RequestBody Map<String, Object> params) {

        try {
            if (!params.containsKey("orderId") || StringUtils.isEmpty(params.get("orderId").toString())) {
                return ApiResult.error("缺少参数");
            }
            MallOrderOrder order = orderService.selectMallOrderOrderById(Long.parseLong(params.get("orderId").toString()));
            Boolean isAccept = orderService.orderStatusRoute(Integer.parseInt("8"), params.get("orderId").toString());
            if (isAccept == true) {
                order.setStatus("8");
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                order.setCompleteAt(formatter.format(new Date()));
                return orderService.updateMallOrderOrderByCancle(order);

            } else {
                return ApiResult.error("订单异常");
            }

        } catch (Exception e) {
            return ApiResult.ok("取消订单失败");
        }
    }

    /**
     * 确认收货
     *
     * @param params
     * @return
     */
    @PostMapping("/orderReceived")
    public ApiResult orderReceived(@RequestBody Map<String, Object> params) {

        try {
            if (!params.containsKey("orderId") || StringUtils.isEmpty(params.get("orderId").toString())) {
                return ApiResult.error("缺少参数");
            }
            MallOrderOrder order = orderService.selectMallOrderOrderById(Long.parseLong(params.get("orderId").toString()));
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setCompleteAt(formatter.format(new Date()));
            order.setEnterAt(formatter.format(new Date()));
            // Boolean isAccept = orderService.orderStatusRoute(Integer.parseInt("3"),params.get("orderId").toString());
            // if (isAccept == true) {
            order.setStatus("4");
            int status = orderService.updateMallOrderOrder(order);

            try {
                // 新增或修改业务员业绩
                mallSalesmanAchievementService.insertOrUpdateMallSalesmanAchievement(Long.parseLong(params.get("orderId").toString()), 1);
            } catch (Exception e) {
                System.out.println("新增或修改业务员业绩异常");
            }

            return status > 0 ? ApiResult.ok("确认收货成功") : ApiResult.ok("确认收货失败");
            // }else {
            //     return ApiResult.error("订单异常");
            // }
        } catch (Exception e) {
            return ApiResult.ok("确认收货失败");
        }
    }

    /**
     * 订单评价
     *
     * @param params
     * @return
     */
    @PostMapping("/orderComment")
    public ApiResult orderComment(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("orderId") || StringUtils.isEmpty(params.get("orderId").toString())
                || !params.containsKey("userId") || StringUtils.isEmpty(params.get("userId").toString())
                || !params.containsKey("commentList") || StringUtils.isEmpty(params.get("commentList").toString())) {
            return ApiResult.error("缺少参数");
        }
        Boolean isAccept = orderService.orderStatusRoute(Integer.parseInt("4"), params.get("orderId").toString());
        if (isAccept == true) {
            int status = orderCommentService.commentOrder(params);
            return status > 0 ? ApiResult.ok("评价成功") : ApiResult.ok("评价失败");
        } else {
            return ApiResult.error("订单异常");
        }
    }

    // /**
    //  * 申请退款
    //  * @param params orderGoodsIds 订单商品ID集合
    //  * @return
    //  */
    // @PostMapping("/applyForRefund")
    // public ApiResult applyForRefund (@RequestBody Map<String, Object> params){
    //     if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())
    //             || !params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())){
    //         return ApiResult.error("缺少参数");
    //     }
    //     if (!params.containsKey("orderGoodsList")||StringUtils.isEmpty(params.get("orderGoodsList").toString())){
    //         return ApiResult.error("缺少orderGoodsList");
    //     }
    //     Boolean isAccept = orderService.orderStatusRoute(Integer.parseInt("5"),params.get("orderId").toString());
    //     if (isAccept == true) {
    //         int status = orderBackService.applyForRefund(params);
    //         return status > 0 ? ApiResult.ok("申请退款中") : ApiResult.error("不能申请退款");
    //     }else {
    //         return ApiResult.error("订单异常");
    //     }
    //
    // }

    /**
     * 申请退款
     *
     * @param params goodsVOList 订单商品ID集合
     * @return
     */
    @PostMapping("/applyForRefund")
    public ApiResult applyForRefund(@RequestBody MallOrderOrder mallOrderOrder) {
        if (mallOrderOrder.getUserId() == null) {
            return ApiResult.error("缺少userId");
        }
        if (mallOrderOrder.getOrderId() == null) {
            return ApiResult.error("缺少orderId");
        }
        if (mallOrderOrder.getGoodsVOList() == null || mallOrderOrder.getGoodsVOList().size() < 1) {
            return ApiResult.error("缺少goodsVOList");
        }

        List<MallOrderGoodsVO> goodsVOList = mallOrderOrder.getGoodsVOList();
        for (MallOrderGoodsVO orderGoodsVO : goodsVOList) {
            if (orderGoodsVO.getReturnTotal() == null || orderGoodsVO.getReturnTotal() < 1) {
                return ApiResult.error("请输入退货数量");
            }
            if (orderGoodsVO.getTotal() < orderGoodsVO.getReturnTotal()) {
                MallOrderGoods mallOrderGoods = orderGoodsService.selectMallOrderGoodsById(orderGoodsVO.getId());
                return ApiResult.error(mallOrderGoods.getGoodsName() + ":" + mallOrderGoods.getProductName() + "退货数大于购买数量");
            }
            if (orderGoodsVO.getReturnableQuantity() < orderGoodsVO.getReturnTotal()) {
                MallOrderGoods mallOrderGoods = orderGoodsService.selectMallOrderGoodsById(orderGoodsVO.getId());
                return ApiResult.error(mallOrderGoods.getGoodsName() + ":" + mallOrderGoods.getProductName() + "退货数大于剩余可退货数量");
            }

        }

        Boolean isAccept = orderService.orderStatusRoute(Integer.parseInt("5"), mallOrderOrder.getOrderId().toString());
        if (isAccept == true) {
            int status = orderBackService.applyForRefund(mallOrderOrder);

            if (status == 1) {
                MallOrderOrder orderOrder = orderService.selectMallOrderOrderById(mallOrderOrder.getOrderId());
                if (orderOrder != null) {
                    Map<String, String> orderInfoParams = new HashMap<>();
                    orderInfoParams.put("orderId", orderOrder.getId().toString());
                    orderInfoParams.put("orderType", "0");
                    String orderInfo = JSON.toJSONString(orderInfoParams);

                    // 极光推送
                    // roleId：1-超级管理员，12-仓库管理员，13-财务，10-分公司管理员，11-业务员
                    Map<String, Object> newParams = new HashMap<>();
                    newParams.put("roleId", 1);
                    String[] userName = sysUserMapper.selectUserNameByParams(newParams);
                    if (userName.length > 0) {
                        System.out.println("线上订单申请退款-管理员查看推送");
                        try {
                            String url = "intent:#Intent;action=cn.jiguang.myaction;component=com.qdw.qianlengnet/com.qdw.qianlengnet.activity.ChiefAdministratorOrderDetailsActivity;S.orderNo=" + orderOrder.getId().toString() + ";i.orderType=" + 0 + ";end";
                            JsonObject jsonObject = new JsonObject();
                            jsonObject.addProperty("url", url);

                            jPushUtils.jPush(userName, orderOrder.getReceiverName() + orderOrder.getReceiverPhone() + "线上订单申请退款，管理员请及时查看", "线上订单申请退款", orderInfo, orderInfoParams, jsonObject);
                        } catch (Exception e) {
                            System.out.println("线上订单申请退款-管理员查看推送异常");
                        }
                    }

                    // roleId：1-超级管理员，12-仓库管理员，13-财务，10-分公司管理员，11-业务员
                    Map<String, Object> financeParams = new HashMap<>();// 线上订单退款-财务查看推送
                    financeParams.put("roleId", 13);
                    String[] financeName = sysUserMapper.selectUserNameByParams(financeParams);
                    if (financeName.length > 0) {
                        System.out.println("线上订单申请退款-财务查看推送");
                        try {
                            String url = "intent:#Intent;action=cn.jiguang.myaction;component=com.qdw.qianlengnet/com.qdw.qianlengnet.activity.ChiefAdministratorOrderDetailsActivity;S.orderNo=" + orderOrder.getId().toString() + ";i.orderType=" + 0 + ";end";
                            JsonObject jsonObject = new JsonObject();
                            jsonObject.addProperty("url", url);

                            jPushUtils.jPush(financeName, orderOrder.getReceiverName() + orderOrder.getReceiverPhone() + "线上订单申请退款，财务请及时查看", "线上订单申请退款", orderInfo, orderInfoParams, jsonObject);
                        } catch (Exception e) {
                            System.out.println("线上订单申请退款-财务查看推送异常");
                        }
                    }

                    if (orderOrder.getSalesmanId() != null) {
                        // roleId：1-超级管理员，12-仓库管理员，13-财务，10-分公司管理员，11-业务员
                        Map<String, Object> salesmanParams = new HashMap<>();// 新增线上订单-业务员查看推送
                        salesmanParams.put("roleId", 11);
                        salesmanParams.put("salesmanId", orderOrder.getSalesmanId());
                        String[] salesmanName = sysUserMapper.selectUserNameByParams(salesmanParams);
                        if (salesmanName.length > 0) {
                            System.out.println("线上订单申请退款-业务员查看推送");
                            try {
                                String url = "intent:#Intent;action=cn.jiguang.myaction;component=com.qdw.qianlengnet/com.qdw.qianlengnet.activity.OrderDetailsActivity;S.orderNo=" + orderOrder.getId().toString() + ";i.orderType=" + 0 + ";end";
                                JsonObject jsonObject = new JsonObject();
                                jsonObject.addProperty("url", url);

                                jPushUtils.jPush(salesmanName, orderOrder.getReceiverName() + orderOrder.getReceiverPhone() + "线上订单申请退款，请及时查看", "线上订单申请退款", orderInfo, orderInfoParams, jsonObject);
                            } catch (Exception e) {
                                System.out.println("线上订单申请退款-业务员查看推送异常");
                            }
                        }
                    }
                }
            }

            return status > 0 ? ApiResult.ok("申请退款中") : ApiResult.error("不能申请退款");
        } else {
            return ApiResult.error("订单异常");
        }

    }

    /**
     * 取消退款
     *
     * @param params
     * @return
     */
    @PostMapping("/cancleRefund")
    public ApiResult cancleRefund(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("refundId") || StringUtils.isEmpty(params.get("refundId").toString())) {
            return ApiResult.error("缺少参数");
        }
        Boolean isAccept = orderService.refundStatusRoute(Integer.parseInt("2"), params.get("refundId").toString());
        if (isAccept == true) {
            int status = orderBackService.cancleRefund(params);
            return status > 0 ? ApiResult.ok("取消成功") : ApiResult.ok("取消失败");
        } else {
            return ApiResult.error("订单异常");
        }
    }

    /**
     * 获取订单列表
     *
     * @param params
     * @return
     */
    @GetMapping("/getOrdersByType")
    public ApiResult getOrdersByType(@RequestParam Map<String, Object> params) {
        if (!params.containsKey("type")
                || !params.containsKey("pageNum")
                || !params.containsKey("pageSize")
                || !params.containsKey("userId")
                || !params.containsKey("deliveryType")
        ) {
            return ApiResult.error("参数异常");
        }

        PageInfo<MallOrderOrder> pageInfo = orderService.selectOrdersByType(params.get("pageNum").toString(), params.get("pageSize").toString(), params.get("type").toString(), params.get("userId").toString(), Integer.parseInt(params.get("deliveryType").toString()));
        return ApiResult.ok("取消成功").put("data", pageInfo);
    }
    /**
     * 获取订单列表
     *
     * @param params
     * @return
     */
    @GetMapping("/getBackOrdersByType")
    public ApiResult getBackOrdersByType(@RequestParam Map<String, Object> params) {
        if (!params.containsKey("type")
                || !params.containsKey("pageNum")
                || !params.containsKey("pageSize")
                || !params.containsKey("userId")
                || !params.containsKey("deliveryType")
        ) {
            return ApiResult.error("参数异常");
        }

        PageInfo<MallOrderBackDto> pageInfo = orderService.selectBackOrdersByType(params.get("pageNum").toString(), params.get("pageSize").toString(), params.get("type").toString(), params.get("userId").toString(), Integer.parseInt(params.get("deliveryType").toString()));
        return ApiResult.ok("取消成功").put("data", pageInfo);
    }

    /**
     * 根据id获取订单
     *
     * @param params
     * @return
     */
    @GetMapping("/getOrderByID")
    public ApiResult getOrderByID(@RequestParam Map<String, Object> params) {
        if (!params.containsKey("orderId")) {
            return ApiResult.error("参数异常");
        }

        try {
            MallOrderOrder order = orderService.selectMallOrderOrderById(Long.parseLong(params.get("orderId").toString()));
            List<MallOrderGoodsVO> orderGoodsVOList = orderGoodsService.selectMallOrderGoodsByOrderId(order.getId());
            order.setGoodsVOList(orderGoodsVOList);
            if ("5".equals(order.getStatus()) || "6".equals(order.getStatus())) {
                List<MallOrderBack> list = orderBackService.selectMallOrderBackByOrderId(Long.parseLong(params.get("orderId").toString()));
                MallOrderBack result = new MallOrderBack();
                for (MallOrderBack orderBack : list) {
                    result = orderBack;
                }
                order.setOrderBack(result);
            }
            return ApiResult.ok().put("data", order);
        } catch (Exception e) {
            return ApiResult.ok("获取订单失败");
        }
    }

    /**
     * 付款之后修改收货地址
     *
     * @param params
     * @return
     */
    @PostMapping("/changeOrderAddress")
    public ApiResult changeOrderAddress(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("orderId") || !params.containsKey("addressId")) {
            return ApiResult.error("参数异常");
        }

        try {
            MallOrderOrder order = orderService.selectMallOrderOrderById(Long.parseLong(params.get("orderId").toString()));
            MallMemberAddress address = addressService.selectMallMemberAddressById(Long.parseLong(params.get("addressId").toString()));
            if ("2".equals(order.getStatus()) || "1".equals(order.getStatus())) {
                if ("1".equals(order.getIsChangeAddress())) {
                    return ApiResult.error("收货地址只能修改一次");
                }
                if (address == null) {
                    return ApiResult.error("收货地址不存在");
                }
                order.setIsChangeAddress("1");
                order.setReceiverPhone(address.getPhone());
                order.setReceiverAddress(address.getAddress());
                order.setReceiverArea(address.getArea());
                order.setReceiverCity(address.getCity());
                order.setReceiverProvince(address.getProvince());
                order.setReceiverName(address.getName());
                orderService.updateMallOrderOrder(order);
                return ApiResult.ok().put("data", order);
            } else {
                return ApiResult.error("当前订单状态无法修改");
            }

        } catch (Exception e) {
            return ApiResult.ok("修改收货地址失败");
        }
    }


    /**
     * 所有订单的金额
     *
     * @param params
     * @return
     */
    @GetMapping("/checkTotlePriceAndTotleCount")
    public ApiResult checkTotlePriceAndTotleCount(@RequestParam Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();

        int count = orderService.checkTotleCount();
        BigDecimal price = orderService.checkTotlePrice();
        map.put("totleCount", count);
        map.put("totlePrice", price);
        return ApiResult.ok().put("data", map);
    }

    /**
     * 按月、按年查询
     *
     * @param params
     * @return
     */
    @GetMapping("/checkTotlePriceByTime")
    public ApiResult checkTotlePriceByTime(@RequestParam Map<String, Object> params) {
        if (!params.containsKey("year")) {
            return ApiResult.error("参数异常");
        }
        MallTarget target = new MallTarget();

        List<MallTarget> list = mallTargetService.selectMallTargetList(new MallTarget());
        if (list.size() > 0) {
            target = list.get(0);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("target", target);

        BigDecimal price = orderService.checkYearAndMonth(params.get("year").toString(), null, null);
        map.put("yearPrice", price);
        int count = orderService.checkCountYearAndMonth(params.get("year").toString(), null, null);
        map.put("yearCount", count);


        if (params.containsKey("month") && params.get("month").toString().length() > 0) {
            BigDecimal monthPrice = orderService.checkYearAndMonth(params.get("year").toString(), params.get("month").toString(), null);
            map.put("monthPrice", monthPrice);

            int monthCount = orderService.checkCountYearAndMonth(params.get("year").toString(), params.get("month").toString(), null);
            map.put("monthCount", monthCount);
        }

        if (params.containsKey("month") && params.get("month").toString().length() > 0
                && params.containsKey("day") && params.get("day").toString().length() > 0) {
            BigDecimal dayPrice = orderService.checkYearAndMonth(params.get("year").toString(), params.get("month").toString(), params.get("day").toString());
            map.put("dayPrice", dayPrice);

            int dayCount = orderService.checkCountYearAndMonth(params.get("year").toString(), params.get("month").toString(), params.get("day").toString());
            map.put("dayCount", dayCount);
        }

        return ApiResult.ok().put("data", map);
    }
    //
    //@GetMapping("/change")
    //public AjaxResult change(){
    //    orderService.change();
    //    return AjaxResult.success();
    //}
}
