package com.ruoyi.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JPushUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.mall.domain.MallOrderBack;
import com.ruoyi.mall.domain.MallOrderGoods;
import com.ruoyi.mall.domain.MallOrderOrder;
import com.ruoyi.mall.domain.MallOrderbackGoods;
import com.ruoyi.mall.domain.vo.MallOrderGoodsVO;
import com.ruoyi.mall.mapper.MallOrderBackMapper;
import com.ruoyi.mall.mapper.MallOrderbackGoodsMapper;
import com.ruoyi.mall.service.IMallGoodsProductService;
import com.ruoyi.mall.service.IMallOrderBackService;
import com.ruoyi.mall.service.IMallOrderGoodsService;
import com.ruoyi.mall.service.IMallOrderOrderService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 退款单Service业务层处理
 *
 * @author chang
 * @date 2021-11-25
 */
@Service
public class MallOrderBackServiceImpl implements IMallOrderBackService {
    @Resource
    private MallOrderBackMapper mallOrderBackMapper;

    @Resource
    private IMallOrderOrderService orderOrderService;

    @Resource
    private IMallOrderGoodsService orderGoodsService;

    @Resource
    private IMallGoodsProductService goodsProductService;

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private MallOrderbackGoodsMapper mallOrderbackGoodsMapper;
    @Resource
    private JPushUtils jPushUtils;
    @Autowired
    private IMallOrderBackService mallOrderBackService;

    /**
     * 查询退款单
     *
     * @param id 退款单主键
     * @return 退款单
     */
    @Override
    public MallOrderBack selectMallOrderBackById(Long id) {
        return mallOrderBackMapper.selectMallOrderBackById(id);
    }

    /**
     * 查询退款单列表
     *
     * @param mallOrderBack 退款单
     * @return 退款单
     */
    @Override
    public List<MallOrderBack> selectMallOrderBackList(MallOrderBack mallOrderBack) {
        return mallOrderBackMapper.selectMallOrderBackList(mallOrderBack);
    }

    /**
     * 新增退款单
     *
     * @param mallOrderBack 退款单
     * @return 结果
     */
    @Override
    public int insertMallOrderBack(MallOrderBack mallOrderBack) {
        return mallOrderBackMapper.insertMallOrderBack(mallOrderBack);
    }

