package com.fs.hisStore.service.impl;

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.JSONObject;
import com.fs.common.annotation.DataScope;
import com.fs.common.annotation.RepeatSubmit;
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.config.WxPayProperties;
import com.fs.core.utils.OrderCodeUtils;
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.mapper.FsJstAftersalePushScrmMapper;
import com.fs.erp.service.IErpOrderService;
import com.fs.his.config.FsSysConfig;
import com.fs.his.domain.*;
import com.fs.his.enums.FsStoreAfterSalesStatusEnum;
import com.fs.his.enums.FsStoreOrderLogEnum;
import com.fs.his.enums.FsStoreOrderStatusEnum;
import com.fs.his.mapper.*;
import com.fs.his.service.IFsStoreOrderLogsService;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.vo.FsStoreAfterSalesExcelVO;
import com.fs.his.vo.FsStoreAfterSalesLogsVO;
import com.fs.hisStore.enums.*;
import com.fs.hisStore.mapper.*;
import com.fs.hisStore.param.*;
import com.fs.huifuPay.domain.HuiFuRefundResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayRefundRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.pay.service.IPayService;
import com.fs.hisStore.config.StoreConfig;
import com.fs.hisStore.domain.*;
import com.fs.hisStore.dto.StoreOrderProductDTO;
import com.fs.hisStore.service.*;
import com.fs.hisStore.vo.FsStoreAfterSalesQueryVO;
import com.fs.hisStore.vo.FsStoreAfterSalesVO;
import com.fs.hisStore.vo.FsStoreOrderItemVO;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.system.service.ISysConfigService;
import com.fs.tzBankPay.TzBankService.TzBankService;
import com.fs.tzBankPay.doman.RefundParam;
import com.fs.tzBankPay.doman.RefundResult;
import com.fs.tzBankPay.doman.TzBankResult;
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 com.google.gson.Gson;
import lombok.Synchronized;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 售后记录Service业务层处理
 *
 * @author fs
 * @date 2022-03-15
 */
@Service
public class FsStoreAfterSalesScrmServiceImpl implements IFsStoreAfterSalesScrmService
{
    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    IFsStorePaymentScrmService paymentService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private FsStoreAfterSalesScrmMapper fsStoreAfterSalesMapper;
    @Autowired
    private IFsStoreAfterSalesItemScrmService afterSalesItemService;
    @Autowired
    private IFsStoreAfterSalesStatusScrmService afterSalesStatusService;
    @Autowired
    private IFsStoreOrderScrmService orderService;
    @Autowired
    private IFsStoreOrderItemScrmService orderItemService;
    @Autowired
    private IPayService payService;
    @Autowired
    private FsStoreOrderItemScrmMapper fsStoreOrderItemMapper;
    @Autowired
    private IFsStoreProductScrmService productService;
    @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 ISysConfigService configService;

    @Autowired
    SysConfigMapper sysConfigMapper;

    @Autowired
    IFsUserScrmService userService;

    @Autowired
    IPayService ybPayService;
    @Autowired
    HuiFuService huiFuService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WxPayProperties wxPayProperties;

    @Autowired
    private ConfigUtil configUtil;

    @Autowired
    private FsStoreAfterSalesLogsScrmMapper fsStoreAfterSalesLogsMapper;

    @Autowired
    private FsStoreScrmMapper fsStoreMapper;

    @Autowired
    private FsStoreOrderScrmMapper fsStoreOrderMapper;
    //fsStoreOrderService
    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderService;
    //fsPackageOrderMapper
    @Autowired
    private FsPackageOrderMapper fsPackageOrderMapper;
    //fsInquiryOrderMapper
    @Autowired
    private FsInquiryOrderMapper fsInquiryOrderMapper;
    @Autowired
    //fsStorePaymentMapper
    private FsStorePaymentScrmMapper fsStorePaymentMapper;
    @Autowired
    //fsStoreOrderLogsMapper
    private FsStoreOrderLogsScrmMapper fsStoreOrderLogsMapper;
    @Autowired
    IFsStoreOrderBillLogScrmService fsStoreOrderBillLogService;

    @Autowired
    FsInquiryOrderMapper inquiryOrderMapper;

    @Autowired
    private TzBankService tzBankService;

    @Autowired
    private IFsStoreOrderLogsService fsStoreOrderLogsService;

    @Autowired
    private CloudHostProper cloudHostProper;

    /**
     * 查询售后记录
     *
     * @param id 售后记录ID
     * @return 售后记录
     */
    @Override
    public FsStoreAfterSalesScrm selectFsStoreAfterSalesById(Long id)
    {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(id);
    }

    /**
     * 查询售后记录列表
     *
     * @param fsStoreAfterSales 售后记录
     * @return 售后记录
     */
    @Override
    public List<FsStoreAfterSalesScrm> selectFsStoreAfterSalesList(FsStoreAfterSalesScrm fsStoreAfterSales)
    {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesList(fsStoreAfterSales);
    }

    /**
     * 新增售后记录
     *
     * @param fsStoreAfterSales 售后记录
     * @return 结果
     */
    @Override
    public int insertFsStoreAfterSales(FsStoreAfterSalesScrm fsStoreAfterSales)
    {
        fsStoreAfterSales.setCreateTime(DateUtils.getNowDate());
        return fsStoreAfterSalesMapper.insertFsStoreAfterSales(fsStoreAfterSales);
    }

    /**
     * 修改售后记录
     *
     * @param fsStoreAfterSales 售后记录
     * @return 结果
     */
    @Override
    public int updateFsStoreAfterSales(FsStoreAfterSalesScrm fsStoreAfterSales)
    {
        return fsStoreAfterSalesMapper.updateFsStoreAfterSales(fsStoreAfterSales);
    }

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

    /**
     * 删除售后记录信息
     *
     * @param id 售后记录ID
     * @return 结果
     */
    @Override
    public int deleteFsStoreAfterSalesById(Long id)
    {
        return fsStoreAfterSalesMapper.deleteFsStoreAfterSalesById(id);
    }

