package com.fs.live.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.CloudHostUtils;
import com.fs.common.utils.DateUtils;

import com.fs.common.utils.StringUtils;
import com.fs.common.utils.spring.SpringUtils;
import com.fs.company.service.ICompanyService;
import com.fs.config.cloud.CloudHostProper;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.course.domain.FsCoursePlaySourceConfig;
import com.fs.course.mapper.FsCoursePlaySourceConfigMapper;
import com.fs.erp.constant.AfterSalesOrderStatusEnum;
import com.fs.erp.domain.FsJstAftersalePush;
import com.fs.erp.dto.BaseResponse;
import com.fs.erp.dto.ErpOrderQueryRequert;
import com.fs.erp.dto.ErpOrderQueryResponse;
import com.fs.erp.dto.ErpRefundUpdateRequest;
import com.fs.erp.mapper.FsJstAftersalePushMapper;
import com.fs.erp.service.IErpOrderService;
import com.fs.his.config.FsSysConfig;
import com.fs.his.domain.FsHfpayConfig;
import com.fs.his.domain.FsPayConfig;
import com.fs.his.domain.FsUser;
import com.fs.his.domain.MerchantAppConfig;
import com.fs.his.mapper.FsHfpayConfigMapper;
import com.fs.his.mapper.MerchantAppConfigMapper;
import com.fs.his.service.IFsUserService;
import com.fs.his.utils.ConfigUtil;
import com.fs.hisStore.config.FsErpConfig;
import com.fs.hisStore.domain.*;
import com.fs.hisStore.dto.StoreOrderProductDTO;
import com.fs.hisStore.enums.*;
import com.fs.hisStore.param.FsStoreAfterSalesProductParam;
import com.fs.hisStore.service.IFsStoreProductScrmService;
import com.fs.hisStore.service.IFsUserScrmService;
import com.fs.hisStore.vo.FsStoreAfterSalesQueryVO;
import com.fs.hisStore.vo.FsStoreOrderItemVO;
import com.fs.huifuPay.domain.HuiFuRefundResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayRefundRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.live.domain.*;
import com.fs.live.dto.LiveAfterSalesProductDTO;
import com.fs.live.enums.LiveAfterSalesStatusEnum;
import com.fs.live.mapper.*;
import com.fs.live.param.*;
import com.fs.live.service.ILiveOrderItemService;
import com.fs.live.service.ILiveOrderLogsService;
import com.fs.live.service.ILiveOrderService;
import com.fs.live.vo.*;
import com.fs.store.config.StoreConfig;
import com.fs.store.domain.*;
import com.fs.store.service.cache.IFsUserCacheService;
import com.fs.system.service.ISysConfigService;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.http.util.Asserts;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.fs.live.service.ILiveAfterSalesService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import java.util.concurrent.TimeUnit;

/**
 * 售后记录Service业务层处理
 *
 * @author fs
 * @date 2025-07-08
 */
@Slf4j
@Service
public class LiveAfterSalesServiceImpl implements ILiveAfterSalesService {

    @Autowired
    private FsCoursePlaySourceConfigMapper fsCoursePlaySourceConfigMapper;

    @Autowired
    private MerchantAppConfigMapper merchantAppConfigMapper;

    @Autowired
    private ILiveOrderService liveOrderService;

    @Autowired
    private ILiveOrderItemService liveOrderItemService;

    @Autowired
    private LiveAfterSalesMapper baseMapper;

    @Autowired
    private LiveAfterSalesLogsMapper liveAfterSalesLogsMapper;

    @Autowired
    private LiveAfterSalesItemMapper liveAfterSalesItemMapper;

//    @Autowired
//    private FsWarehousesMapper fsWarehousesMapper;

    @Autowired
    private ConfigUtil configUtil;


    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IFsUserScrmService userService;

    @Autowired
    private IErpOrderService erpOrderService;
    @Autowired
    @Qualifier("erpOrderServiceImpl")
    private IErpOrderService gyOrderService;
    @Autowired
    @Qualifier("hzOMSErpOrderServiceImpl")
    private IErpOrderService hzOMSerpOrderService;

    @Autowired
    @Qualifier("dfOrderServiceImpl")
    private IErpOrderService dfOrderService;

    @Autowired
    @Qualifier("wdtErpOrderServiceImpl")
    private IErpOrderService wdtErpOrderService;

    @Autowired
    @Qualifier("JSTErpOrderServiceImpl")
    private IErpOrderService jSTOrderService;
    @Autowired
    @Qualifier("k9OrderScrmServiceImpl")
    private IErpOrderService k9OrderService;


    @Autowired
    private LiveOrderPaymentMapper liveOrderPaymentMapper;

//    @Autowired
//    private IFsWarehousesCacheService fsWarehouseCacheService;

    @Autowired
    private FsJstAftersalePushMapper fsJstAftersalePushMapper;
    @Autowired
    private LiveOrderMapper liveOrderMapper;
//    @Autowired
//    private FsStoreDeliversMapper fsStoreDeliversMapper;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 查询售后记录
     *
     * @param id 售后记录主键
     * @return 售后记录
     */
    @Override
    public LiveAfterSales selectLiveAfterSalesById(Long id)
    {
        return baseMapper.selectLiveAfterSalesById(id);
    }

    /**
     * 查询售后记录列表
     *
     * @param liveAfterSales 售后记录
     * @return 售后记录
     */
    @Override
    public List<LiveAfterSales> selectLiveAfterSalesList(LiveAfterSales liveAfterSales)
    {
        return baseMapper.selectLiveAfterSalesList(liveAfterSales);
    }

    @Autowired
    private IFsUserCacheService fsUserCacheService;

//    @Autowired
//    private FsStoreDeliversService fsStoreDeliversService;