    /**
     * 修改退款单
     *
     * @param mallOrderBack 退款单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMallOrderBack(MallOrderBack mallOrderBack) {
        MallOrderOrder order = orderOrderService.selectMallOrderOrderById(mallOrderBack.getOrderId());
        MallOrderBack orderBack = mallOrderBackService.selectMallOrderBackById(mallOrderBack.getId());
        List<MallOrderGoodsVO> list = orderGoodsService.selectMallOrderGoodsByOrderId(order.getId());
        List<MallOrderbackGoods> mallOrderbackGoods = mallOrderbackGoodsMapper.selectMallOrderbackGoodsByrefundno(mallOrderBack.getRefundNo());

        if (!Objects.equals(order.getStatus(), "6")) {
            order.setStatus(mallOrderBack.getOrginalStatus());
        }
        if ("1".equals(mallOrderBack.getStatus())) {
            if (!Objects.equals(order.getStatus(), "6")){//判断这个已退货说明前面已经处理过数据了，不需要这里再覆盖数据了
                if (orderBack.getPrice().compareTo(order.getPayment()) < 0) {
                    order.setStatus("1");
                    order.setOrderStatus("1");
                    order.setIsExamine("0");
                } else {
                    order.setReturnAt(DateUtils.getTime());
                    order.setStatus("6");
                    order.setOrderStatus("10");
                }
            }
            //改库存
            for (MallOrderGoodsVO vo : list) {
                goodsProductService.updateMallGoodsProductByParams(vo.getProductId(), vo.getTotal() - vo.getReturnTotal());
            }
        }
        if ("3".equals(mallOrderBack.getStatus())) {
            order.setStatus(mallOrderBack.getOrginalStatus());
            if ("1".equals(mallOrderBack.getOrginalStatus())) {
                if (order.getWarehouseManageId() != null) {
                    order.setOrderStatus("3");
                } else {
                    order.setOrderStatus("2");
                }
            }
            if ("2".equals(mallOrderBack.getOrginalStatus())) {
                order.setOrderStatus("4");
            }
            //回退本次退款商品数量
            for (MallOrderbackGoods backGoods : mallOrderbackGoods) {
                //orderid goodid
                Long orderId = backGoods.getOrderId();
                Long goodsId = backGoods.getGoodsId();
                //根据订单id和商品id查出确定的订单中的商品
                MallOrderGoodsVO orderGoodsVO = orderGoodsService.selectMallOrderGoodsByOrderIdAndGoodsId(orderId, goodsId);
                if (orderGoodsVO != null) {
                    // 安全获取数值，设置默认值
                    Integer orderReturnTotal = orderGoodsVO.getReturnTotal() != null ? orderGoodsVO.getReturnTotal() : 0;
                    Integer backReturnTotal = Integer.valueOf(backGoods.getReturnTotal());

                    // 计算退货总数量（确保不小于0）
                    int calculatedReturnTotal = Math.max(0, orderReturnTotal - backReturnTotal);
                    String returnTotal = String.valueOf(calculatedReturnTotal);

                    // 安全获取可退数量，设置默认值
                    Integer orderReturnableQuantity = orderGoodsVO.getReturnableQuantity() != null ? orderGoodsVO.getReturnableQuantity() : 0;

                    // 计算可退数量（确保不小于0）
                    int calculatedReturnableQuantity = Math.max(0, orderReturnableQuantity + backReturnTotal);
                    String returnableQuantity = String.valueOf(calculatedReturnableQuantity);
                    orderGoodsService.updateMallOrderGoodsByOrderIdAndGoodsId(orderId,goodsId,"3",returnTotal,returnableQuantity);
                }
            }
//            orderGoodsService.updateMallOrderGoodsReturnStatus(mallOrderBack.getOrderId(), "3");
        }
        orderOrderService.updateMallOrderOrder(order);
//        MallOrderbackGoods mallOrderbackGoods = new MallOrderbackGoods();
//        mallOrderbackGoods.setBatchId(mallOrderBack.getRefundNo());
//        mallOrderBack
//        mallOrderbackGoodsMapper.updateMallOrderbackGoodsByBatchId(mallOrderbackGoods);
        mallOrderBack.setUpdateAt(DateUtils.getTime());

        // 同意退款
        if ("1".equals(mallOrderBack.getStatus())) {

            Map<String, String> orderInfoParams = new HashMap<>();
            orderInfoParams.put("orderId", order.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=" + order.getId().toString() + ";i.orderType=" + 0 + ";end";
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("url", url);

                    jPushUtils.jPush(userName, order.getReceiverName() + order.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=" + order.getId().toString() + ";i.orderType=" + 0 + ";end";
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("url", url);

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

            if (order.getSalesmanId() != null) {
                // roleId：1-超级管理员，12-仓库管理员，13-财务，10-分公司管理员，11-业务员
                Map<String, Object> salesmanParams = new HashMap<>();// 线上订单退款成功-业务员查看推送
                salesmanParams.put("roleId", 11);
                salesmanParams.put("salesmanId", order.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=" + order.getId().toString() + ";i.orderType=" + 0 + ";end";
                        JsonObject jsonObject = new JsonObject();
                        jsonObject.addProperty("url", url);

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

        }
        return mallOrderBackMapper.updateMallOrderBack(mallOrderBack);
    }


    /**
     * 批量删除退款单
     *
     * @param ids 需要删除的退款单主键
     * @return 结果
     */
    @Override
    public int deleteMallOrderBackByIds(Long[] ids) {
        return mallOrderBackMapper.deleteMallOrderBackByIds(ids);
    }

    /**
     * 删除退款单信息
     *
     * @param id 退款单主键
     * @return 结果
     */
    @Override
    public int deleteMallOrderBackById(Long id) {
        return mallOrderBackMapper.deleteMallOrderBackById(id);
    }