    @Override
    @Transactional
    public R applyForAfterSales(long userId, FsStoreAfterSalesParam storeAfterSalesParam) {
        logger.info("申请退款请求信息:"+JSONUtil.toJsonStr(storeAfterSalesParam));
        FsStoreOrderScrm order=orderService.selectFsStoreOrderByOrderCode(storeAfterSalesParam.getOrderCode());
        Integer orderStatus = order.getStatus();
        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("康年堂")){
            logger.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");
            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("此订单已超过售后时间,不能提交售后");
                    }

                }
            }
        }
        //商品除去优惠后的总价格
        //BigDecimal totalPrice = BigDecimal.ZERO;
        //拿到所有的商品
        List<FsStoreOrderItemVO> orderItems=orderItemService.selectFsStoreOrderItemListByOrderId(order.getId());
        for (FsStoreOrderItemVO item : orderItems) {
            FsStoreAfterSalesProductParam prosuctParam = storeAfterSalesParam.getProductList().stream().filter(p -> p.getProductId().equals(item.getProductId())).findFirst().orElse(new FsStoreAfterSalesProductParam());
            if (prosuctParam.getProductId() != null) {

                item.setIsAfterSales(1);
                FsStoreOrderItemScrm orderItem=new FsStoreOrderItemScrm();
                try {
                    BeanUtils.copyProperties(orderItem,item);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
                orderItemService.updateFsStoreOrderItem(orderItem);

            }
        }
        //更新订单状态
        order.setStatus(OrderInfoEnum.STATUS_NE1.getValue());
        order.setRefundStatus(OrderInfoEnum.REFUND_STATUS_1.getValue());
        order.setRefundReasonWap(storeAfterSalesParam.getReasons());
        order.setRefundReasonWapExplain(storeAfterSalesParam.getExplains());
        order.setRefundReasonTime(new Date());
        orderService.updateFsStoreOrder(order);
        //生成售后订单
        FsStoreAfterSalesScrm storeAfterSales = new FsStoreAfterSalesScrm();
        storeAfterSales.setOrderCode(storeAfterSalesParam.getOrderCode());
        storeAfterSales.setRefundAmount(storeAfterSalesParam.getRefundAmount());
        storeAfterSales.setServiceType(storeAfterSalesParam.getServiceType());
        storeAfterSales.setReasons(storeAfterSalesParam.getReasons());
        storeAfterSales.setExplains(storeAfterSalesParam.getExplains());
        storeAfterSales.setExplainImg(storeAfterSalesParam.getExplainImg());
        storeAfterSales.setStatus(AfterSalesStatusEnum.STATUS_0.getValue());
        storeAfterSales.setSalesStatus(0);
        storeAfterSales.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        storeAfterSales.setIsDel(0);
        storeAfterSales.setUserId(userId);
        storeAfterSales.setOrderStatus(orderStatus);
        storeAfterSales.setCompanyId(order.getCompanyId());
        storeAfterSales.setCompanyUserId(order.getCompanyUserId());
        storeAfterSales.setPackageJson(order.getPackageJson());
        storeAfterSales.setIsPackage(order.getIsPackage());
        fsStoreAfterSalesMapper.insertFsStoreAfterSales(storeAfterSales);
        //售后商品详情
        for (FsStoreAfterSalesProductParam productParam : storeAfterSalesParam.getProductList()) {
            FsStoreOrderItemVO item = orderItems.stream().filter(p -> p.getProductId().equals(productParam.getProductId())).findFirst().orElse(new FsStoreOrderItemVO());
            FsStoreAfterSalesItemScrm storeAfterSalesItem = new FsStoreAfterSalesItemScrm();
            storeAfterSalesItem.setStoreAfterSalesId(storeAfterSales.getId());
            storeAfterSalesItem.setProductId(item.getProductId());
            storeAfterSalesItem.setNum(productParam.getNum());
            storeAfterSalesItem.setJsonInfo(item.getJsonInfo());
            storeAfterSalesItem.setIsDel(0);
            afterSalesItemService.insertFsStoreAfterSalesItem(storeAfterSalesItem);
        }
        //操作记录
        FsStoreAfterSalesStatusScrm storeAfterSalesStatus = new FsStoreAfterSalesStatusScrm();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(0);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_0.getDesc());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        FsUserScrm user=userService.selectFsUserById(userId);
        storeAfterSalesStatus.setOperator(user.getNickname());
        afterSalesStatusService.insertFsStoreAfterSalesStatus(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.refundUpdateScrm(request);
            if(response.getSuccess()){
                return R.ok();
            }
            else{
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error(response.getErrorDesc());
            }
        }
        return R.ok();
    }

    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
    @Transactional
    @Synchronized
    @RepeatSubmit
    public R revoke(long userId, Long id) throws ParseException {
        FsStoreAfterSalesScrm storeAfterSales = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(id);
        if (storeAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if(storeAfterSales.getSalesStatus()!=0){
            throw new CustomException("非法操作");
        }
        if (storeAfterSales.getStatus().equals(AfterSalesStatusEnum.STATUS_2.getValue()) || storeAfterSales.getStatus().equals(AfterSalesStatusEnum.STATUS_3.getValue())|| storeAfterSales.getStatus().equals(AfterSalesStatusEnum.STATUS_4.getValue())) {
            throw new CustomException("已发货退款单不能撤销");
        }
        //只有未发货的可以撤销，
        if (!storeAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_1.getValue()) ) {
            throw new CustomException("只有未发货的订单可以撤销售后");
        }


        storeAfterSales.setSalesStatus(1);
        FsStoreOrderScrm order = orderService.selectFsStoreOrderByOrderCode(storeAfterSales.getOrderCode());
        order.setStatus(storeAfterSales.getOrderStatus());
        order.setRefundStatus(OrderInfoEnum.REFUND_STATUS_0.getValue());
        orderService.updateFsStoreOrder(order);

        //操作记录
        FsStoreAfterSalesStatusScrm storeAfterSalesStatus = new FsStoreAfterSalesStatusScrm();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(5);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_5.getDesc());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        FsUserScrm user=userService.selectFsUserById(userId);
        storeAfterSalesStatus.setOperator(user.getNickname());
        afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);
        if (storeAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_1.getValue()) ) {
            if(StringUtils.isNotEmpty(order.getExtendOrderId())){
                //更新订单code
                String orderSn = IdUtil.getSnowflake(0, 0).nextIdStr();
                FsStoreOrderScrm orderMap=new FsStoreOrderScrm();
                orderMap.setId(order.getId());
                orderMap.setOrderCode(orderSn);
                orderService.updateFsStoreOrder(orderMap);
                storeAfterSales.setOrderCode(orderSn);
                orderItemService.updateFsStoreOrderCode(order.getId(),orderSn);
                //生成新的订单
                orderService.createOmsOrder(order.getId());
            }
        }
        fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);
        return R.ok();
//        //更新OMS
//        ErpRefundUpdateRequest request=new ErpRefundUpdateRequest();
//        request.setTid(order.getOrderCode());
//        request.setOid(order.getOrderCode());
//        request.setRefund_state(0);
//        BaseResponse response= erpOrderService.refundUpdate(request);
//        if(response.getSuccess()){
//            return R.ok();
//        }
//        else{
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return R.error(response.getErrorDesc());
//        }
    }

    @Override
    public List<FsStoreAfterSalesQueryVO> selectFsStoreAfterSalesListQuery(FsStoreAfterSalesQueryParam storeAfterSalesParam) {
        List<FsStoreAfterSalesQueryVO>  list=fsStoreAfterSalesMapper.selectFsStoreAfterSalesListQuery(storeAfterSalesParam);
        for(FsStoreAfterSalesQueryVO vo:list){
            FsStoreAfterSalesItemScrm map=new FsStoreAfterSalesItemScrm();
             map.setStoreAfterSalesId(vo.getId());
            List<FsStoreAfterSalesItemScrm>  items=afterSalesItemService.selectFsStoreAfterSalesItemList(map);
            vo.setItems(items);
        }
        return list;
    }

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

        if("益善缘".equals(cloudHostProper.getCompanyName())){
            FsJstAftersalePush fsJstAftersalePush = new FsJstAftersalePush();
            fsJstAftersalePush.setOrderId(storeAfterSales.getOrderCode());
            fsJstAftersalePush.setTaskStatus(TaskStatusEnum.PENDING.getCode());
            fsJstAftersalePush.setType(String.valueOf(AfterSalesOrderStatusEnum.WAIT_SELLER_CONFIRM_GOODS.getIndex()));
            fsJstAftersalePush.setAfterSaleId(String.valueOf(storeAfterSales.getId()));
            fsJstAftersalePush.setRetryCount(0);
            fsJstAftersalePushMapper.insert(fsJstAftersalePush);
        }
        //操作记录
        FsStoreAfterSalesStatusScrm storeAfterSalesStatus = new FsStoreAfterSalesStatusScrm();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(2);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_2.getDesc());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        FsUserScrm user=userService.selectFsUserById(param.getUserId());
        storeAfterSalesStatus.setOperator(user.getNickname());
        afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);
        fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);
        return R.ok();
    }

    @Override
    @DataScope(deptAlias = "cu",userAlias = "cu")
    public List<FsStoreAfterSalesVO> selectFsStoreAfterSalesListVO(FsStoreAfterSalesScrm fsStoreAfterSales) {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesListVO(fsStoreAfterSales);
    }