    @Override
    public List<LiveAfterSalesVo> selectLiveAfterSalesVoListExport(LiveAfterSalesVo liveAfterSales) {
        List<LiveAfterSalesVo> liveAfterSalesVos = baseMapper.selectLiveAfterSalesVoListExport(liveAfterSales);
        List<Long> orderIds = new ArrayList<>();
        Map<Long, List<LiveOrderItemListUVO>> orderItemMap = new HashMap<>();
        if(null != liveAfterSalesVos && !liveAfterSalesVos.isEmpty()){
            orderIds = liveAfterSalesVos.stream().map(e -> e.getOrderId()).collect(Collectors.toList());
            if(null != orderIds && !orderIds.isEmpty()){
                List<LiveOrderItemListUVO> liveOrderItemListUVOS = liveOrderItemMapper.selectLiveOrderItemListUVOByOrderIds(orderIds);
                orderItemMap = liveOrderItemListUVOS.stream()
                        .collect(Collectors.groupingBy(LiveOrderItemListUVO::getOrderId));
            }
        }
        boolean mapEmpty = orderItemMap.isEmpty();
        for (LiveAfterSalesVo item : liveAfterSalesVos) {
            if(ObjectUtil.isNotNull(item.getUserId())) {
                FsUser fsUser = fsUserCacheService.selectFsUserById(item.getUserId());
                if(ObjectUtil.isNotNull(fsUser)) {
                    item.setUserName(String.format("%s_%s",fsUser.getUserId(),fsUser.getNickname()));
                }
            }

            if(ObjectUtil.isNull(item.getCompanyUserNickName())) {
                item.setCompanyUserNickName("-");
            }

            if(ObjectUtil.isNull(item.getCompanyName())){
                item.setCompanyName("-");
            }

            if(!mapEmpty && orderItemMap.containsKey(item.getOrderId())){
                List<LiveOrderItemListUVO> liveOrderItemListUVOS = orderItemMap.get(item.getOrderId());
                for (LiveOrderItemListUVO liveOrderItemListUVO : liveOrderItemListUVOS) {
                    try {
                        JSONObject jsO = JSONObject.parseObject(liveOrderItemListUVO.getJsonInfo());
                        item.setProductName(StringUtils.isNotBlank(item.getProductName()) ? item.getProductName() + "," + jsO.getString("productName") : jsO.getString("productName"));
                        item.setProductBarCode(StringUtils.isNotBlank(item.getProductBarCode()) ? item.getProductBarCode() + "," + jsO.getString("barCode") : jsO.getString("barCode"));
                        item.setSku(StringUtils.isNotBlank(item.getSku()) ? item.getSku() + "," + jsO.getString("sku") : jsO.getString("sku"));
                        item.setNum(StringUtils.isNotBlank(item.getNum()) ? item.getNum() + "," + jsO.getString("num") : jsO.getString("num"));
                        item.setPrice(StringUtils.isNotBlank(item.getPrice()) ? item.getPrice() + "," + jsO.getString("price") : jsO.getString("price"));
                        item.setCost(StringUtils.isNotBlank(item.getCost()) ? item.getCost() + "," + liveOrderItemListUVO.getCost() : liveOrderItemListUVO.getCost());
                        item.setCateName(StringUtils.isNotBlank(item.getCateName()) ? item.getCateName() + "," + liveOrderItemListUVO.getCateName() : liveOrderItemListUVO.getCateName());
                    } catch (Exception ex) {
                        log.error("售后订单商品信息转换异常",ex);
                    }
                }
            }

        }
        return liveAfterSalesVos;
    }
    /**
     * 查询售后记录列表
     *
     * @param liveAfterSales 售后记录
     * @return 售后记录
     */
    @Override
    public List<LiveAfterSalesVo> selectLiveAfterSalesVoList(LiveAfterSalesVo liveAfterSales)
    {
        List<LiveAfterSalesVo> liveAfterSalesVos = baseMapper.selectLiveAfterSalesVoList(liveAfterSales);
        List<Long> orderIds = new ArrayList<>();
        Map<Long, List<LiveOrderItemListUVO>> orderItemMap = new HashMap<>();
        if(null != liveAfterSalesVos && !liveAfterSalesVos.isEmpty()){
            orderIds = liveAfterSalesVos.stream().map(e -> e.getOrderId()).collect(Collectors.toList());
            if(null != orderIds && !orderIds.isEmpty()){
                List<LiveOrderItemListUVO> liveOrderItemListUVOS = liveOrderItemMapper.selectLiveOrderItemListUVOByOrderIds(orderIds);
                orderItemMap = liveOrderItemListUVOS.stream()
                        .collect(Collectors.groupingBy(LiveOrderItemListUVO::getOrderId));
            }
        }
        boolean mapEmpty = orderItemMap.isEmpty();
        for (LiveAfterSalesVo item : liveAfterSalesVos) {
            if(ObjectUtil.isNotNull(item.getUserId())) {
                FsUser fsUser = fsUserCacheService.selectFsUserById(item.getUserId());
                if(ObjectUtil.isNotNull(fsUser)) {
                    item.setUserName(String.format("%s_%s",fsUser.getUserId(),fsUser.getNickname()));
                }
            }

            if(ObjectUtil.isNull(item.getCompanyUserNickName())) {
                item.setCompanyUserNickName("-");
            }

            if(ObjectUtil.isNull(item.getCompanyName())){
                item.setCompanyName("-");
            }

            if(!mapEmpty && orderItemMap.containsKey(item.getOrderId())){
                List<LiveOrderItemListUVO> liveOrderItemListUVOS = orderItemMap.get(item.getOrderId());
                for (LiveOrderItemListUVO liveOrderItemListUVO : liveOrderItemListUVOS) {
                    try {
                        JSONObject jsO = JSONObject.parseObject(liveOrderItemListUVO.getJsonInfo());
                        item.setProductName(StringUtils.isNotBlank(item.getProductName()) ? item.getProductName() + "," + jsO.getString("productName") : jsO.getString("productName"));
                        item.setProductBarCode(StringUtils.isNotBlank(item.getProductBarCode()) ? item.getProductBarCode() + "," + jsO.getString("barCode") : jsO.getString("barCode"));
                        item.setSku(StringUtils.isNotBlank(item.getSku()) ? item.getSku() + "," + jsO.getString("sku") : jsO.getString("sku"));
                        item.setNum(StringUtils.isNotBlank(item.getNum()) ? item.getNum() + "," + jsO.getString("num") : jsO.getString("num"));
                        item.setPrice(StringUtils.isNotBlank(item.getPrice()) ? item.getPrice() + "," + jsO.getString("price") : jsO.getString("price"));
                        item.setCost(StringUtils.isNotBlank(item.getCost()) ? item.getCost() + "," + liveOrderItemListUVO.getCost() : liveOrderItemListUVO.getCost());
                        item.setCateName(StringUtils.isNotBlank(item.getCateName()) ? item.getCateName() + "," + liveOrderItemListUVO.getCateName() : liveOrderItemListUVO.getCateName());
                    } catch (Exception ex) {
                        log.error("售后订单商品信息转换异常",ex);
                    }
                }
            }
//            if (StringUtils.isNotBlank(item.getItemJson())) {
//                try {
//                    JSONArray array = JSONObject.parseArray(item.getItemJson());
//                    if(null != array && !array.isEmpty()){
//                        for (Object o : array) {
//                            JSONObject jsO = (JSONObject) o;
//                            item.setProductName(StringUtils.isNotBlank(item.getProductName())?item.getProductName()+","+jsO.getString("productName"):jsO.getString("productName"));
//                            item.setProductBarCode(StringUtils.isNotBlank(item.getProductBarCode())?item.getProductBarCode()+","+jsO.getString("barCode"):jsO.getString("barCode"));
//                            item.setSku(StringUtils.isNotBlank(item.getSku())?item.getSku()+","+jsO.getString("sku"):jsO.getString("sku"));
//                            item.setNum(null != item.getNum()?item.getNum() +jsO.getInteger("num"):jsO.getInteger("num"));
//                            item.setPrice(null != item.getPrice()?item.getPrice().add(jsO.getBigDecimal("price")):jsO.getBigDecimal("price"));
//                        }
//                    }
//                } catch (Exception ex) {
//                    log.error("售后订单商品信息转换异常",ex);
//                }
//
//            }


//            if(ObjectUtil.isNotNull(item.getOrderId())){
//                List<FsStoreDelivers> byOrderIdWithType = fsStoreDeliversService.findByOrderIdWithType(item.getOrderId(), 1);
//                if(CollectionUtils.isNotEmpty(byOrderIdWithType)) {
//                    FsStoreDelivers delivers = byOrderIdWithType.get(0);
//                    item.setDeliveryStatus(String.valueOf(delivers.getStatus()));
//                    item.setDeliveryId(delivers.getDeliverId());
//                }
//            }

        }
        return liveAfterSalesVos;
    }