    // /*
    // * 申请退款
    // * */
    // @Transactional
    // @Override
    // public int applyForRefund(Map<String, Object> params) {
    //     try {
    //         String userId = params.get("userId").toString();
    //         String orderId = params.get("orderId").toString();
    //         String reason = params.get("reason").toString();
    //
    //         String orderGoodsIds = params.get("orderGoodsIds").toString();
    //         String[] orderGoodsIdArray = orderGoodsIds.split(",");
    //
    //         // 退货金额
    //         BigDecimal returnPrice = new BigDecimal(0);
    //         for (String orderGoodsId : orderGoodsIdArray) {
    //             MallOrderGoods orderGoods = orderGoodsService.selectMallOrderGoodsById(Long.parseLong(orderGoodsId));
    //             orderGoods.setReturnStatus("1");
    //             orderGoodsService.updateMallOrderGoods(orderGoods);
    //             returnPrice = returnPrice.add(orderGoods.getPrice());
    //         }
    //
    //         MallOrderOrder orgOrder = orderOrderService.selectMallOrderOrderById(Long.parseLong(orderId));
    //         MallOrderBack back = new MallOrderBack();
    //         back.setOrderId(Long.parseLong(orderId));
    //         back.setReason(reason);
    //         back.setStatus("0");
    //         back.setPrice(returnPrice);
    //         back.setOrginalStatus(orgOrder.getStatus());
    //         back.setCreateAt(DateUtils.getTime());
    //         this.insertMallOrderBack(back);
    //
    //         orgOrder.setStatus("5");
    //         orderOrderService.updateMallOrderOrder(orgOrder);
    //         return 1;
    //     } catch (Exception e) {
    //         return 0;
    //     }
    // }