//    @Override
//    public R audit(FsStoreAfterSalesAudit1Param param) {
//
//        FsStoreAfterSalesScrm storeAfterSales = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(param.getSalesId());
//        if (storeAfterSales == null) {
//            throw new CustomException("未查询到售后订单信息");
//        }
//        if (!storeAfterSales.getStatus().equals(AfterSalesStatusEnum.STATUS_0.getValue())) {
//            throw new CustomException("非法操作");
//        }
//        FsStoreOrderScrm order=orderService.selectFsStoreOrderByOrderCode(storeAfterSales.getOrderCode());
//        if(param.getRefundAmount().compareTo(order.getPayPrice())==1){
//            return R.error("退款金额不能大于支付金额");
//        }
//        if(storeAfterSales.getServiceType().equals(0)){
//            //退款 1未发货处理 2已发货未签收处理
//            if(storeAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_1.getValue())){
//                //审核通过
//                storeAfterSales.setStatus(3);
//                storeAfterSales.setSalesStatus(3);
//                storeAfterSales.setRefundAmount(param.getRefundAmount());
//                fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);
//                FsStoreAfterSalesStatus storeAfterSalesStatus = new FsStoreAfterSalesStatus();
//                storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
//                storeAfterSalesStatus.setChangeType(3);
//                storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_3.getDesc());
//                storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
//                storeAfterSalesStatus.setOperator(param.getOperator());
//                afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);
//
//                //退款
//                order.setStatus(-2);
//                order.setRefundPrice(storeAfterSales.getRefundAmount());
//                order.setRefundStatus(OrderInfoEnum.REFUND_STATUS_2.getValue());
//                orderService.updateFsStoreOrder(order);
//
//                if(order.getPayType().equals(3)){
//                    //货到付款
//                }
//                else{
//                    //将钱退还给用户
//                    FsStorePaymentScrm payment=paymentService.selectFsStorePaymentByOrderId(order.getId());
//                    if(payment!=null){
//                        RefundDTO refundDTO=new RefundDTO();
//                        refundDTO.setMerchOrderNo(Ids.oid());
//                        refundDTO.setAmount(order.getRefundPrice().toString());
//                        refundDTO.setOrigMerchOrderNo("store-"+payment.getPayCode());
//                        payService.refundOrder(refundDTO);
//                    }
//                    else{
//                        //处理单表退款逻辑
//                        RefundDTO refundDTO=new RefundDTO();
//                        refundDTO.setMerchOrderNo(Ids.oid());
//                        refundDTO.setAmount(order.getRefundPrice().toString());
//                        refundDTO.setOrigMerchOrderNo("store-"+order.getOrderCode());
//                        payService.refundOrder(refundDTO);
//                    }
//                }
//
//                if(order.getTuiUserId()!=null&&order.getTuiUserId()>0){
//                    userService.subTuiMoney(order);
//                }
//            }
//            else if(storeAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_2.getValue())){
//                storeAfterSales.setStatus(2);
//                storeAfterSales.setRefundAmount(param.getRefundAmount());
//                fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);
//
//                FsStoreAfterSalesStatus storeAfterSalesStatus = new FsStoreAfterSalesStatus();
//                storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
//                storeAfterSalesStatus.setChangeType(1);
//                storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_1.getDesc());
//                storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
//                storeAfterSalesStatus.setOperator(param.getOperator());
//                afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);
//                FsStoreAfterSalesStatus storeAfterSalesStatus1 = new FsStoreAfterSalesStatus();
//                storeAfterSalesStatus1.setStoreAfterSalesId(storeAfterSales.getId());
//                storeAfterSalesStatus1.setChangeType(1);
//                storeAfterSalesStatus1.setChangeMessage(AfterSalesStatusEnum.STATUS_2.getDesc());
//                storeAfterSalesStatus1.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
//                storeAfterSalesStatus.setOperator(param.getOperator());
//                afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus1);
//            }
//
//        }
//        else if(storeAfterSales.getServiceType().equals(1)){
//            //退款退货
//            //审核通过
//            storeAfterSales.setStatus(1);
//            storeAfterSales.setRefundAmount(param.getRefundAmount());
//            storeAfterSales.setConsignee(param.getConsignee());
//            storeAfterSales.setPhoneNumber(param.getPhoneNumber());
//            storeAfterSales.setAddress(param.getAddress());
//            fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);
//            FsStoreAfterSalesStatus storeAfterSalesStatus = new FsStoreAfterSalesStatus();
//            storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
//            storeAfterSalesStatus.setChangeType(1);
//            storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_1.getDesc());
//            storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
//            storeAfterSalesStatus.setOperator(param.getOperator());
//
//            afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);
//        }
//
//        return R.ok("操作成功");
//    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public R refundMoney(FsStoreAfterSalesRefundParam param) {
        FsStoreAfterSalesScrm storeAfterSales = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(param.getSalesId());
        if (storeAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if (!storeAfterSales.getStatus().equals(AfterStatusEnum.STATUS_3.getValue())) {
            throw new CustomException("非法操作");
        }



        //审核通过
        storeAfterSales.setRefundAmount(param.getRefundAmount());
        storeAfterSales.setStatus(4);
        storeAfterSales.setSalesStatus(3);
        fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);

        FsStoreOrderScrm order = orderService.selectFsStoreOrderByOrderCode(storeAfterSales.getOrderCode());

        if (("益善缘".equals(cloudHostProper.getCompanyName()))) {
            FsJstAftersalePush fsJstAftersalePush = new FsJstAftersalePush();
            fsJstAftersalePush.setOrderId(order.getOrderCode());
            fsJstAftersalePush.setTaskStatus(TaskStatusEnum.PENDING.getCode());
            fsJstAftersalePush.setType(String.valueOf(AfterSalesOrderStatusEnum.SUCCESS.getIndex()));
            fsJstAftersalePush.setRetryCount(0);
            fsJstAftersalePush.setAfterSaleId(String.valueOf(storeAfterSales.getId()));
            fsJstAftersalePushMapper.insert(fsJstAftersalePush);

            // 售后单改成已确认
            FsJstAftersalePush aftersaleConfirm = new FsJstAftersalePush();
            aftersaleConfirm.setOrderId(order.getOrderCode());
            aftersaleConfirm.setTaskStatus(TaskStatusEnum.PENDING.getCode());
            aftersaleConfirm.setType(String.valueOf(AfterSalesOrderStatusEnum.CONFIRM.getIndex()));
            aftersaleConfirm.setRetryCount(0);
            aftersaleConfirm.setAfterSaleId(String.valueOf(storeAfterSales.getId()));
            fsJstAftersalePushMapper.insert(aftersaleConfirm);
        }

        order.setStatus(-2);
        order.setRefundPrice(storeAfterSales.getRefundAmount());
        order.setRefundStatus(OrderInfoEnum.REFUND_STATUS_2.getValue());
        orderService.updateFsStoreOrder(order);

        BigDecimal refundAmount = param.getRefundAmount();
        if (Objects.isNull(refundAmount)) {
            throw new CustomException("退款金额不能为空");
        }
        if (order.getPayMoney().compareTo(refundAmount) < 0) {
            throw new CustomException("退款金额不能大于支付金额");
        }

        FsStoreAfterSalesStatusScrm storeAfterSalesStatus = new FsStoreAfterSalesStatusScrm();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(4);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_4.getDesc());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        storeAfterSalesStatus.setOperator(param.getOperator());
        afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);
        //退库存
        //获取订单下的商品
        List<FsStoreOrderItemVO> orderItemVOS=fsStoreOrderItemMapper.selectFsStoreOrderItemListByOrderId(order.getId());

        // 获取售后商品
        FsStoreAfterSalesItemScrm params = new FsStoreAfterSalesItemScrm();
        params.setStoreAfterSalesId(storeAfterSales.getId());
        List<FsStoreAfterSalesItemScrm> fsStoreAfterSalesItems = afterSalesItemService.selectFsStoreAfterSalesItemList(params);

        // 退库存
        for (FsStoreAfterSalesItemScrm item : fsStoreAfterSalesItems) {
            FsStoreOrderItemVO itemVO = orderItemVOS.stream().filter(i -> i.getProductId().equals(item.getProductId())).findFirst().orElse(null);
            if(Objects.nonNull(itemVO) && itemVO.getIsAfterSales() == 1 && Objects.nonNull(item.getNum())){
                productService.incProductStock(item.getNum().longValue(), item.getProductId(), null);
            }
        }

        //将钱退还给用户
        if(order.getPayMoney().compareTo(BigDecimal.ZERO)==1){
            List<FsStorePaymentScrm> payments=paymentService.selectFsStorePaymentByOrderId(order.getId());
            if(payments!=null){
                String json = configService.selectConfigByKey("his.pay");
                FsPayConfigScrm fsPayConfig = JSON.parseObject(json, FsPayConfigScrm.class);
                for(FsStorePaymentScrm payment:payments){
                    if (payment.getPayMode()==null||payment.getPayMode().equals("wx")){
                        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("store-"+payment.getPayCode());
                        refundRequest.setOutRefundNo("store-"+payment.getPayCode());
                        refundRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(payment.getPayMoney().toString()));
                        refundRequest.setRefundFee(WxPayUnifiedOrderRequest.yuanToFen(refundAmount.toString()));
                        try {
                            WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
                            WxPayRefundQueryResult refundQueryResult = wxPayService.refundQuery("", refundResult.getOutTradeNo(), refundResult.getOutRefundNo(), refundResult.getRefundId());
                            if(refundQueryResult!=null&&refundQueryResult.getResultCode().equals("SUCCESS")){
                                FsStorePaymentScrm paymentMap=new FsStorePaymentScrm();
                                paymentMap.setPaymentId(payment.getPaymentId());
                                paymentMap.setStatus(-1);
                                paymentMap.setRefundTime(DateUtils.getNowDate());
                                paymentMap.setRefundMoney(refundAmount);
                                paymentService.updateFsStorePayment(paymentMap);
                            }
                            else {
                                return R.error("退款请求失败"+refundQueryResult.getErrCodeDes());
                            }
                        } catch (WxPayException e) {
                            return R.error("退款请求失败"+e.getErrCodeDes());
                        }
                    }else if (payment.getPayMode()!=null&&payment.getPayMode().equals("hf")){
                        String huifuId="";
                        FsHfpayConfigMapper fsHfpayConfigMapper = SpringUtils.getBean(FsHfpayConfigMapper.class);
                        if (payment.getAppId() != null) {
                            FsHfpayConfig fsHfpayConfig = fsHfpayConfigMapper.selectByAppId(payment.getAppId());
                            huifuId = fsHfpayConfig.getHuifuId();
                        } else {
                            if (("益善缘".equals(cloudHostProper.getCompanyName()))) {

                                FsHfpayConfig fsPayConfig2 = fsHfpayConfigMapper.selectByAppId("wx0d1a3dd485268521");
                                huifuId = fsPayConfig2.getHuifuId();
                            }else {
                                huifuId=fsPayConfig.getHuifuId();
                            }
                        }
                        V2TradePaymentScanpayRefundRequest request = new V2TradePaymentScanpayRefundRequest();
                        DecimalFormat df = new DecimalFormat("0.00");
                        request.setOrgHfSeqId(payment.getTradeNo());
                        request.setHuifuId(huifuId);
                        request.setOrdAmt(df.format(refundAmount));
                        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);
                        HuiFuRefundResult refund = huiFuService.refund(request);
                        logger.info("退款："+refund);
                        if((refund.getResp_code().equals("00000000")||refund.getResp_code().equals("00000100"))&&(refund.getTrans_stat().equals("S")||refund.getTrans_stat().equals("P"))){
                            payment.setRefundMoney(refundAmount);
                            payment.setStatus(-1);
                            payment.setRefundTime(new Date());
                            paymentService.updateFsStorePayment(payment);
                        }else {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.error(refund.getResp_desc());
                        }

                    }else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error("支付类型异常");
                    }


                }
            }
        }
        //减去公司收入
        if(order.getCompanyId()!=null&&order.getCompanyId()>0&&order.getTuiMoneyStatus()!=null&&order.getTuiMoneyStatus()==1){
            companyService.subCompanyMoney(order);
        }
        //退佣金
        if(order.getTuiUserId()!=null&&order.getTuiUserId()>0){
            userService.subTuiMoney(order);
        }
        return R.ok();
    }


    @Autowired
    private FsJstAftersalePushScrmMapper fsJstAftersalePushMapper;

    //平台撤销
    @Override
    @Transactional
    public R cancel(FsStoreAfterSalesCancelParam param) throws ParseException{
        FsStoreAfterSalesScrm storeAfterSales = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(param.getSalesId());
        if (storeAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if (storeAfterSales.getSalesStatus()!=0) {
            throw new CustomException("非法操作");
        }

        FsStoreOrderScrm order = orderService.selectFsStoreOrderByOrderCode(storeAfterSales.getOrderCode());
        order.setStatus(storeAfterSales.getOrderStatus());
        order.setRefundStatus(OrderInfoEnum.REFUND_STATUS_0.getValue());
        orderService.updateFsStoreOrder(order);
        storeAfterSales.setSalesStatus(2);
        FsStoreAfterSalesStatusScrm storeAfterSalesStatus = new FsStoreAfterSalesStatusScrm();
        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());
        afterSalesStatusService.insertFsStoreAfterSalesStatus(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 = IdUtil.getSnowflake(0, 0).nextIdStr();
                    FsStoreOrderScrm orderMap=new FsStoreOrderScrm();
                    orderMap.setId(order.getId());
                    orderMap.setOrderCode(orderSn);
                    orderService.updateFsStoreOrder(orderMap);
                    storeAfterSales.setOrderCode(orderSn);
                    orderItemService.updateFsStoreOrderCode(order.getId(),orderSn);
                    //生成新的订单
                    orderService.createOmsOrder(order.getId());
                }
            }
        }


        fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);
        return R.ok();