    @Override
    @Transactional
    public R cancel(LiveAfterSalesCancelParam param)  throws ParseException{
        LiveAfterSales storeAfterSales = baseMapper.selectLiveAfterSalesById(param.getSalesId());
        if (storeAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if (storeAfterSales.getSalesStatus()!=0) {
            throw new CustomException("非法操作");
        }

        LiveOrder order = liveOrderService.selectLiveOrderByOrderId(String.valueOf(storeAfterSales.getOrderId()));
        order.setStatus(storeAfterSales.getOrderStatus());
        order.setRefundStatus(String.valueOf(OrderInfoEnum.REFUND_STATUS_0.getValue()));
        liveOrderService.updateLiveOrder(order);
        storeAfterSales.setSalesStatus(2);
        LiveAfterSalesLogs storeAfterSalesStatus = new LiveAfterSalesLogs();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(6);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_6.getDesc()+" "+param.getRemark());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        storeAfterSalesStatus.setOperator(param.getOperator());
        liveAfterSalesLogsMapper.insertLiveAfterSalesLogs(storeAfterSalesStatus);
        if (ObjectUtil.equal(order.getStatus(), 2)) {
            FsJstAftersalePush fsJstAftersalePush = new FsJstAftersalePush();
            fsJstAftersalePush.setOrderId(order.getOrderCode());
            fsJstAftersalePush.setTaskStatus(TaskStatusEnum.PENDING.getCode());
            fsJstAftersalePush.setType(String.valueOf(AfterSalesOrderStatusEnum.CLOSED.getIndex()));
            fsJstAftersalePush.setRetryCount(0);
            fsJstAftersalePush.setAfterSaleId(String.valueOf(storeAfterSales.getId()));
            fsJstAftersalePushMapper.insert(fsJstAftersalePush);
        } else {
            //创建新的OMS订单
            if (storeAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_1.getValue()) ) {
                if(StringUtils.isNotEmpty(order.getExtendOrderId())){
                    //更新订单code
                    String orderSn = OrderCodeUtils.getOrderSn();
                    LiveOrder orderMap=new LiveOrder();
                    orderMap.setOrderId(order.getOrderId());
                    orderMap.setOrderCode(orderSn);
                    orderMap.setStatus(order.getStatus());
                    liveOrderService.updateLiveOrder(orderMap);
                    liveOrderItemMapper.updateFsStoreOrderCode(order.getOrderId(),orderSn);
                    //生成新的订单
                    liveOrderService.createOmsOrder(order.getOrderId());
                }
            }
        }
        baseMapper.updateLiveAfterSales(storeAfterSales);
        return R.ok();
    }

    @Override
    @Transactional
    public R applyForAfterSales(String userId, LiveAfterSalesParam param) {
        log.info("申请退款请求信息:"+JSONUtil.toJsonStr(param));

        // 使用Redis分布式锁，确保同一订单只能有一个服务器处理申请售后 因为卓美有一个订单生成了三个售后订单，数据一摸一样，除了id
        String lockKey = "live:afterSales:apply:" + param.getOrderCode();
        RLock lock = redissonClient.getLock(lockKey);

        try {
            // 尝试获取锁，等待时间3秒，锁过期时间30秒
            boolean locked = lock.tryLock(3, 30, TimeUnit.SECONDS);
            if (!locked) {
                log.warn("申请售后订单锁获取失败，订单号：{}", param.getOrderCode());
                return R.error("系统繁忙，请稍后重试");
            }

            log.info("申请售后订单锁获取成功，订单号：{}", param.getOrderCode());

            LiveOrder order=liveOrderService.selectOrderIdByOrderCode(param.getOrderCode());

            // 查询配置：是否删除历史售后数据
            try {
                String deleteAfterSalesConfig = configService.selectConfigByKey("delete_after_sales");
                if (StringUtils.isNotEmpty(deleteAfterSalesConfig) && "true".equalsIgnoreCase(deleteAfterSalesConfig.trim())) {
                    // 查询历史售后数据，将 is_del 设置为 1
                    if (order != null && order.getOrderId() != null) {
                        LiveAfterSales queryAfterSales = new LiveAfterSales();
                        queryAfterSales.setOrderId(order.getOrderId());
                        List<LiveAfterSales> historyAfterSalesList = baseMapper.selectLiveAfterSalesList(queryAfterSales);
                        if (historyAfterSalesList != null && !historyAfterSalesList.isEmpty()) {
                            for (LiveAfterSales historyAfterSales : historyAfterSalesList) {
                                if (historyAfterSales.getIsDel() != null && historyAfterSales.getIsDel() == 0) {
                                    LiveAfterSales updateAfterSales = new LiveAfterSales();
                                    updateAfterSales.setId(historyAfterSales.getId());
                                    updateAfterSales.setIsDel(1);
                                    baseMapper.updateLiveAfterSales(updateAfterSales);
                                    log.info("删除历史售后数据，售后ID：{}，订单ID：{}", historyAfterSales.getId(), order.getOrderId());
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("查询或更新历史售后数据失败", e);
            }
            if(!order.getUserId().equals(userId)){
                throw new CustomException("非法操作");
            }
            if(order.getStatus()==0){
                return R.error("未支付订单不能申请售后");
            }
            if("1".equals(configUtil.generateConfigByKey(SysConfigEnum.HIS_CONFIG.getKey()).getString("erpOpen"))
                    && StringUtils.isEmpty(order.getExtendOrderId())
                    && !CloudHostUtils.hasCloudHostName("康年堂")){
                log.info("erpOpen：{}",configUtil.generateConfigByKey(SysConfigEnum.HIS_CONFIG.getKey()).getString("erpOpen"));
                return R.error("仓库未生成订单,暂时不能申请退款,请联系客服");
            }
            if(order.getStatus()== OrderInfoEnum.STATUS_NE3.getValue()){
                return R.error("已取消订单不能申请售后");
            }
            if(order.getStatus()== OrderInfoEnum.STATUS_NE1.getValue()){
                return R.error("已提交申请,等待处理");
            }
//        if(storeAfterSalesParam.getRefundAmount().compareTo(order.getPayPrice())==1){
//            return R.error("退款金额不能大于支付金额");
//        }
            //已完成订单七天后不能申请退款
            if(order.getStatus().equals(OrderInfoEnum.STATUS_3.getValue())) {
                String json=configService.selectConfigByKey("store.config");
                com.fs.hisStore.config.StoreConfig config=JSONUtil.toBean(json, com.fs.hisStore.config.StoreConfig.class);
                //已完成订单
                if (order.getFinishTime() != null) {
                    if (config.getStoreAfterSalesDay() != null && config.getStoreAfterSalesDay() > 0) {
                        //判断完成时间是否超过指定时间
                        Calendar calendarAfterSales = new GregorianCalendar();
                        calendarAfterSales.setTime(order.getFinishTime());
                        calendarAfterSales.add(calendarAfterSales.DATE, config.getStoreAfterSalesDay()); //把日期往后增加一天,整数  往后推,负数往前移动
                        if (calendarAfterSales.getTime().getTime() < new Date().getTime()) {
                            return R.error("此订单已超过售后时间,不能提交售后");
                        }

                    }
                }
            }
            //商品除去优惠后的总价格
            //BigDecimal totalPrice = BigDecimal.ZERO;
            //拿到所有的商品
            List<LiveOrderItem> orderItems = liveOrderItemService.selectCheckedByOrderId(order.getOrderId());
            for (LiveOrderItem item : orderItems) {
                StoreOrderProductDTO cartInfo = JSONObject.parseObject(item.getJsonInfo(), StoreOrderProductDTO.class);
                LiveAfterSalesProductParam prosuctParam = param.getProductList().stream().filter(p -> p.getProductId().equals(item.getProductId())).findFirst().orElse(new LiveAfterSalesProductParam());
                if (prosuctParam.getProductId() != null) {
//                //商品优惠前总金额
//                BigDecimal totalAmountOfGoods = NumberUtil.mul(cartInfo.getPrice(), item.getNum());
//                //商品优惠总金额
//                BigDecimal commodityDiscountAmount = NumberUtil.mul(NumberUtil.div(totalAmountOfGoods, NumberUtil.sub(order.getTotalPrice(), order.getPayPostage())), order.getCouponPrice());
//                //商品优惠后总金额
//                totalPrice = NumberUtil.add(totalPrice, NumberUtil.sub(totalAmountOfGoods, commodityDiscountAmount));
                    item.setIsAfterSales(1);
                    LiveOrderItem orderItem=new LiveOrderItem();
//                BeanUtil.copyProperties(item, orderItem);
                    try {
                        BeanUtils.copyProperties(orderItem,item);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    }
                    liveOrderItemService.updateLiveOrderItem(orderItem);

                }
            }
            //更新订单状态
            Integer orderStatus=order.getStatus();
            order.setStatus(OrderInfoEnum.STATUS_NE1.getValue());
            order.setRefundStatus(String.valueOf(OrderInfoEnum.REFUND_STATUS_1.getValue()));
            order.setRefundExplain(param.getReasons());
            order.setCancelReason(param.getExplains());
            order.setIsAfterSales(1);
            order.setRefundTime(new Date());
            liveOrderService.updateLiveOrder(order);
            //生成售后订单
            LiveAfterSales storeAfterSales = new LiveAfterSales();
            storeAfterSales.setOrderId(order.getOrderId());
            storeAfterSales.setRefundAmount(param.getRefundAmount());
            storeAfterSales.setRefundType(param.getServiceType());
            storeAfterSales.setReasons(param.getReasons());
            storeAfterSales.setExplains(param.getExplains());
            storeAfterSales.setExplainImg(param.getExplainImg());
            storeAfterSales.setStatus(AfterSalesStatusEnum.STATUS_0.getValue());
            storeAfterSales.setSalesStatus(0);
            storeAfterSales.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
            storeAfterSales.setIsDel(0);
            storeAfterSales.setOrderStatus(orderStatus);
            storeAfterSales.setUserId(Long.valueOf(userId));
            storeAfterSales.setCompanyId(order.getCompanyId());
            storeAfterSales.setCompanyUserId(order.getCompanyUserId());
            liveAfterSalesService.insertLiveAfterSales(storeAfterSales);
            //售后商品详情
            for (LiveAfterSalesProductParam productParam : param.getProductList()) {
                LiveOrderItem item = orderItems.stream().filter(p -> p.getProductId().equals(productParam.getProductId())).findFirst().orElse(new LiveOrderItem());
                LiveAfterSalesItem storeAfterSalesItem = new LiveAfterSalesItem();
                storeAfterSalesItem.setAfterSalesId(storeAfterSales.getId());
                storeAfterSalesItem.setProductId(item.getProductId());
                storeAfterSalesItem.setJsonInfo(item.getJsonInfo());
                storeAfterSalesItem.setIsDel(0);
                liveAfterSalesItemMapper.insertLiveAfterSalesItem(storeAfterSalesItem);
            }
            //操作记录
            LiveAfterSalesLogs storeAfterSalesStatus = new LiveAfterSalesLogs();
            storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
            storeAfterSalesStatus.setChangeType(0);
            storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_0.getDesc());
            storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
            FsUserScrm user=userService.selectFsUserById(Long.valueOf(userId));
            storeAfterSalesStatus.setOperator(user.getNickname());
            liveAfterSalesLogsMapper.insertLiveAfterSalesLogs(storeAfterSalesStatus);

//        //更新OMS
            IErpOrderService erpOrderService = getErpService();
            ErpRefundUpdateRequest request=new ErpRefundUpdateRequest();
            request.setTid(order.getOrderCode());
            request.setOid(order.getOrderCode());
            request.setRefund_state(1);
            request.setStoreAfterSalesId(storeAfterSales.getId());
            request.setOrderStatus(orderStatus);
            if (StringUtils.isNotBlank(order.getExtendOrderId())){
                BaseResponse response=erpOrderService.refundUpdateLive(request);
                if(response.getSuccess()){
                    return R.ok();
                }
                else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error(response.getErrorDesc());
                }
            }
            return R.ok();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
                log.info("申请售后订单锁释放成功，订单号：{}", param.getOrderCode());
            }
        }
    }

    @Override
    public List<LiveAfterSalesQueryVO> selectLiveAfterSalesListQuery(LiveAfterSalesQueryParam param) {
        List<LiveAfterSalesQueryVO>  list=baseMapper.selectLiveAfterSalesListQuery(param);
        for(LiveAfterSalesQueryVO vo:list){
            LiveAfterSalesItem map=new LiveAfterSalesItem();
            map.setAfterSalesId(vo.getId());
            List<LiveAfterSalesItem>  items=liveAfterSalesItemMapper.selectLiveAfterSalesItemByAfterId(vo.getId());
            vo.setItems(items);
        }
        return list;
    }

    @Override
    public Integer selectLiveAfterSalesCount(long userId, int salesStatus) {
        return baseMapper.selectLiveAfterSalesCount(userId, salesStatus);
    }

    private IErpOrderService getErpService() {
        FsSysConfig sysConfig = configUtil.getSysConfig();
        Integer erpOpen = sysConfig.getErpOpen();
        if (erpOpen != null && erpOpen == 1){
            //判断erp类型
            Integer erpType = sysConfig.getErpType();
            if (erpType != null){
                IErpOrderService erpOrderService = null;
                if (erpType == 1){
                    //管易
                    erpOrderService =  gyOrderService;
                } else if (erpType == 2){
                    //旺店通
                    erpOrderService =  wdtErpOrderService;
                } else if (erpType == 3){
                    //
                    erpOrderService =  hzOMSerpOrderService;
                } else if (erpType == 4){
                    //代服
                    erpOrderService =  dfOrderService;
                }else if(erpType == 5){
                    erpOrderService=jSTOrderService;
                }else if(erpType == 6){
                    erpOrderService=k9OrderService;
                }
                return erpOrderService;


            }
        }
        return null;
    }

    @Override
    public R audit2(LiveAfterSalesAudit2Param param) {
        LiveAfterSales storeAfterSales = baseMapper.selectLiveAfterSalesById(param.getSalesId());
        if (storeAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if (!storeAfterSales.getStatus().equals(AfterStatusEnum.STATUS_2.getValue())) {
            throw new CustomException("非法操作");
        }
        //退款退货 仓库审核
        storeAfterSales.setStatus(3);
        baseMapper.updateLiveAfterSales(storeAfterSales);
        LiveAfterSalesLogs storeAfterSalesStatus = new LiveAfterSalesLogs();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(3);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_3.getDesc());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        storeAfterSalesStatus.setOperator(param.getOperator());
        liveAfterSalesLogsMapper.insertLiveAfterSalesLogs(storeAfterSalesStatus);

        return R.ok("操作成功");
    }

    @Autowired
    private ILiveAfterSalesService liveAfterSalesService;
    @Override
    public R refundMoney(LiveAfterSalesRefundParam param) {
        LiveAfterSales liveAfterSales = liveAfterSalesService.selectLiveAfterSalesById(param.getSalesId());
        if(ObjectUtil.isNull(liveAfterSales)) {
            throw new IllegalArgumentException("售后单不存在！");
        }
        if (!liveAfterSales.getStatus().equals(AfterStatusEnum.STATUS_3.getValue())) {
            throw new CustomException("非法操作");
        }
        liveAfterSales.setRefundAmount(param.getRefundAmount());
        return liveOrderService.refundOrderMoney(liveAfterSales.getOrderId(),liveAfterSales);
    }

    /**
     * 新增售后记录
     *
     * @param liveAfterSales 售后记录
     * @return 结果
     */
    @Override
    public int insertLiveAfterSales(LiveAfterSales liveAfterSales)
    {
        liveAfterSales.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertLiveAfterSales(liveAfterSales);
    }

    /**
     * 修改售后记录
     *
     * @param liveAfterSales 售后记录
     * @return 结果
     */
    @Override
    public int updateLiveAfterSales(LiveAfterSales liveAfterSales)
    {

        return baseMapper.updateLiveAfterSales(liveAfterSales);
    }

    /**
     * 批量删除售后记录
     *
     * @param ids 需要删除的售后记录主键
     * @return 结果
     */
    @Override
    public int deleteLiveAfterSalesByIds(Long[] ids)
    {
        return baseMapper.deleteLiveAfterSalesByIds(ids);
    }

    /**
     * 删除售后记录信息
     *
     * @param id 售后记录主键
     * @return 结果
     */
    @Override
    public int deleteLiveAfterSalesById(Long id)
    {
        return baseMapper.deleteLiveAfterSalesById(id);
    }

    @Override
    public List<LiveAfterSalesListUVO> selectLiveAfterSalesListUVO(LiveAfterSalesListUParam param) {
        List<LiveAfterSalesListUVO> list = baseMapper.selectLiveAfterSalesListUVO(param);
        for (LiveAfterSalesListUVO vo : list) {
            LiveAfterSalesItem map = new LiveAfterSalesItem();
            map.setAfterSalesId(vo.getId());
            List<LiveAfterSalesItem> items = liveAfterSalesItemMapper.selectLiveAfterSalesItemList(map);
            vo.setItems(items);
        }
        return list;
    }

    @Override
    public List<LiveAfterSales> selectLiveAfterSalesByDoAudit() {
        return baseMapper.selectLiveAfterSalesByDoAudit();
    }



    @Override
    public R audit1(LiveAfterSalesAudit1Param param) {
        LiveAfterSales liveAfterSales = baseMapper.selectLiveAfterSalesById(param.getSalesId());
        if (liveAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if (!liveAfterSales.getStatus().equals(AfterStatusEnum.STATUS_0.getValue())) {
            throw new CustomException("非法操作");
        }
        //仅退款
        if(liveAfterSales.getRefundType().equals(0)){
            //仅退款未发货处理
            if(liveAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_1.getValue())){
                //审核通过
                liveAfterSales.setStatus(3);
                baseMapper.updateLiveAfterSales(liveAfterSales);
            }
            //仅退款待收货处理
            else if(liveAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_2.getValue())){
                liveAfterSales.setStatus(2);
                baseMapper.updateLiveAfterSales(liveAfterSales);
            //已完成 退货退款
            }
            LiveAfterSalesLogs salesLogs = new LiveAfterSalesLogs();
            salesLogs.setStoreAfterSalesId(liveAfterSales.getId());
            salesLogs.setChangeType(1);
            salesLogs.setChangeMessage(AfterSalesStatusEnum.STATUS_1.getDesc());
            salesLogs.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
            salesLogs.setOperator(param.getOperator());
            liveAfterSalesLogsMapper.insertLiveAfterSalesLogs(salesLogs);
        }
        //退款退货
        else if(liveAfterSales.getRefundType().equals(1)){
            String json=configService.selectConfigByKey("store.config");
            StoreConfig config=JSONUtil.toBean(json,StoreConfig.class);
            LiveOrder order=liveOrderMapper.selectLiveOrderByOrderId(String.valueOf(liveAfterSales.getOrderId()));
            if(order.getStoreHouseCode()!=null){
                if(order.getStoreHouseCode().equals("CK01")){
                    liveAfterSales.setConsignee(config.getRefundConsignee());
                    liveAfterSales.setPhoneNumber(config.getRefundPhoneNumber());
                    liveAfterSales.setAddress(config.getRefundAddress());
                }
                else  if(order.getStoreHouseCode().equals("WHSP001")){
                    //todo
                    liveAfterSales.setConsignee("田伟");
                    liveAfterSales.setPhoneNumber("19318102192");
                    liveAfterSales.setAddress("湖北省武汉市东西湖区国东一路5号2栋");
                }
            }
            else{
                liveAfterSales.setConsignee(config.getRefundConsignee());
                liveAfterSales.setPhoneNumber(config.getRefundPhoneNumber());
                liveAfterSales.setAddress(config.getRefundAddress());
            }
            //退款退货
            liveAfterSales.setStatus(1);
            baseMapper.updateLiveAfterSales(liveAfterSales);
            LiveAfterSalesLogs salesLogs  = new LiveAfterSalesLogs();
            salesLogs.setStoreAfterSalesId(liveAfterSales.getId());
            salesLogs.setChangeType(1);
            salesLogs.setChangeMessage(AfterSalesStatusEnum.STATUS_1.getDesc());
            salesLogs.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
            salesLogs.setOperator(param.getOperator());
            liveAfterSalesLogsMapper.insertLiveAfterSalesLogs(salesLogs);
        }

        return R.ok("操作成功");

    }

    @Override
    public R addDelivery(LiveAfterSalesDeliveryParam param) {
        LiveAfterSales storeAfterSales = baseMapper.selectLiveAfterSalesById(param.getId());
        if (storeAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if (!storeAfterSales.getStatus().equals(OrderInfoEnum.STATUS_1.getValue())) {
            throw new CustomException("未审核订单不能提交物流信息");
        }
        storeAfterSales.setStatus(2);
        storeAfterSales.setDeliverySn(param.getDeliverySn());
        storeAfterSales.setDeliveryName(param.getDeliveryName());

        //操作记录
        LiveAfterSalesLogs logs = new LiveAfterSalesLogs();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(2);
        FsUserScrm user = userService.selectFsUserByUserId(storeAfterSales.getUserId());
        logs.setOperator(user.getNickname());
        logs.setStoreAfterSalesId(storeAfterSales.getId());
        logs.setChangeMessage(OrderInfoEnum.STATUS_2.getDesc());
        liveAfterSalesLogsMapper.insertLiveAfterSalesLogs(logs);

        baseMapper.updateLiveAfterSales(storeAfterSales);
        return R.ok();
    }



    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public R applyAfterSales(String uesrId, LiveAfterSalesApplyParam param) {
//        LiveOrder order = liveOrderService.selectLiveOrderByOrderId(String.valueOf(param.getOrderId()));
//        if (!order.getUserId().equals(uesrId)) {
//            throw new CustomException("非法操作");
//        }
//        Set<Integer> notAllowRefundStatusSet = new HashSet<>();
//        notAllowRefundStatusSet.add(-1);
//        notAllowRefundStatusSet.add(-2);
//        notAllowRefundStatusSet.add(-3);
//        notAllowRefundStatusSet.add(0);
////        notAllowRefundStatusSet.add(3);
//        if(notAllowRefundStatusSet.contains(order.getStatus())){
//            throw new CustomException("该订单不可申请售后");
//        }
//        if(StringUtils.isEmpty(order.getExtendOrderId())){
//            return R.error("仓库未生成订单,暂时不能申请退款,请联系客服");
//        }
//        if(order.getStatus()== OrderInfoEnum.STATUS_NE3.getValue()){
//            return R.error("已取消订单不能申请售后");
//        }
//        if(order.getStatus()== OrderInfoEnum.STATUS_NE1.getValue()){
//            return R.error("已提交申请,等待处理");
//        }
//
//        if(order.getStatus().equals(OrderInfoEnum.STATUS_3.getValue())) {
//            String json=configService.selectConfigByKey("store.config");
//            StoreConfig config= JSONUtil.toBean(json,StoreConfig.class);
//            //已完成订单
//            if (order.getFinishTime() != null) {
//                if (config.getStoreAfterSalesDay() != null && config.getStoreAfterSalesDay() > 0) {
//                    //判断完成时间是否超过指定时间
//                    Calendar calendarAfterSales = new GregorianCalendar();
//                    calendarAfterSales.setTime(order.getFinishTime());
//                    calendarAfterSales.add(calendarAfterSales.DATE, config.getStoreAfterSalesDay()); //把日期往后增加一天,整数  往后推,负数往前移动
//                    if (calendarAfterSales.getTime().getTime() < new Date().getTime()) {
//                        return R.error("此订单已超过售后时间,不能提交售后");
//                    }
//
//                }
//            }
//        }
//
//        LiveOrderItem liveOrderItem = new LiveOrderItem();
//        liveOrderItem.setOrderId(param.getOrderId());
//        List<LiveOrderItem> orderItems = liveOrderItemService.selectLiveOrderItemList(liveOrderItem);
//        for (LiveOrderItem item : orderItems) {
//            LiveAfterSalesProductDTO prosuctParam = param.getProductList().stream().filter(p -> p.getProductId().equals(item.getProductId())).findFirst().orElse(new LiveAfterSalesProductDTO());
//            if (prosuctParam.getProductId() != null) {
////                //商品优惠前总金额
////                BigDecimal totalAmountOfGoods = NumberUtil.mul(cartInfo.getPrice(), item.getNum());
////                //商品优惠总金额
////                BigDecimal commodityDiscountAmount = NumberUtil.mul(NumberUtil.div(totalAmountOfGoods, NumberUtil.sub(order.getTotalPrice(), order.getPayPostage())), order.getCouponPrice());
////                //商品优惠后总金额
////                totalPrice = NumberUtil.add(totalPrice, NumberUtil.sub(totalAmountOfGoods, commodityDiscountAmount));
//                item.setIsAfterSales(1);
//                LiveOrderItem orderItem = new LiveOrderItem();
//                BeanUtil.copyProperties(item, orderItem);
//                liveOrderItemService.updateLiveOrderItem(orderItem);
//
//            }
//        }
//        //更新订单状态
//        Integer orderStatus = order.getStatus();
//        order.setStatus(OrderInfoEnum.STATUS_NE1.getValue());
//        order.setRefundStatus(String.valueOf(OrderInfoEnum.REFUND_STATUS_1.getValue()));
//        order.setRefundReason(param.getReasons());
//        order.setRefundExplain(param.getExplains());
//        order.setRefundTime(new Date());
//        liveOrderService.updateLiveOrder(order);
//        //生成售后订单
//        LiveAfterSales storeAfterSales = new LiveAfterSales();
//        storeAfterSales.setOrderId(order.getOrderId());
//        storeAfterSales.setStoreId(order.getStoreId());
//        storeAfterSales.setDeptId(order.getDeptId());
//        storeAfterSales.setRefundAmount(param.getRefundAmount());
//        storeAfterSales.setRefundType(param.getRefundType());
//        storeAfterSales.setReasons(param.getReasons());
//        storeAfterSales.setExplains(param.getExplains());
//        storeAfterSales.setExplainImg(param.getExplainImg());
//        storeAfterSales.setStatus(AfterSalesStatusEnum.STATUS_0.getValue());
//        storeAfterSales.setSalesStatus(0);
//        storeAfterSales.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
//        storeAfterSales.setIsDel(0);
//        storeAfterSales.setUserId(Long.valueOf(uesrId));
//        storeAfterSales.setOrderStatus(orderStatus);
//        storeAfterSales.setCompanyId(order.getCompanyId());
//        storeAfterSales.setCompanyUserId(order.getCompanyUserId());
//        baseMapper.insertLiveAfterSales(storeAfterSales);
//        //售后商品详情
//        for (LiveAfterSalesProductDTO productParam : param.getProductList()) {
//            LiveOrderItem item = orderItems.stream().filter(p -> p.getProductId().equals(productParam.getProductId())).findFirst().orElse(new LiveOrderItem());
//            LiveAfterSalesItem storeAfterSalesItem = new LiveAfterSalesItem();
//            storeAfterSalesItem.setAfterSalesId(storeAfterSales.getId());
//            storeAfterSalesItem.setProductId(item.getProductId());
//            storeAfterSalesItem.setJsonInfo(item.getJsonInfo());
//            storeAfterSalesItem.setIsDel(0);
//            liveAfterSalesItemMapper.insertLiveAfterSalesItem(storeAfterSalesItem);
//        }
//        //操作记录
//        LiveAfterSalesLogs logs = new LiveAfterSalesLogs();
//        logs.setChangeTime(new DateTime());
//        logs.setChangeType(0);
//        FsUser user = userService.selectFsUserByUserId(Long.valueOf(order.getUserId()));
//        logs.setOperator(user.getNickname());
//        logs.setStoreAfterSalesId(storeAfterSales.getId());
//        logs.setChangeMessage(LiveAfterSalesStatusEnum.STATUS_0.getDesc());
//        liveAfterSalesLogsMapper.insertLiveAfterSalesLogs(logs);
//
//        //更新OMS
//        ErpRefundUpdateRequest request=new ErpRefundUpdateRequest();
//        request.setTid(order.getOrderCode());
//        request.setOid(order.getOrderCode());
//        request.setRefund_state(1);
//        request.setOrderStatus(orderStatus);
//
//
//        // 根据仓库code找erp
//        if(StringUtils.isNotBlank(order.getStoreHouseCode())){
//            String erp = fsWarehousesMapper.selectErpByCode(order.getStoreHouseCode());
//
//            if(StringUtils.equals(erp, ErpTypeConstant.JST_ERP)){
//                FsJstAftersalePush fsJstAftersalePush = new FsJstAftersalePush();
//                fsJstAftersalePush.setOrderId(order.getOrderCode());
//                fsJstAftersalePush.setType(String.valueOf(AfterSalesOrderStatusEnum.WAIT_SELLER_AGREE.getIndex()));
//                fsJstAftersalePush.setTaskStatus(TaskStatusEnum.PENDING.getCode());
//                fsJstAftersalePush.setRetryCount(0);
//                fsJstAftersalePush.setAfterSaleId(String.valueOf(storeAfterSales.getId()));
//                fsJstAftersalePush.setOrderType(1);
//                fsJstAftersalePushMapper.insert(fsJstAftersalePush);
//            }
//            ErpContextHolder.setErpType(erp);
//        }
//
//        BaseResponse response=erpOrderService.refundUpdateLive(request);
//        if(response.getSuccess()){
//            return R.ok();
//        }
//        else{
//            throw new CustomException(response.getErrorDesc());
//        }
        return R.ok();
    }


    @Override
    @Transactional
    public R revoke(String userId, LiveAfterSalesRevokeParam param) throws ParseException {
        LiveAfterSales storeAfterSales = baseMapper.selectLiveAfterSalesById(param.getId());
        if (storeAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if (storeAfterSales.getSalesStatus() != 0) {
            throw new CustomException("非法操作");
        }
        if (storeAfterSales.getStatus().equals(LiveAfterSalesStatusEnum.STATUS_2.getValue()) || storeAfterSales.getStatus().equals(LiveAfterSalesStatusEnum.STATUS_3.getValue()) || storeAfterSales.getStatus().equals(LiveAfterSalesStatusEnum.STATUS_4.getValue())) {
            throw new CustomException("已发货退款单不能撤销");
        }
        //只有未发货的可以撤销，
        if (!storeAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_1.getValue())) {
            throw new CustomException("只有未发货的订单可以撤销售后");
        }
        storeAfterSales.setSalesStatus(1);
        LiveOrder order = liveOrderService.selectLiveOrderByOrderId(String.valueOf(storeAfterSales.getOrderId()));
        order.setStatus(storeAfterSales.getOrderStatus());
        order.setRefundStatus(OrderInfoEnum.REFUND_STATUS_0.getValue().toString());
        liveOrderService.updateLiveOrder(order);
        //操作记录
        LiveAfterSalesLogs logs = new LiveAfterSalesLogs();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(5);
        FsUserScrm user = userService.selectFsUserByUserId(Long.valueOf(order.getUserId()));
        logs.setOperator(user.getNickname());
        logs.setStoreAfterSalesId(storeAfterSales.getId());
        logs.setChangeMessage(OrderInfoEnum.REFUND_STATUS_1.getDesc());
        liveAfterSalesLogsMapper.insertLiveAfterSalesLogs(logs);
        if (storeAfterSales.getOrderStatus().equals(1)) {
            if (StringUtils.isNotEmpty(order.getExtendOrderId())) {
                //更新订单code
                String orderSn = OrderCodeUtils.getOrderSn();
                if (StringUtils.isEmpty(orderSn)) {
                    return R.error("订单生成失败，请重试");
                }
                LiveOrder orderMap = new LiveOrder();
                orderMap.setOrderId(order.getOrderId());
                orderMap.setOrderCode(orderSn);
                orderMap.setStatus(order.getStatus());
                liveOrderService.updateLiveOrder(orderMap);
                liveOrderItemService.updateFsStoreOrderCode(order.getOrderId(), orderSn);
                liveOrderService.createOmsOrder(order.getOrderId());
            }
        }
        baseMapper.updateLiveAfterSales(storeAfterSales);
        return R.ok();

    }


    @Autowired
    private LiveOrderItemMapper liveOrderItemMapper;
    @Autowired
    private LiveUserLotteryRecordMapper liveUserLotteryRecordMapper;
    @Autowired
    private IFsStoreProductScrmService fsStoreProductService;

    @Autowired
    private WxPayService wxPayService;


    @Autowired
    private HuiFuService huiFuService;

    @Autowired
    private ILiveOrderLogsService liveOrderLogsService;
    @Autowired
    private ICompanyService companyService;

    @Autowired
    private LiveAfterSalesMapper liveAfterSalesMapper;

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public R handleImmediatelyRefund(Long orderId) {
        IErpOrderService erpOrderService = getErpService();
        FsErpConfig erpConfig = configUtil.generateStructConfigByKey("his.config", FsErpConfig.class);
        LiveOrder order = liveOrderService.selectLiveOrderByOrderId(String.valueOf(orderId));
        if (order == null) {
            return R.error("订单不存在");
        }
        if (order.getStatus() == -2) {
            return R.error("已退款");
        }
        if (!Integer.valueOf(-1).equals(order.getStatus())) {
            return R.error("非法操作");
        }
        if (erpConfig.getErpOpen() != null
                && erpConfig.getErpOpen() == 1
                && StringUtils.isEmpty(order.getExtendOrderId())
                && !CloudHostUtils.hasCloudHostName("康年堂")) {
            return R.error("暂未推送至erp,请稍后再试！");
        }
//        if (StringUtils.isNotEmpty(order.getExtendOrderId())) {
//            ErpRefundUpdateRequest request = new ErpRefundUpdateRequest();
//            request.setTid(order.getOrderCode());
//            request.setOid(order.getOrderCode());
//            request.setRefund_state(1);
//
//            if (ObjectUtils.equals(order.getStatus(), 2)) {
//                LiveAfterSalesParam param = new LiveAfterSalesParam();
//                param.setOrderCode(order.getOrderCode());
//                param.setRefundAmount(order.getPayMoney());
//                param.setServiceType(1);
//                param.setReasons("后台手动退款流程");
//                param.setExplainImg(null);
//                List<FsStoreAfterSalesProductParam> productParams = new ArrayList<>();
//                List <LiveOrderItem> items = liveOrderItemMapper.selectLiveOrderItemByOrderId(order.getOrderId());
//                for (LiveOrderItem item : items){
//                    FsStoreAfterSalesProductParam param1 = new FsStoreAfterSalesProductParam();
//                    param1.setProductId(item.getProductId());
//                    param1.setNum(Math.toIntExact(item.getNum()));
//                    productParams.add(param1);
//                }
//                return liveAfterSalesService.applyForAfterSales(order.getUserId(), param);
//            } else {
//                jSTOrderService.refundUpdateLive(request);
//            }
//        }
        order.setStatus(OrderInfoEnum.STATUS_NE2.getValue());
        order.setRefundMoney(order.getPayMoney());
        order.setRefundStatus(String.valueOf(OrderInfoEnum.REFUND_STATUS_2.getValue()));
        liveUserLotteryRecordMapper.updateOrderStatusByOrderId(order.getOrderId(), -2);
        liveOrderService.updateLiveOrder(order);

        //退库存
        //获取订单下的商品
        List<LiveOrderItem> orderItemVOS = liveOrderItemMapper.selectLiveOrderItemByOrderId(order.getOrderId());
        for (LiveOrderItem vo : orderItemVOS) {
            if (vo.getIsAfterSales() == 1) {
                fsStoreProductService.incProductStock(vo.getNum(), vo.getProductId(), vo.getProductAttrValueId());
            }
        }
        if ("3".equals(order.getPayType())) {
            //货到付款
        } else {
            //将钱退还给用户
            List<LiveOrderPayment> payments = liveOrderPaymentMapper.selectLiveOrderPaymentByPay(5, order.getOrderId());
            if (payments != null && !payments.isEmpty()) {
//                String json = configService.selectConfigByKey("his.pay");
//                FsPayConfigScrm fsPayConfig = JSON.parseObject(json, FsPayConfigScrm.class);

                for (LiveOrderPayment payment : payments) {
                    FsCoursePlaySourceConfig fsCoursePlaySourceConfig = fsCoursePlaySourceConfigMapper.selectCoursePlaySourceConfigByAppId(payment.getAppId());
                    if (fsCoursePlaySourceConfig == null) {
                        throw new CustomException("未找到appId对应的小程序配置: " + payment.getAppId());
                    }
                    Long merchantConfigId = fsCoursePlaySourceConfig.getMerchantConfigId();
                    if (merchantConfigId == null || merchantConfigId <= 0) {
                        throw new CustomException("小程序没有配置商户信息");
                    }
                    MerchantAppConfig merchantAppConfig = merchantAppConfigMapper.selectMerchantAppConfigById(fsCoursePlaySourceConfig.getMerchantConfigId());
                    FsPayConfig fsPayConfig = JSON.parseObject(merchantAppConfig.getDataJson(), FsPayConfig.class);

                    if (payment.getPayMode() == null || "wx".equals(payment.getPayMode())) {
                        WxPayConfig payConfig = new WxPayConfig();
                        payConfig.setAppId(fsPayConfig.getAppId());
                        payConfig.setMchId(fsPayConfig.getWxMchId());
                        payConfig.setMchKey(fsPayConfig.getWxMchKey());
                        payConfig.setKeyPath(fsPayConfig.getKeyPath());
                        payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                        payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                        wxPayService.setConfig(payConfig);
                        WxPayRefundRequest refundRequest = new WxPayRefundRequest();
                        refundRequest.setOutTradeNo("live-" + payment.getPayCode());
                        refundRequest.setOutRefundNo("live-" + payment.getPayCode());
                        refundRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(payment.getPayMoney().toString()));
                        refundRequest.setRefundFee(WxPayUnifiedOrderRequest.yuanToFen(payment.getPayMoney().toString()));
                        try {
                            WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
                            WxPayRefundQueryResult refundQueryResult = wxPayService.refundQuery("", refundResult.getOutTradeNo(), refundResult.getOutRefundNo(), refundResult.getRefundId());
                            if (refundQueryResult != null && "SUCCESS".equals(refundQueryResult.getResultCode())) {
                                LiveOrderPayment paymentMap = new LiveOrderPayment();
                                paymentMap.setPaymentId(payment.getPaymentId());
                                paymentMap.setStatus(-1);
                                paymentMap.setRefundTime(DateUtils.getNowDate());
                                paymentMap.setRefundMoney(payment.getPayMoney());
                                liveOrderPaymentMapper.updateLiveOrderPayment(paymentMap);
                            } else {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return R.error("退款请求失败" + (refundQueryResult != null ? refundQueryResult.getErrCodeDes() : ""));
                            }
                        } catch (WxPayException e) {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.error("退款请求失败" + e.getErrCodeDes());
                        }
                    } else if (payment.getPayMode() != null && "hf".equals(payment.getPayMode())) {
                        String huifuId = "";
                        FsHfpayConfigMapper fsHfpayConfigMapper = SpringUtils.getBean(FsHfpayConfigMapper.class);
                        if (payment.getAppId() != null) {
                            FsHfpayConfig fsHfpayConfig = fsHfpayConfigMapper.selectByAppId(payment.getAppId());
                            if (fsHfpayConfig != null) {
                                huifuId = fsHfpayConfig.getHuifuId();
                            }
                        } else {
                            CloudHostProper cloudHostProper = SpringUtils.getBean(CloudHostProper.class);
                            if ("益善缘".equals(cloudHostProper.getCompanyName())) {
                                FsHfpayConfig fsPayConfig2 = fsHfpayConfigMapper.selectByAppId("wx0d1a3dd485268521");
                                if (fsPayConfig2 != null) {
                                    huifuId = fsPayConfig2.getHuifuId();
                                }
                            } else {
                                huifuId = fsPayConfig.getHuifuId();
                            }
                        }

                        V2TradePaymentScanpayRefundRequest request = new V2TradePaymentScanpayRefundRequest();
                        request.setOrgHfSeqId(payment.getTradeNo());
                        request.setHuifuId(huifuId);
                        request.setOrdAmt(payment.getPayMoney().toString());
                        request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                        request.setReqSeqId("refund-" + payment.getPayCode());
                        Map<String, Object> extendInfoMap = new HashMap<>();
                        extendInfoMap.put("org_party_order_id", payment.getBankSerialNo());
                        request.setExtendInfo(extendInfoMap);
                        request.setAppId(payment.getAppId());
                        HuiFuRefundResult refund = huiFuService.refund(request);
                        log.info("退款：" + refund);
                        if (refund != null && ("00000000".equals(refund.getResp_code()) || "00000100".equals(refund.getResp_code()))
                                && ("S".equals(refund.getTrans_stat()) || "P".equals(refund.getTrans_stat()))) {
                            payment.setRefundMoney(payment.getPayMoney());
                            payment.setStatus(-1);
                            payment.setRefundTime(new Date());
                            liveOrderPaymentMapper.updateLiveOrderPayment(payment);
                        } else {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.error(refund != null ? refund.getResp_desc() : "退款失败");
                        }
                    } else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error("支付类型异常");
                    }
                }
            }
        }
        liveOrderLogsService.create(order.getOrderId(), OrderLogEnum.REFUND_ORDER_SUCCESS.getValue(),
                OrderLogEnum.REFUND_ORDER_SUCCESS.getDesc());
        //减去公司收入
        if (order.getCompanyId() != null && order.getCompanyId() > 0 && order.getTuiMoneyStatus() != null && order.getTuiMoneyStatus() == 1) {
            companyService.subLiveCompanyMoney(order);
        }
        // 减去用户佣金
        if (order.getTuiUserId() != null && order.getTuiUserId() > 0) {
            IFsUserScrmService userService = SpringUtils.getBean(IFsUserScrmService.class);
            if (userService != null) {
                // 需要将LiveOrder转换为FsStoreOrderScrm用于subTuiMoney方法
                FsStoreOrderScrm storeOrder = new FsStoreOrderScrm();
                storeOrder.setId(order.getOrderId());
                storeOrder.setTuiUserId(order.getTuiUserId());
                userService.subTuiMoney(storeOrder);
            }
        }
        LiveAfterSales liveAfterSales = liveAfterSalesMapper.getLiveAfterSalesByOrderId(orderId);
        LiveAfterSales liveMp = new LiveAfterSales();
        liveMp.setId(liveAfterSales.getId());
        liveMp.setStatus(LiveAfterSalesStatusEnum.STATUS_4.getValue());
        liveMp.setSalesStatus(3);
        liveAfterSalesMapper.updateLiveAfterSales(liveMp);

        return R.ok();
    }

}
