package com.fs.store.service.impl;

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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
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.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.service.ICompanyService;
import com.fs.erp.dto.BaseResponse;
import com.fs.erp.dto.ErpRefundUpdateRequest;
import com.fs.erp.service.IErpOrderService;
import com.fs.huifuPay.domain.HuiFuRefundResult;
import com.fs.huifuPay.dto.*;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayRefundRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.tzBank.TzBankService;
import com.fs.pay.pay.domain.RefundResult;
import com.fs.pay.pay.service.PayService;
import com.fs.store.config.StoreConfig;
import com.fs.store.domain.*;
import com.fs.store.dto.StoreOrderProductDTO;
import com.fs.store.enums.AfterSalesStatusEnum;
import com.fs.store.enums.AfterStatusEnum;
import com.fs.store.enums.OrderInfoEnum;
import com.fs.store.mapper.FsStoreOrderItemMapper;
import com.fs.store.param.*;
import com.fs.store.service.*;
import com.fs.store.vo.FsStoreAfterSalesQueryVO;
import com.fs.store.vo.FsStoreAfterSalesVO;
import com.fs.store.vo.FsStoreOrderItemVO;
import com.fs.pay.service.IPayService;
import com.fs.system.service.ISysConfigService;
import com.fs.tzBank.utils.TzConfigUtils;
import com.hc.openapi.tool.fastjson.JSON;
import lombok.Synchronized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.store.mapper.FsStoreAfterSalesMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

    @Autowired
    IFsStorePaymentService paymentService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private FsStoreAfterSalesMapper fsStoreAfterSalesMapper;
    @Autowired
    private IFsStoreAfterSalesItemService afterSalesItemService;
    @Autowired
    private IFsStoreAfterSalesStatusService afterSalesStatusService;
    @Autowired
    private IFsStoreOrderService orderService;
    @Autowired
    private IFsStoreOrderItemService orderItemService;
    @Autowired
    private IPayService payService;
    @Autowired
    private FsStoreOrderItemMapper fsStoreOrderItemMapper;
    @Autowired
    private IFsStoreProductService productService;
    @Autowired
    IErpOrderService erpOrderService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private HuiFuService huiFuService;

    @Autowired
    IFsUserService userService;

    @Autowired
    PayService ybPayService;

    @Autowired
    TzBankService tzBankService;


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

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

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

    /**
     * 修改售后记录
     *
     * @param fsStoreAfterSales 售后记录
     * @return 结果
     */
    @Override
    public int updateFsStoreAfterSales(FsStoreAfterSales 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));
        FsStoreOrder order=orderService.selectFsStoreOrderByOrderCode(storeAfterSalesParam.getOrderCode());
        if(!order.getUserId().equals(userId)){
            throw new CustomException("非法操作");
        }

        if (order.getCompanyId()==null||order.getCompanyUserId()==null){
            if (order.getStatus()!=OrderInfoEnum.STATUS_1.getValue()){
                throw new CustomException("不可申请售后");
            }

        }
        if(order.getStatus()==0){
            return R.error("未支付订单不能申请售后");
        }
        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(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);
                FsStoreOrderItem orderItem=new FsStoreOrderItem();
                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);
        //生成售后订单
        FsStoreAfterSales storeAfterSales = new FsStoreAfterSales();
        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());
            FsStoreAfterSalesItem storeAfterSalesItem = new FsStoreAfterSalesItem();
            storeAfterSalesItem.setStoreAfterSalesId(storeAfterSales.getId());
            storeAfterSalesItem.setProductId(item.getProductId());
            storeAfterSalesItem.setJsonInfo(item.getJsonInfo());
            storeAfterSalesItem.setIsDel(0);
            afterSalesItemService.insertFsStoreAfterSalesItem(storeAfterSalesItem);
        }
        //操作记录
        FsStoreAfterSalesStatus storeAfterSalesStatus = new FsStoreAfterSalesStatus();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(0);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_0.getDesc());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        FsUser user=userService.selectFsUserById(userId);
        storeAfterSalesStatus.setOperator(user.getNickname());
        afterSalesStatusService.insertFsStoreAfterSalesStatus(storeAfterSalesStatus);

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

    }

    @Override
    @Transactional
    @Synchronized
    @RepeatSubmit
    public R revoke(long userId, Long id) throws ParseException {
        FsStoreAfterSales 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);
        FsStoreOrder order = orderService.selectFsStoreOrderByOrderCode(storeAfterSales.getOrderCode());
        order.setStatus(storeAfterSales.getOrderStatus());
        order.setRefundStatus(OrderInfoEnum.REFUND_STATUS_0.getValue());
        orderService.updateFsStoreOrder(order);

        //操作记录
        FsStoreAfterSalesStatus storeAfterSalesStatus = new FsStoreAfterSalesStatus();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(5);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_5.getDesc());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        FsUser 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();
                FsStoreOrder orderMap=new FsStoreOrder();
                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){
            FsStoreAfterSalesItem map=new FsStoreAfterSalesItem();
             map.setStoreAfterSalesId(vo.getId());
            List<FsStoreAfterSalesItem>  items=afterSalesItemService.selectFsStoreAfterSalesItemList(map);
            vo.setItems(items);
        }
        return list;
    }

    @Override
    public R addDelivery(FsStoreAfterSalesDeliveryParam param) {
        FsStoreAfterSales 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());

        //操作记录
        FsStoreAfterSalesStatus storeAfterSalesStatus = new FsStoreAfterSalesStatus();
        storeAfterSalesStatus.setStoreAfterSalesId(storeAfterSales.getId());
        storeAfterSalesStatus.setChangeType(2);
        storeAfterSalesStatus.setChangeMessage(AfterSalesStatusEnum.STATUS_2.getDesc());
        storeAfterSalesStatus.setChangeTime(Timestamp.valueOf(LocalDateTime.now()));
        FsUser 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(FsStoreAfterSales fsStoreAfterSales) {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesListVO(fsStoreAfterSales);
    }