//        ErpRefundUpdateRequest request=new ErpRefundUpdateRequest();
//        request.setTid(order.getOrderCode());
//        request.setOid(order.getOrderCode());
//        request.setRefund_state(0);
//        erpOrderService.refundUpdate(request);
    }

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


    @Override
    public List<FsStoreAfterSalesVO> selectFsStoreAfterSalesVOByOrderCode(String orderCode) {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesVOByOrderCode(orderCode);
    }

    @Override
    public R audit1(FsStoreAfterSalesAudit1Param param) {
        FsStoreAfterSalesScrm storeAfterSales = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(param.getSalesId());
        if (storeAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if (!storeAfterSales.getStatus().equals(AfterStatusEnum.STATUS_0.getValue())) {
            throw new CustomException("非法操作");
        }
        //仅退款
        if(storeAfterSales.getServiceType().equals(0)){
            //仅退款未发货处理
            if(storeAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_1.getValue())){
                //审核通过
                storeAfterSales.setStatus(3);
                fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);

            }
            //仅退款待收货处理
            else if(storeAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_2.getValue())){
                storeAfterSales.setStatus(2);
                fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);
            }
            FsStoreAfterSalesStatusScrm storeAfterSalesStatus = new FsStoreAfterSalesStatusScrm();
            storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
            storeAfterSalesStatus.setChangeType(1);
            storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_1.getDesc());
            storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
            storeAfterSalesStatus.setOperator(param.getOperator());
            afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);
        }
        //退款退货
        else if(storeAfterSales.getServiceType().equals(1)){
            String json=configService.selectConfigByKey("store.config");
            StoreConfig config=JSONUtil.toBean(json,StoreConfig.class);
            FsStoreOrderScrm order=orderService.selectFsStoreOrderByOrderCode(storeAfterSales.getOrderCode());
            if(order.getStoreHouseCode()!=null){
                if(order.getStoreHouseCode().equals("CK01")){
                    storeAfterSales.setConsignee(config.getRefundConsignee());
                    storeAfterSales.setPhoneNumber(config.getRefundPhoneNumber());
                    storeAfterSales.setAddress(config.getRefundAddress());
                }
                else  if(order.getStoreHouseCode().equals("WHSP001")){
                    //todo
                    storeAfterSales.setConsignee("田伟");
                    storeAfterSales.setPhoneNumber("19318102192");
                    storeAfterSales.setAddress("湖北省武汉市东西湖区国东一路5号2栋");
                }
            }
            else{
                storeAfterSales.setConsignee(config.getRefundConsignee());
                storeAfterSales.setPhoneNumber(config.getRefundPhoneNumber());
                storeAfterSales.setAddress(config.getRefundAddress());
            }
            //退款退货
            storeAfterSales.setStatus(1);
            fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);
            FsStoreAfterSalesStatusScrm storeAfterSalesStatus = new FsStoreAfterSalesStatusScrm();
            storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
            storeAfterSalesStatus.setChangeType(1);
            storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_1.getDesc());
            storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
            storeAfterSalesStatus.setOperator(param.getOperator());
            afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);
        }

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

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

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

    @Override
    public List<FsStoreAfterSalesScrm> selectFsStoreAfterSalesByDoAudit() {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesByDoAudit();
    }

    @Override
    public Boolean isEntityNull(FsStoreAfterSalesScrm fsStoreAfterSales) {
        Class<?> entityClass = fsStoreAfterSales.getClass();
        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = field.getName();
            if (!fieldName.equals("serialVersionUID")) {
                try {
                    Object fieldValue = field.get(fsStoreAfterSales);
                    if (fieldValue != null) {
                        return false;  // 除了 serialVersionUID 字段之外的字段值不为 null
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();  // 处理反射异常
                    return false;
                }
            }
        }
        return true;  // 所有字段值为 null，除了 serialVersionUID 字段
    }

    @Override
    public int updateDelivery(FsStoreAfterSalesScrm fsStoreAfterSales) {
        return fsStoreAfterSalesMapper.updateDeliveryById(fsStoreAfterSales);
    }

    @Override
    @Transactional
    public R autoApplyForAfterSales(long userId, FsStoreAfterSalesParam storeAfterSalesParam) {
        logger.info("申请退款请求信息:"+JSONUtil.toJsonStr(storeAfterSalesParam));
        FsStoreOrderScrm order=orderService.selectFsStoreOrderByOrderCode(storeAfterSalesParam.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())){
            logger.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");
            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("此订单已超过售后时间,不能提交售后");
                    }

                }
            }
        }
        //商品除去优惠后的总价格
        //BigDecimal totalPrice = BigDecimal.ZERO;
        //拿到所有的商品
        List<FsStoreOrderItemVO> orderItems=orderItemService.selectFsStoreOrderItemListByOrderId(order.getId());
        for (FsStoreOrderItemVO item : orderItems) {
            StoreOrderProductDTO cartInfo = JSONObject.parseObject(item.getJsonInfo(), StoreOrderProductDTO.class);
            FsStoreAfterSalesProductParam prosuctParam = storeAfterSalesParam.getProductList().stream().filter(p -> p.getProductId().equals(item.getProductId())).findFirst().orElse(new FsStoreAfterSalesProductParam());
            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);
                FsStoreOrderItemScrm orderItem=new FsStoreOrderItemScrm();
                BeanUtil.copyProperties(item, orderItem);
                orderItemService.updateFsStoreOrderItem(orderItem);

            }
        }
        //更新订单状态
        Integer orderStatus=order.getStatus();
        order.setStatus(OrderInfoEnum.STATUS_NE1.getValue());
        order.setRefundStatus(OrderInfoEnum.REFUND_STATUS_1.getValue());
        order.setRefundReasonWap(storeAfterSalesParam.getReasons());
        order.setRefundReasonWapExplain(storeAfterSalesParam.getExplains());
        order.setRefundReasonTime(new Date());
        orderService.updateFsStoreOrder(order);
        //生成售后订单
        FsStoreAfterSalesScrm storeAfterSales = new FsStoreAfterSalesScrm();
        storeAfterSales.setOrderCode(storeAfterSalesParam.getOrderCode());
        storeAfterSales.setRefundAmount(storeAfterSalesParam.getRefundAmount());
        storeAfterSales.setServiceType(storeAfterSalesParam.getServiceType());
        storeAfterSales.setReasons(storeAfterSalesParam.getReasons());
        storeAfterSales.setExplains(storeAfterSalesParam.getExplains());
        storeAfterSales.setExplainImg(storeAfterSalesParam.getExplainImg());
        storeAfterSales.setStatus(AfterSalesStatusEnum.STATUS_3.getValue());
        storeAfterSales.setSalesStatus(0);
        storeAfterSales.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        storeAfterSales.setIsDel(0);
        storeAfterSales.setUserId(userId);
        storeAfterSales.setOrderStatus(orderStatus);
        storeAfterSales.setCompanyId(order.getCompanyId());
        storeAfterSales.setCompanyUserId(order.getCompanyUserId());
        storeAfterSales.setPackageJson(order.getPackageJson());
        storeAfterSales.setIsPackage(order.getIsPackage());
        fsStoreAfterSalesMapper.insertFsStoreAfterSales(storeAfterSales);
        //售后商品详情
        for (FsStoreAfterSalesProductParam productParam : storeAfterSalesParam.getProductList()) {
            FsStoreOrderItemVO item = orderItems.stream().filter(p -> p.getProductId().equals(productParam.getProductId())).findFirst().orElse(new FsStoreOrderItemVO());
            FsStoreAfterSalesItemScrm storeAfterSalesItem = new FsStoreAfterSalesItemScrm();
            storeAfterSalesItem.setStoreAfterSalesId(storeAfterSales.getId());
            storeAfterSalesItem.setProductId(item.getProductId());
            storeAfterSalesItem.setJsonInfo(item.getJsonInfo());
            storeAfterSalesItem.setIsDel(0);
            afterSalesItemService.insertFsStoreAfterSalesItem(storeAfterSalesItem);
        }
        //操作记录
        FsStoreAfterSalesStatusScrm storeAfterSalesStatus = new FsStoreAfterSalesStatusScrm();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(0);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_0.getDesc());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        storeAfterSalesStatus.setOperator("管理员");
        afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);

        //更新OMS
        ErpRefundUpdateRequest request=new ErpRefundUpdateRequest();
        request.setTid(order.getOrderCode());
        request.setOid(order.getOrderCode());
        request.setRefund_state(1);
        IErpOrderService erpOrderService = getErpService();
        BaseResponse response=erpOrderService.refundUpdate(request);
        if(response.getSuccess()){
            return R.ok();
        }
        else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(response.getErrorDesc());
        }
    }

    @Override
    public List<FsStoreAfterSalesExcelVO> selectFsStoreAfterSalesExcelListVO(com.fs.his.param.FsStoreAfterSalesParam fsStoreAfterSales) {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesExcelListVO(fsStoreAfterSales);
    }

    @Override
    public FsStoreAfterSalesVO selectFsStoreAfterSalesVOById(Long id) {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesVOById(id);
    }

    @Override
    public List<FsStoreAfterSalesItemScrm> selectFsStoreAfterSalesItemById(Long id) {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesItemById(id);
    }

    @Override
    public List<FsStoreAfterSalesLogsVO> selectFsStoreAfterSalesLogById(Long id) {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesLogById(id);
    }

    @Override
    public Long selectFsOrderIdByCode(Long id) {
        return fsStoreAfterSalesMapper.selectFsOrderIdByCode(id);
    }

    @Override
    public int auditing(FsStoreAfterSalesScrm fsStoreAfterSales) {
        FsStoreAfterSalesScrm order = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(fsStoreAfterSales.getId());
        if (order == null) {

            throw new CustomException("订单不存在");
        }
        if (order.getSalesStatus() != 0) {
            throw new CustomException("非法更改");
        }
        Integer status = null;
        FsStoreAfterSalesScrm fs = new FsStoreAfterSalesScrm();
        if (order.getOrderStatus() == 2) {
            status = 3;
        } else if (order.getOrderStatus() == 3) {
            FsStoreScrm fsStore = fsStoreMapper.selectFsStoreByStoreId(order.getStoreId());
            fs.setPhoneNumber(fsStore.getRefundPhone());
            fs.setAddress(fsStore.getRefundAddress());
            fs.setConsignee(fsStore.getRefundConsignee());
            status = 2;
        } else if (order.getOrderStatus() == 4) {
            FsStoreScrm fsStore = fsStoreMapper.selectFsStoreByStoreId(order.getStoreId());
            fs.setPhoneNumber(fsStore.getRefundPhone());
            fs.setAddress(fsStore.getRefundAddress());
            fs.setConsignee(fsStore.getRefundConsignee());
            status = 1;
        }

        fs.setId(fsStoreAfterSales.getId());
        fs.setStatus(status);
        int i = fsStoreAfterSalesMapper.updateFsStoreAfterSales(fs);
        FsStoreAfterSalesLogsScrm logs = new FsStoreAfterSalesLogsScrm();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(FsStoreAfterSalesStatusEnum.STATUS_1.getValue());
        logs.setStoreAfterSalesId(fsStoreAfterSales.getId());
        logs.setChangeMessage(FsStoreAfterSalesStatusEnum.STATUS_1.getDesc());
        logs.setOperator(fsStoreAfterSales.getOperator());
        fsStoreAfterSalesLogsMapper.insertFsStoreAfterSalesLogs(logs);
        //添加订单日志
        fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.PLATFORM_REVIEW_SALES.getValue(),
                logs.getOperator()+" "+FsStoreOrderLogEnum.PLATFORM_REVIEW_SALES.getDesc());
        return 1;
    }

    @Override
    public int depotAuditing(FsStoreAfterSalesScrm fsStoreAfterSales) {
        FsStoreAfterSalesScrm order = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(fsStoreAfterSales.getId());
        if (order == null) throw new CustomException("订单不存在");
        if (order.getSalesStatus() != 0) throw new CustomException("非法更改");
        if (order.getStatus() != 2) {
            throw new CustomException("非法更改");
        }
        FsStoreAfterSalesScrm fs = new FsStoreAfterSalesScrm();
        fs.setId(fsStoreAfterSales.getId());
        fs.setStatus(3);
        int i = fsStoreAfterSalesMapper.updateFsStoreAfterSales(fs);
        FsStoreAfterSalesLogsScrm logs = new FsStoreAfterSalesLogsScrm();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(FsStoreAfterSalesStatusEnum.STATUS_3.getValue());
        logs.setStoreAfterSalesId(fsStoreAfterSales.getId());
        logs.setChangeMessage(FsStoreAfterSalesStatusEnum.STATUS_3.getDesc());
        logs.setOperator(fsStoreAfterSales.getOperator());
        fsStoreAfterSalesLogsMapper.insertFsStoreAfterSalesLogs(logs);
        //添加订单日志
        fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.WAREHOUSE_REVIEW_SALES.getValue(),
                logs.getOperator() + " " +FsStoreOrderLogEnum.WAREHOUSE_REVIEW_SALES.getDesc());
        return 1;
    }

    @Override
    public int noAuditing(FsStoreAfterSalesScrm fsStoreAfterSales) {
        FsStoreAfterSalesScrm order = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(fsStoreAfterSales.getId());
        if (order == null) throw new CustomException("订单不存在");
        if (order.getSalesStatus() != 0) {
            throw new CustomException("非法更改");
        }
        if (order.getStatus() == 5) {
            throw new CustomException("非法更改");
        }
        FsStoreAfterSalesScrm fs = new FsStoreAfterSalesScrm();
        fs.setId(fsStoreAfterSales.getId());
        fs.setSalesStatus(2);
        fs.setStatus(5);
        int i = fsStoreAfterSalesMapper.updateFsStoreAfterSales(fs);
        FsStoreAfterSalesLogsScrm logs = new FsStoreAfterSalesLogsScrm();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(FsStoreAfterSalesStatusEnum.STATUS_6.getValue());
        logs.setStoreAfterSalesId(fsStoreAfterSales.getId());
        logs.setChangeMessage(FsStoreAfterSalesStatusEnum.STATUS_6.getDesc() + " " + fsStoreAfterSales.getRemark());
        logs.setOperator(fsStoreAfterSales.getOperator());
        fsStoreAfterSalesLogsMapper.insertFsStoreAfterSalesLogs(logs);
        //添加订单日志
        fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.PLATFORM_REVIEW_CANCEL.getValue(),
                logs.getOperator() + " " +FsStoreOrderLogEnum.PLATFORM_REVIEW_CANCEL.getDesc());