    /*
     * 申请退款
     * */
    @Transactional
    @Override
    public int applyForRefund(MallOrderOrder mallOrderOrder) {
        try {
            String userId = mallOrderOrder.getUserId().toString();
            String orderId = mallOrderOrder.getOrderId().toString();
            String reason = mallOrderOrder.getReason();

            List<MallOrderGoodsVO> goodsVOList = mallOrderOrder.getGoodsVOList();

            // 退货金额
            int Returnnum = 0;
            BigDecimal returnPrice = new BigDecimal(0);
            for (MallOrderGoodsVO orderGoodsVO : goodsVOList) {
                MallOrderGoods orderGoods = orderGoodsService.selectMallOrderGoodsById(orderGoodsVO.getId());
                orderGoods.setReturnStatus("1");//todo 进行中
                orderGoods.setReturnTotal(orderGoodsVO.getReturnTotal()+orderGoods.getReturnTotal());//本次退货数量+历史退货数量
                orderGoods.setReturnableQuantity(orderGoodsVO.getTotal() - orderGoods.getReturnTotal());//剩余可退货数量 = 商品总数量 - 刚赋值的退货数量
                orderGoodsService.updateMallOrderGoods(orderGoods);
                returnPrice = returnPrice.add(orderGoods.getPrice().multiply(new BigDecimal(orderGoodsVO.getReturnTotal())));

            }


            MallOrderOrder orgOrder = orderOrderService.selectMallOrderOrderById(Long.parseLong(orderId));
            if (returnPrice.compareTo(orgOrder.getPayment()) > 0) {
                returnPrice = orgOrder.getPayment();
            }

            MallOrderBack back = new MallOrderBack();
            back.setOrderId(Long.parseLong(orderId));
            back.setReason(reason);
            back.setStatus("0");
            back.setPrice(returnPrice);
            back.setOrginalStatus(orgOrder.getStatus());
            back.setCreateAt(DateUtils.getTime());
            String string = BackIdGenerator();
            back.setRefundNo(string);
            this.insertMallOrderBack(back);
            List<MallOrderGoodsVO> goodsVOList1 = mallOrderOrder.getGoodsVOList();
            for (MallOrderGoodsVO vo : goodsVOList1) {
                MallOrderbackGoods mallOrderbackGoods = new MallOrderbackGoods();
                BeanUtils.copyProperties(vo, mallOrderbackGoods);
                mallOrderbackGoods.setId(null);
                mallOrderbackGoods.setBatchId(string);
                mallOrderbackGoods.setTotal(vo.getTotal().longValue());
                mallOrderbackGoods.setReturnTotal(vo.getReturnTotal().toString());//退货单退货数量是本次提交数量
                mallOrderbackGoods.setReturnableQuantity(vo.getReturnTotal().longValue());//没有总的退货数量，无法计算
                mallOrderbackGoodsMapper.insertMallOrderbackGoods(mallOrderbackGoods);
            }
            orgOrder.setStatus("5");
            orgOrder.setOrderStatus("9");
            orderOrderService.updateMallOrderOrder(orgOrder);
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    public static String BackIdGenerator() {
        String time = DateUtils.dateTimeNow();
        String randomString = RandomStringUtils.randomNumeric(9);
        return time + randomString;
    }

    /*
     * 取消退款
     * */
    @Transactional
    @Override
    public int cancleRefund(Map<String, Object> params) {
        try {
            String refundId = params.get("refundId").toString();

            MallOrderBack orderBack = this.selectMallOrderBackById(Long.parseLong(refundId));
            List<MallOrderbackGoods> mallOrderbackGoods = mallOrderbackGoodsMapper.selectMallOrderbackGoodsByrefundno(orderBack.getRefundNo());
            orderBack.setStatus("2");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            orderBack.setUpdateAt(formatter.format(new Date()));
            this.updateMallOrderBack(orderBack);

            MallOrderOrder orgOrder = orderOrderService.selectMallOrderOrderById(orderBack.getOrderId());
            orgOrder.setStatus(orderBack.getOrginalStatus());

            if ("1".equals(orderBack.getOrginalStatus())) {
                if (orgOrder.getWarehouseManageId() != null) {
                    orgOrder.setOrderStatus("3");
                } else {
                    orgOrder.setOrderStatus("2");
                }
            }
            if ("2".equals(orderBack.getOrginalStatus())) {
                orgOrder.setOrderStatus("4");
            }
            //回退本次退款商品数量
            for (MallOrderbackGoods backGoods : mallOrderbackGoods) {
                //orderid goodid
                Long orderId = backGoods.getOrderId();
                Long goodsId = backGoods.getGoodsId();
                //根据订单id和商品id查出确定的订单中的商品
                MallOrderGoodsVO orderGoodsVO = orderGoodsService.selectMallOrderGoodsByOrderIdAndGoodsId(orderId, goodsId);
                if (orderGoodsVO != null) {
                    // 安全获取数值，设置默认值
                    Integer orderReturnTotal = orderGoodsVO.getReturnTotal() != null ? orderGoodsVO.getReturnTotal() : 0;
                    Integer backReturnTotal = Integer.valueOf(backGoods.getReturnTotal());

                    // 计算退货总数量（确保不小于0）
                    int calculatedReturnTotal = Math.max(0, orderReturnTotal - backReturnTotal);
                    String returnTotal = String.valueOf(calculatedReturnTotal);

                    // 安全获取可退数量，设置默认值
                    Integer orderReturnableQuantity = orderGoodsVO.getReturnableQuantity() != null ? orderGoodsVO.getReturnableQuantity() : 0;

                    // 计算可退数量（确保不小于0）
                    int calculatedReturnableQuantity = Math.max(0, orderReturnableQuantity + backReturnTotal);
                    String returnableQuantity = String.valueOf(calculatedReturnableQuantity);
                    orderGoodsService.updateMallOrderGoodsByOrderIdAndGoodsId(orderId,goodsId,"4",returnTotal,returnableQuantity);
                }
            }
//            orderGoodsService.updateMallOrderGoodsReturnStatus(orderBack.getOrderId(), "4");

            orderOrderService.updateMallOrderOrder(orgOrder);
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    /*
     * 同意、拒绝退款
     * */
    @Transactional
    @Override
    public int handleRefund(Map<String, Object> params) {
        try {
            String refundId = params.get("refundId").toString();

            MallOrderBack orderBack = this.selectMallOrderBackById(Long.parseLong(refundId));
            if ("0".equals(params.get("isAccept"))) {
                //0是拒绝
                orderBack.setStatus("3");
            } else {
                orderBack.setStatus("1");
            }
            orderBack.setUpdateAt(new Date().toString());
            this.updateMallOrderBack(orderBack);

            MallOrderOrder orgOrder = orderOrderService.selectMallOrderOrderById(orderBack.getOrderId());
            if ("0".equals(params.get("isAccept"))) {
                //0是拒绝
                orgOrder.setStatus(orderBack.getOrginalStatus());
            } else {
                orgOrder.setStatus("6");
            }
            orderOrderService.updateMallOrderOrder(orgOrder);
            return 1;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public List<MallOrderBack> selectMallOrderBackByOrderId(Long orderId) {
        return mallOrderBackMapper.selectMallOrderBackByOrderId(orderId);
    }

    /**
     * 退货金额
     *
     * @param orderId 订单ID
     * @param status  状态
     * @return 结果
     */
    @Override
    public BigDecimal getReturnPrice(Long orderId, String status) {
        return mallOrderBackMapper.getReturnPrice(orderId, status);
    }
}