//    @Override
//    public R audit(FsStoreAfterSalesAudit1Param param) {
//
//        FsStoreAfterSales storeAfterSales = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(param.getSalesId());
//        if (storeAfterSales == null) {
//            throw new CustomException("未查询到售后订单信息");
//        }
//        if (!storeAfterSales.getStatus().equals(AfterSalesStatusEnum.STATUS_0.getValue())) {
//            throw new CustomException("非法操作");
//        }
//        FsStoreOrder 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{
//                    //将钱退还给用户
//                    FsStorePayment 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("操作成功");
//    }

    @Override
    public synchronized R refundMoney(FsStoreAfterSalesRefundParam param) {
       return refundStoreMoney(param);
    }
    @Transactional
    R refundStoreMoney(FsStoreAfterSalesRefundParam param){
        FsStoreAfterSales 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);

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

        FsStoreAfterSalesStatus storeAfterSalesStatus = new FsStoreAfterSalesStatus();
        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());
        for(FsStoreOrderItemVO vo:orderItemVOS){
            if(vo.getIsAfterSales()==1){
                productService.incProductStock(vo.getNum(), vo.getProductId()
                        , vo.getProductAttrValueId());
            }
        }
        //将钱退还给用户
        if(order.getPayMoney().compareTo(BigDecimal.ZERO)==1){
            List<FsStorePayment> payments=paymentService.selectFsStorePaymentByOrderId(order.getId());
            if(payments!=null){
                for(FsStorePayment payment:payments){
                    if (payment.getPayMode()==null||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("refund-"+payment.getPayCode());
                        refundDTO.setUpOrderId(payment.getTradeNo());

                        RefundResult result=ybPayService.refund(refundDTO);
                        if(result.getState().equals("5")||result.getState().equals("6")){
                            payment.setRefundMoney(payment.getPayMoney());
                            payment.setStatus(-1);
                            payment.setRefundTime(new Date());
                            paymentService.updateFsStorePayment(payment);
                        }
                        else{
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.error(result.getMessage());
                        }
                    }else if (payment.getPayMode()!=null&&payment.getPayMode().equals("hf")){
                        V2TradePaymentScanpayRefundRequest request = new V2TradePaymentScanpayRefundRequest();
                        request.setOrdAmt(payment.getPayMoney().toString());
                        request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                        request.setReqSeqId("refund-"+payment.getPayCode());
                        Map<String, Object> extendInfoMap = new HashMap<>();
                        extendInfoMap.put("org_party_order_id", payment.getBankSerialNo());
                        request.setExtendInfo(extendInfoMap);
                        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(payment.getPayMoney());
                            payment.setStatus(-1);
                            payment.setRefundTime(new Date());
                            paymentService.updateFsStorePayment(payment);
                        }else {
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return R.error(refund.getResp_desc());
                        }

                    } else if(payment.getPayMode() != null && payment.getPayMode().equals("tzbk")){

                        TzConfigInfoDTO tzConfigInfoDTO = TzConfigUtils.getConfig();

                        RequestDTO<TzPayRefundDTO> requestDTO = new RequestDTO<TzPayRefundDTO>();
                        TzPayRefundDTO tzPayRefundDTO = new TzPayRefundDTO();
                        tzPayRefundDTO.setOldPayOutOrderNo(payment.getPayCode());
                        tzPayRefundDTO.setRefundOrderNo(payment.getPayCode());
                        tzPayRefundDTO.setPlatMerCstNo(tzConfigInfoDTO.getPlatMerCstNo());
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        tzPayRefundDTO.setTrxSendTime(sdf.format(new Date()));
                        tzPayRefundDTO.setRefundOrdTransAmt(order.getPayMoney());
                        tzPayRefundDTO.setNotifyURL(tzConfigInfoDTO.getRefundNotifyUrl());
                        requestDTO.setReqBody(tzPayRefundDTO);
                        requestDTO.setReqHeader(TzReqHeaderDTO.getInstance(order.getOrderCode()));

                        TzReqResultDTO<TzRefundNotifyDTO> resultDTO;

                        try {
                            resultDTO = tzBankService.payRefund(requestDTO);
                            TzRefundNotifyDTO body = resultDTO.getBody();
                            String refundOrdStatus = body.getRefundOrdStatus();
                            if("90".equals(refundOrdStatus) || "50".equals(refundOrdStatus)){
                                payment.setRefundMoney(payment.getPayMoney());
                                payment.setStatus(-1);
                                payment.setRefundTime(new Date());
                                paymentService.updateFsStorePayment(payment);
                            } else {
                                throw new RuntimeException("退款请求失败:"+ JSON.toJSONString(resultDTO));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new RuntimeException("退款请求失败"+e);
                        }
                    }
                }
            }
        }
        //减去公司收入
        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();
    }

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

        FsStoreOrder order = orderService.selectFsStoreOrderByOrderCode(storeAfterSales.getOrderCode());
        order.setStatus(storeAfterSales.getOrderStatus());
        order.setRefundStatus(OrderInfoEnum.REFUND_STATUS_0.getValue());
        orderService.updateFsStoreOrder(order);
        storeAfterSales.setSalesStatus(2);
        FsStoreAfterSalesStatus storeAfterSalesStatus = new FsStoreAfterSalesStatus();
        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);
        //创建新的OMS订单
        if (storeAfterSales.getOrderStatus().equals(OrderInfoEnum.STATUS_1.getValue()) ) {
            if(StringUtils.isNotEmpty(order.getExtendOrderId())){
                //更新订单code
                String orderSn = IdUtil.getSnowflake(0, 0).nextIdStr();
                FsStoreOrder orderMap=new FsStoreOrder();
                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) {
        FsStoreAfterSales 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);
            }
            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);
        }
        //退款退货
        else if(storeAfterSales.getServiceType().equals(1)){
            String json=configService.selectConfigByKey("store.config");
            StoreConfig config=JSONUtil.toBean(json,StoreConfig.class);
            FsStoreOrder order=orderService.selectFsStoreOrderByOrderCode(storeAfterSales.getOrderCode());
            if(order.getStoreHouseCode()!=null){
                if(order.getStoreHouseCode().equals("CQDS001")){
                    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);
            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("操作成功");
    }

    @Override
    public R audit2(FsStoreAfterSalesAudit2Param param) {
        FsStoreAfterSales 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);
        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);

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

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

    @Override
    public Boolean isEntityNull(FsStoreAfterSales 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(FsStoreAfterSales fsStoreAfterSales) {
        return fsStoreAfterSalesMapper.updateDeliveryById(fsStoreAfterSales);
    }

    @Override
    @Transactional
    public R autoApplyForAfterSales(long userId, FsStoreAfterSalesParam storeAfterSalesParam) {
        logger.info("申请退款请求信息:"+JSONUtil.toJsonStr(storeAfterSalesParam));
        FsStoreOrder order=orderService.selectFsStoreOrderByOrderCode(storeAfterSalesParam.getOrderCode());
        if(!order.getUserId().equals(userId)){
            throw new CustomException("非法操作");
        }
        if(order.getStatus()==0){
            return R.error("未支付订单不能申请售后");
        }
        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(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);
                FsStoreOrderItem orderItem=new FsStoreOrderItem();
                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);
        //生成售后订单
        FsStoreAfterSales storeAfterSales = new FsStoreAfterSales();
        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());
            FsStoreAfterSalesItem storeAfterSalesItem = new FsStoreAfterSalesItem();
            storeAfterSalesItem.setStoreAfterSalesId(storeAfterSales.getId());
            storeAfterSalesItem.setProductId(item.getProductId());
            storeAfterSalesItem.setJsonInfo(item.getJsonInfo());
            storeAfterSalesItem.setIsDel(0);
            afterSalesItemService.insertFsStoreAfterSalesItem(storeAfterSalesItem);
        }
        //操作记录
        FsStoreAfterSalesStatus storeAfterSalesStatus = new FsStoreAfterSalesStatus();
        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);
        BaseResponse response=erpOrderService.refundUpdate(request);
        if(response.getSuccess()){
            return R.ok();
        }
        else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(response.getErrorDesc());
        }
    }
}