//        FsStoreOrderLogsScrm Logs = new FsStoreOrderLogsScrm();
//        Logs.setChangeMessage("已取消退款");
//        Logs.setOrderId(order.getOrderId());
//        Logs.setChangeTime(new DateTime());
//        Logs.setChangeType(order.getOrderStatus().toString());
//        fsStoreOrderLogsMapper.insertFsStoreOrderLogs(Logs);
        FsStoreOrderScrm or = new FsStoreOrderScrm();
        or.setId(order.getOrderId());
        or.setStatus(order.getOrderStatus());
        fsStoreOrderMapper.updateFsStoreOrder(or);
        if (order.getOrderStatus() == 2) {
            FsStoreOrderScrm fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderById(order.getOrderId());
            String newOrderSn = OrderCodeUtils.getOrderSn();
            if (StringUtils.isEmpty(newOrderSn)) {
                newOrderSn = OrderCodeUtils.getOrderSn();
            }
            FsStoreOrderScrm newOrder = new FsStoreOrderScrm();
            newOrder.setId(order.getOrderId());
            newOrder.setOrderCode(newOrderSn);
            fsStoreOrderMapper.updateFsStoreOrder(newOrder);
            or.setOrderCode(newOrderSn);
            if (fsStoreOrder.getPackageOrderId() != null) {
                FsPackageOrder fsPackageOrder = new FsPackageOrder();
                fsPackageOrder.setOrderId(fsStoreOrder.getPackageOrderId());
                fsPackageOrder.setOrderSn(newOrderSn);
                fsPackageOrderMapper.updateFsPackageOrder(fsPackageOrder);
            }
            if (fsStoreOrder.getInquiryOrderId() != null) {
                FsInquiryOrder fsInquiryOrder = new FsInquiryOrder();
                fsInquiryOrder.setOrderSn(newOrderSn);
                fsInquiryOrder.setOrderId(fsStoreOrder.getInquiryOrderId());
                fsInquiryOrderMapper.updateFsInquiryOrder(fsInquiryOrder);
            }

            List<FsStorePaymentScrm> payments = fsStorePaymentMapper.selectFsStorePaymentByPay(2, fsStoreOrder.getId());
            if (fsStoreOrder.getPackageOrderId() != null) {
                payments = fsStorePaymentMapper.selectFsStorePaymentByPay(3, fsStoreOrder.getPackageOrderId());
            }
            for (FsStorePaymentScrm payment : payments) {
                FsStorePaymentScrm fsStorePayment = new FsStorePaymentScrm();
                fsStorePayment.setPaymentId(payment.getPaymentId());
                fsStorePayment.setBusinessCode(newOrderSn);
                fsStorePaymentMapper.updateFsStorePayment(fsStorePayment);
            }

            try {
                fsStoreOrderService.createOmsOrder(order.getOrderId());
            } catch (ParseException e) {
                logger.error(e.getMessage());
            }

        }


        return 1;
    }

    @Override
    public int storeRefundMoney(FsStoreAfterSalesScrm fsStoreAfterSales) {
        FsStoreAfterSalesScrm order = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(fsStoreAfterSales.getId());
        FsStoreOrderScrm fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderById(order.getOrderId());
        if (order == null) throw new CustomException("订单不存在");
        if (order.getStatus() != 3) throw new CustomException("非法更改");
        //更改售后订单状态
        FsStoreAfterSalesScrm fs = new FsStoreAfterSalesScrm();
        fs.setId(fsStoreAfterSales.getId());
        fs.setStatus(4);
        fs.setSalesStatus(3);
        int i = fsStoreAfterSalesMapper.updateFsStoreAfterSales(fs);
        FsStoreAfterSalesLogsScrm logs = new FsStoreAfterSalesLogsScrm();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(FsStoreAfterSalesStatusEnum.STATUS_4.getValue());
        logs.setStoreAfterSalesId(fsStoreAfterSales.getId());
        logs.setChangeMessage(FsStoreAfterSalesStatusEnum.STATUS_4.getDesc());
        logs.setOperator(fsStoreAfterSales.getOperator());
        fsStoreAfterSalesLogsMapper.insertFsStoreAfterSalesLogs(logs);
        //添加订单日志
        fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.FINANCE_REVIEW_SALES.getValue(),
                logs.getOperator() + " " +FsStoreOrderLogEnum.FINANCE_REVIEW_SALES.getDesc());
        //更改订单状态
        FsStoreOrderScrm or = new FsStoreOrderScrm();
        or.setId(order.getOrderId());
        or.setStatus(-2);
        or.setRefundTime(DateUtils.getNowDate());
        fsStoreOrderMapper.updateFsStoreOrder(or);
        FsStoreOrderLogsScrm Logs = new FsStoreOrderLogsScrm();
        Logs.setChangeMessage(FsStoreOrderStatusEnum.REFUND_STATUS_2.getDesc());
        Logs.setOrderId(order.getOrderId());
        Logs.setChangeTime(new DateTime());
        Logs.setChangeType(FsStoreOrderStatusEnum.REFUND_STATUS_2.getValue().toString());
        fsStoreOrderLogsMapper.insertFsStoreOrderLogs(Logs);
        BigDecimal reMoney = order.getRefundAmount();
        String orderType = "store";
        // 开票冲红
        fsStoreOrderBillLogService.billBackByOrderId(fsStoreOrder.getId());


        if (fsStoreOrder.getPackageOrderId() != null) {
            orderType = "package";
            FsPackageOrder fsPackageOrder = fsPackageOrderMapper.selectFsPackageOrderByOrderId(fsStoreOrder.getPackageOrderId());
            if (fsPackageOrder != null) {
                fsPackageOrder.setStatus(-2);
                fsPackageOrder.setRefundStatus(2);
                fsPackageOrderMapper.updateFsPackageOrder(fsPackageOrder);
            }
            if (fsPackageOrder.getInquiryOrderId() != null) {
                FsInquiryOrder fsInquiryOrder = new FsInquiryOrder();
                fsInquiryOrder.setOrderId(fsPackageOrder.getInquiryOrderId());
                fsInquiryOrder.setStatus(-2);
                inquiryOrderMapper.updateFsInquiryOrder(fsInquiryOrder);
            }

        }
        //商品增加库存
        //退库存
        //获取订单下的商品
