package com.fs.live.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

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.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.erp.constant.AfterSalesOrderStatusEnum;
import com.fs.erp.domain.FsJstAftersalePush;
import com.fs.erp.dto.BaseResponse;
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.FsUser;
import com.fs.his.service.IFsUserService;
import com.fs.his.utils.ConfigUtil;
import com.fs.hisStore.domain.*;
import com.fs.hisStore.dto.StoreOrderProductDTO;
import com.fs.hisStore.enums.AfterSalesStatusEnum;
import com.fs.hisStore.enums.AfterStatusEnum;
import com.fs.hisStore.enums.OrderInfoEnum;
import com.fs.hisStore.enums.SysConfigEnum;
import com.fs.hisStore.param.FsStoreAfterSalesProductParam;
import com.fs.hisStore.service.IFsUserScrmService;
import com.fs.hisStore.vo.FsStoreAfterSalesQueryVO;
import com.fs.hisStore.vo.FsStoreOrderItemVO;
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.ILiveOrderService;
import com.fs.live.vo.LiveAfterSalesListUVO;
import com.fs.live.vo.LiveAfterSalesQueryVO;
import com.fs.live.vo.LiveAfterSalesVo;
import com.fs.live.vo.LiveOrderItemVO1;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
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;

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

    @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;


    /**
     * 查询售后记录
     *
     * @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;
    /**
     * 查询售后记录列表
     *
     * @param liveAfterSales 售后记录
     * @return 售后记录
     */
    @Override
    public List<LiveAfterSalesVo> selectLiveAfterSalesVoList(LiveAfterSalesVo liveAfterSales)
    {
        List<LiveAfterSalesVo> liveAfterSalesVos = baseMapper.selectLiveAfterSalesVoList(liveAfterSales);
        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(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(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public R cancel(LiveAfterSalesCancelParam param) {
//        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);
//
//        // 查询是否已经发货
//        FsStoreDelivers byOrderCode = fsStoreDeliversMapper.findByOrderCode(order.getOrderCode());
//        // 如果已发货走发货售后逻辑，否则直接取消
//        if(byOrderCode!=null){
//            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.setTaskStatus(TaskStatusEnum.PENDING.getCode());
//                    fsJstAftersalePush.setType(String.valueOf(AfterSalesOrderStatusEnum.CLOSED.getIndex()));
//                    fsJstAftersalePush.setRetryCount(0);
//                    fsJstAftersalePush.setAfterSaleId(String.valueOf(storeAfterSales.getId()));
//                    fsJstAftersalePush.setOrderType(1);
//                    fsJstAftersalePushMapper.insert(fsJstAftersalePush);
//                }
//            }
//        }
//        // 如果未发货，重新推送
//        else {
//            //创建新的OMS订单
//            if (storeAfterSales.getOrderStatus().equals(2) ) {
//                if(StringUtils.isNotEmpty(order.getExtendOrderId())){
//                    //更新订单code
//                    String orderSn = SnowflakeUtils.nextId();
//                    LiveOrder orderMap=new LiveOrder();
//                    orderMap.setOrderId(order.getOrderId());
//                    orderMap.setOrderCode(orderSn);
//                    liveOrderService.updateLiveOrder(orderMap);
//                    storeAfterSales.setStoreId(Long.valueOf(orderSn));
//                    liveOrderItemService.updateFsStoreOrderCode(order.getOrderId(),orderSn);
//                    //生成新的订单
//                    try {
//                        liveOrderService.createOmsOrder(order.getOrderId());
//                    } catch (Exception e) {
//                        log.error("创建订单失败！",e);
//                        throw new CustomException("创建订单失败");
//                    }
//                }
//            }
//
//        }
//        baseMapper.updateLiveAfterSales(storeAfterSales);
        return R.ok();
    }

    @Override
    @Transactional
    public R applyForAfterSales(String userId, LiveAfterSalesParam param) {
        log.info("申请退款请求信息:"+JSONUtil.toJsonStr(param));
        LiveOrder order=liveOrderService.selectOrderIdByOrderCode(param.getOrderCode());
        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.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.setUserId(Long.valueOf(userId));
        storeAfterSales.setOrderStatus(orderStatus);
        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());
        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();
    }

    @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("售后单不存在！");
        }
        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)
    {
        if (!"".equals(liveAfterSales.getDeliveryName()) && !"".equals(liveAfterSales.getDeliverySn())){
            liveAfterSales.setStatus(2);
        }

        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(2)){
                //审核通过
                liveAfterSales.setStatus(3);
                baseMapper.updateLiveAfterSales(liveAfterSales);
            }
            //待收货直接退款
            else if(liveAfterSales.getOrderStatus().equals(3)){
                liveAfterSales.setStatus(2);
                baseMapper.updateLiveAfterSales(liveAfterSales);
            //已完成 退货退款
            } else if(liveAfterSales.getOrderStatus().equals(4)) {
                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);
        }
        //退款退货
        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("CQDS001")){
                    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(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public R revoke(String userId, LiveAfterSalesRevokeParam param) {
        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(2)) {
            if (StringUtils.isNotEmpty(order.getExtendOrderId())) {
                //更新订单code
                String orderSn = IdUtil.getSnowflake(0, 0).nextIdStr();
                if (StringUtils.isEmpty(orderSn)) {
                    return R.error("订单生成失败，请重试");
                }
                LiveOrder orderMap = new LiveOrder();
                orderMap.setOrderId(order.getOrderId());
                orderMap.setOrderCode(orderSn);
                liveOrderService.updateLiveOrder(orderMap);
                //生成新的订单
                List<LiveOrderPayment> payments = liveOrderPaymentMapper.selectLiveOrderPaymentByPay(2, order.getOrderId());
                for (LiveOrderPayment payment : payments) {
                    LiveOrderPayment livePayment = new LiveOrderPayment();
                    livePayment.setPaymentId(payment.getPaymentId());
                    livePayment.setBusinessCode(orderSn);
                    liveOrderPaymentMapper.updateLiveOrderPayment(livePayment);
                }

                try {
                    liveOrderService.createOmsOrder(order.getOrderId());
                } catch (Exception e) {
                    log.error("推送ERP订单失败！",e);
                }
            }
        }
        baseMapper.updateLiveAfterSales(storeAfterSales);
        return R.ok();

    }


}