//        List<FsStoreOrderItem> orderItem=fsStoreOrderItemMapper.selectFsStoreOrderItemListByOrderId(order.getOrderId());
//        for(FsStoreOrderItem vo:orderItem){
//            if(vo.getIsAfterSales()==1){
//                logger.info("退库存"+vo.getNum()+":"+vo.getProductId());
//                productService.incProductStock(vo.getNum(), vo.getProductId(), vo.getProductAttrValueId());
//            }
//        }
        if (order.getCompanyId() != null) {
            companyService.refundCompanyMoneyScrm(fsStoreOrder);
        }

//        if (fsStoreOrder.getPackageOrderId()!=null){
//            fsUserService.subUserIntegral(fsStoreOrder.getUserId(),fsStoreOrder.getPackageOrderId(),3);
//        }else {
//            fsUserService.subUserIntegral(fsStoreOrder.getUserId(),fsStoreOrder.getOrderId(),2);
//        }

        List<FsStorePaymentScrm> payments = fsStorePaymentMapper.selectFsStorePaymentByPay(2, fsStoreOrder.getId());
        if (fsStoreOrder.getPackageOrderId() != null) {

            payments = fsStorePaymentMapper.selectFsStorePaymentByPay(3, fsStoreOrder.getPackageOrderId());
        }
        if (payments != null && payments.size() > 0) {
            FsStorePaymentScrm payment = payments.get(0);
            String json = configService.selectConfigByKey("store.pay");
            FsPayConfigScrm fsPayConfig = JSON.parseObject(json, FsPayConfigScrm.class);
            if (payment.getPayMode().equals("wx")) {
                WxPayConfig payConfig = new WxPayConfig();
                //SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.pay");
                //FsPayConfig fsPayConfig = new Gson().fromJson(sysConfig.getConfigValue(), FsPayConfig.class);
                payConfig.setAppId(fsPayConfig.getAppId());
                payConfig.setMchId(fsPayConfig.getWxMchId());
                payConfig.setMchKey(fsPayConfig.getWxMchKey());
                payConfig.setKeyPath(wxPayProperties.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(orderType + "-" + payment.getPayCode());
                refundRequest.setOutRefundNo(orderType + "-" + 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 && refundQueryResult.getResultCode().equals("SUCCESS")) {
                        FsStorePaymentScrm paymentMap = new FsStorePaymentScrm();
                        paymentMap.setPaymentId(payment.getPaymentId());
                        paymentMap.setStatus(-1);
                        paymentMap.setRefundTime(DateUtils.getNowDate());
                        paymentMap.setRefundMoney(payment.getPayMoney());
                        fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                    } else {
                        throw new CustomException("退款请求失败" + refundQueryResult.getReturnMsg());
                    }
                } catch (WxPayException e) {
                    throw new CustomException("退款请求失败" + e.getReturnMsg());
                }
            } else if (payment.getPayMode().equals("yb")) {
                //易宝
                com.fs.pay.pay.dto.RefundDTO refundDTO = new com.fs.pay.pay.dto.RefundDTO();
                refundDTO.setRefundMoney(payment.getPayMoney().toString());
                refundDTO.setLowRefundNo(orderType + "-" + payment.getPayCode());
                refundDTO.setUpOrderId(payment.getTradeNo());
                com.fs.ybPay.domain.RefundResult result = payService.refund(refundDTO);
                logger.info("订单退款返回结果:退款订单id:" + order.getOrderId() + result);
                if (result.getState().equals("5")) {
                    FsStorePaymentScrm paymentMap = new FsStorePaymentScrm();
                    paymentMap.setPaymentId(payment.getPaymentId());
                    paymentMap.setStatus(-1);
                    paymentMap.setRefundTime(DateUtils.getNowDate());
                    paymentMap.setRefundMoney(payment.getPayMoney());
                    fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                } else {
                    throw new CustomException("退款请求失败" + result.getMessage());
                }
            } else if (payment.getPayMode().equals("tz")) {
                RefundParam tzBankResult = new RefundParam();
                // 使用set方法为对象的字段赋值
                //商户原支付订单号
                tzBankResult.setOldPayOutOrderNo(orderType + payment.getPayCode());
                // 商户退款订单号 对接平台系统里自己生成的退款订单号
                tzBankResult.setRefundOrderNo(orderType + payment.getPayCode());
                // 交易发送时间 yyyyMMddHHmmss
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                tzBankResult.setTrxSendTime(sdf.format(new Date()));
                // 退款金额
                tzBankResult.setRefundOrdTransAmt(payment.getPayMoney().doubleValue());
                TzBankResult<RefundResult> result = tzBankService.refund(tzBankResult);
                logger.info("订单退款返回结果:退款订单id:" + order.getOrderId() + result);
                if (result.getBody().getRefundOrdStatus().equals("90") || result.getBody().getRefundOrdStatus().equals("60")) {
                    FsStorePaymentScrm paymentMap = new FsStorePaymentScrm();
                    paymentMap.setPaymentId(payment.getPaymentId());
                    paymentMap.setStatus(-1);
                    paymentMap.setRefundTime(DateUtils.getNowDate());
                    paymentMap.setRefundMoney(payment.getPayMoney());
                    fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                } else {
                    throw new CustomException("退款请求失败" + result.getRetMsg());
                }
            } else if (payment.getPayMode().equals("hf")) {
                String huifuId="";
                FsHfpayConfigMapper fsHfpayConfigMapper = SpringUtils.getBean(FsHfpayConfigMapper.class);
                if (payment.getAppId() != null) {
                    FsHfpayConfig fsHfpayConfig = fsHfpayConfigMapper.selectByAppId(payment.getAppId());
                    huifuId = fsHfpayConfig.getHuifuId();
                } else {
                    if (("益善缘".equals(cloudHostProper.getCompanyName()))) {

                        FsHfpayConfig fsPayConfig2 = fsHfpayConfigMapper.selectByAppId("wx0d1a3dd485268521");
                        huifuId = fsPayConfig2.getHuifuId();
                    }else {
                        huifuId=fsPayConfig.getHuifuId();
                    }
                }
                V2TradePaymentScanpayRefundRequest request = new V2TradePaymentScanpayRefundRequest();
                request.setOrdAmt(payment.getPayMoney().toString());
                request.setHuifuId(huifuId);
                request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                request.setReqSeqId("refund-" + payment.getPayCode());
                Map<String, Object> extendInfoMap = new HashMap<>();
                extendInfoMap.put("org_req_seq_id", orderType + "-" + payment.getPayCode());
                request.setExtendInfo(extendInfoMap);
                HuiFuRefundResult refund = huiFuService.refund(request);
                logger.info("订单退款返回结果:退款订单id:" + order.getOrderId() + refund);
                if ((refund.getResp_code().equals("00000000") || refund.getResp_code().equals("00000100")) && (refund.getTrans_stat().equals("S") || refund.getTrans_stat().equals("P"))) {
                    FsStorePaymentScrm paymentMap = new FsStorePaymentScrm();
                    paymentMap.setPaymentId(payment.getPaymentId());
                    paymentMap.setStatus(-1);
                    paymentMap.setRefundTime(DateUtils.getNowDate());
                    paymentMap.setRefundMoney(payment.getPayMoney());
                    fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                } else {
                    throw new CustomException("退款请求失败" + refund.getResp_desc());
                }
            }
            //管易作废
            if (StringUtils.isNotEmpty(fsStoreOrder.getExtendOrderId())) {
                if (!fsStoreOrder.getExtendOrderId().equals("HIS")) {
                    ErpRefundUpdateRequest request = new ErpRefundUpdateRequest();
                    request.setTid(fsStoreOrder.getOrderCode());
                    request.setOid(fsStoreOrder.getOrderCode());
                    request.setRefund_state(1);
                    request.setStoreAfterSalesId(fsStoreAfterSales.getId());
                    FsSysConfig sysConfig = configUtil.getSysConfig();
                    Integer erpType = sysConfig.getErpType();
                    IErpOrderService erpOrderService = getErpService();
                    if (erpType == 1) {
                        erpOrderService.refundUpdate(request);
                    }else if (erpType == 2) {
                        //旺店通
                        wdtErpOrderService.refundUpdate(request);
                    } else if (erpType == 3) {
                        //瀚智
                        hzOMSerpOrderService.refundUpdate(request);
                    }  else if (erpType == 4) {
                        dfOrderService.refundUpdate(request);
                    }else if(erpType == 5){
                        jSTOrderService.refundUpdate(request);
                    }else if(erpType == 6){
                        k9OrderService.refundUpdate(request);
                    }
                }
            }
        } else {
            if (order.getRefundAmount().compareTo(BigDecimal.ZERO) == 0) {

            } else {
                throw new CustomException("未找的支付明细");
            }
        }


        return i;
    }
}
