package com.fs.his.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.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.fs.common.core.domain.AjaxResult;
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.common.utils.poi.ExcelUtil;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.impl.CompanyServiceImpl;
import com.fs.core.config.WxPayProperties;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.his.config.StoreConfig;
import com.fs.erp.dto.BaseResponse;
import com.fs.erp.dto.ErpRefundUpdateRequest;
import com.fs.erp.service.IErpOrderService;
import com.fs.his.domain.*;
import com.fs.his.dto.FsStoreAfterSalesProductDTO;
import com.fs.his.dto.PayConfigDTO;
import com.fs.his.enums.FsInquiryOrderStatusEnum;
import com.fs.his.enums.FsStoreAfterSalesStatusEnum;
import com.fs.his.enums.FsStoreOrderStatusEnum;
import com.fs.his.mapper.*;
import com.fs.his.param.*;
import com.fs.his.service.*;
import com.fs.his.vo.*;
import com.fs.huifuPay.domain.HuiFuRefundResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayRefundRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.im.dto.*;
import com.fs.im.service.IImService;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.ybPay.dto.RefundDTO;
import com.fs.ybPay.service.IPayService;
import com.fs.system.service.ISysConfigService;
import com.fs.tzBankPay.TzBankService.TzBankService;
import com.fs.tzBankPay.config.TzBankConfig;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 售后记录Service业务层处理
 *
 * @author fs
 * @date 2023-06-13
 */
@Service
public class FsStoreAfterSalesServiceImpl implements IFsStoreAfterSalesService {
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private FsStoreAfterSalesMapper fsStoreAfterSalesMapper;
    @Autowired
    private FsStoreAfterSalesLogsMapper fsStoreAfterSalesLogsMapper;
    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;
    @Autowired
    private FsStoreOrderLogsMapper fsStoreOrderLogsMapper;
    @Autowired
    private FsStoreOrderItemMapper fsStoreOrderItemMapper;
    @Autowired
    private IFsStoreProductService productService;
    @Autowired
    private TzBankService tzBankService;
    @Autowired
    private IErpOrderService erpOrderService;
    @Autowired
    private FsStorePaymentMapper fsStorePaymentMapper;
    @Autowired
    IPayService payService;
    @Autowired
    SysConfigMapper sysConfigMapper;
    @Autowired
    FsPackageOrderMapper fsPackageOrderMapper;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private HuiFuService huiFuService;
    @Autowired
    private FsStoreAfterSalesItemMapper fsStoreAfterSalesItemMapper;
    @Autowired
    private IFsUserService userService;
    @Autowired
    FsInquiryOrderMapper fsInquiryOrderMapper;
    @Autowired
    IFsStoreOrderService fsStoreOrderService;
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    FsInquiryOrderMapper inquiryOrderMapper;
    @Autowired
    private ICompanyService companyService;
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private IFsUserService fsUserService;
    @Autowired
    FsStoreMapper fsStoreMapper;
    @Autowired
    FsExportTaskMapper fsExportTaskMapper;
    @Autowired
    IFsStoreOrderBillLogService fsStoreOrderBillLogService;


    /**
     * 查询售后记录
     *
     * @param 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 需要删除的售后记录主键
     * @return 结果
     */
    @Override
    public int deleteFsStoreAfterSalesByIds(Long[] ids) {
        return fsStoreAfterSalesMapper.deleteFsStoreAfterSalesByIds(ids);
    }

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

    @Override
    public List<FsStoreAfterSalesListVO> selectFsStoreAfterSalesListVO(FsStoreAfterSalesParam fsStoreAfterSales) {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesListVO(fsStoreAfterSales);
    }

    @Override
    public List<FsStoreAfterSalesItem> 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);
    }

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

        throw new CustomException("订单不存在");
        }
        if (order.getSalesStatus()!=0){
            throw new CustomException("非法更改");
        }
        Integer status=null;
        FsStoreAfterSales fs = new FsStoreAfterSales();
        if (order.getOrderStatus()==2){
            status=3;
        }else if (order.getOrderStatus()==3){
            FsStore fsStore = fsStoreMapper.selectFsStoreByStoreId(order.getStoreId());
            fs.setPhoneNumber(fsStore.getRefundPhone());
            fs.setAddress(fsStore.getRefundAddress());
            fs.setConsignee(fsStore.getRefundConsignee());
            status=2;
        }else if (order.getOrderStatus()==4){
            FsStore 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);
        FsStoreAfterSalesLogs logs = new FsStoreAfterSalesLogs();
        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);
        return 1;
    }

    @Transactional
    @Override
    public int noAuditing(FsStoreAfterSales fsStoreAfterSales) {
        FsStoreAfterSales 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("非法更改");}
        FsStoreAfterSales fs = new FsStoreAfterSales();
        fs.setId(fsStoreAfterSales.getId());
        fs.setSalesStatus(2);
        fs.setStatus(5);
        int i = fsStoreAfterSalesMapper.updateFsStoreAfterSales(fs);
        FsStoreAfterSalesLogs logs = new FsStoreAfterSalesLogs();
        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);
//        FsStoreOrderLogs Logs = new FsStoreOrderLogs();
//        Logs.setChangeMessage("已取消退款");
//        Logs.setOrderId(order.getOrderId());
//        Logs.setChangeTime(new DateTime());
//        Logs.setChangeType(order.getOrderStatus().toString());
//        fsStoreOrderLogsMapper.insertFsStoreOrderLogs(Logs);
        FsStoreOrder or = new FsStoreOrder();
        or.setOrderId(order.getOrderId());
        or.setStatus(order.getOrderStatus());
        fsStoreOrderMapper.updateFsStoreOrder(or);
        if (order.getOrderStatus()==2){
            FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderId(order.getOrderId());
            String newOrderSn =  OrderCodeUtils.getOrderSn();
            if(StringUtils.isEmpty(newOrderSn)){
                newOrderSn =  OrderCodeUtils.getOrderSn();
            }
            FsStoreOrder newOrder = new FsStoreOrder();
            newOrder.setOrderId(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<FsStorePayment> payments = fsStorePaymentMapper.selectFsStorePaymentByPay(2,fsStoreOrder.getOrderId());
            if (fsStoreOrder.getPackageOrderId()!=null){
                payments = fsStorePaymentMapper.selectFsStorePaymentByPay(3,fsStoreOrder.getPackageOrderId());
            }
            for (FsStorePayment payment : payments) {
                FsStorePayment fsStorePayment = new FsStorePayment();
                fsStorePayment.setPaymentId(payment.getPaymentId());
                fsStorePayment.setBusinessCode(newOrderSn);
                fsStorePaymentMapper.updateFsStorePayment(fsStorePayment);
            }

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

            }

        }






        return 1;
    }

    @Transactional
    @Override
    public int refundMoney(FsStoreAfterSales fsStoreAfterSales) {
        FsStoreAfterSales order = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(fsStoreAfterSales.getId());
        FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderId(order.getOrderId());
        if (order==null)throw new CustomException("订单不存在");
        if (order.getStatus()!=3)throw new CustomException("非法更改");
        //更改售后订单状态
        FsStoreAfterSales fs = new FsStoreAfterSales();
        fs.setId(fsStoreAfterSales.getId());
        fs.setStatus(4);
        fs.setSalesStatus(3);
        int i = fsStoreAfterSalesMapper.updateFsStoreAfterSales(fs);
        FsStoreAfterSalesLogs logs = new FsStoreAfterSalesLogs();
        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);
        //更改订单状态
        FsStoreOrder or = new FsStoreOrder();
        or.setOrderId(order.getOrderId());
        or.setStatus(-2);
        or.setRefundTime(DateUtils.getNowDate());
        fsStoreOrderMapper.updateFsStoreOrder(or);
        FsStoreOrderLogs Logs = new FsStoreOrderLogs();
        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.getOrderId());


        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.refundCompanyMoney(fsStoreOrder);
        }

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

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

            payments = fsStorePaymentMapper.selectFsStorePaymentByPay(3,fsStoreOrder.getPackageOrderId());
        }
        if(payments!=null&&payments.size()>0){
            FsStorePayment payment=payments.get(0);
            String json=configService.selectConfigByKey("his.pay");
            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")){
                        FsStorePayment paymentMap=new FsStorePayment();
                        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")){
                //易宝
                RefundDTO refundDTO=new 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")){
                    FsStorePayment paymentMap=new FsStorePayment();
                    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<com.fs.tzBankPay.doman.RefundResult> result = tzBankService.refund(tzBankResult);
                logger.info("订单退款返回结果:退款订单id:"+order.getOrderId()+result);
                if(result.getBody().getRefundOrdStatus().equals("90")||result.getBody().getRefundOrdStatus().equals("60")){
                    FsStorePayment paymentMap=new FsStorePayment();
                    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")){
                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_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"))){
                    FsStorePayment paymentMap=new FsStorePayment();
                    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);
                    erpOrderService.refundUpdate(request);
                }
            }
        }else {
            if (order.getRefundAmount().compareTo(BigDecimal.ZERO) == 0){

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


        return i;
    }

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

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

    @Override
    @Transactional
    public R applyAfterSales(long uesrId, FsStoreAfterSalesApplyParam param) {
        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(param.getOrderId());
        if (!order.getUserId().equals(uesrId)) {
            throw new CustomException("非法操作");
        }
        if (order.getOrderType().equals(2)) {
            return R.error("中药订单不允许发起售后");
        }
        if (order.getStatus() == 0) {
            return R.error("未支付订单不能申请售后");
        }
//        if (StringUtils.isEmpty(order.getExtendOrderId())) {
//            return R.error("仓库未生成订单,暂时不能申请退款,请联系客服");
//        }
        if (order.getStatus() == FsStoreOrderStatusEnum.STATUS_NE3.getValue()) {
            return R.error("已取消订单不能申请售后");
        }
        if (order.getStatus() == FsStoreOrderStatusEnum.STATUS_NE2.getValue()) {
            return R.error("已退款订单不能申请售后");
        }
        if (order.getStatus() == FsStoreOrderStatusEnum.STATUS_NE1.getValue()) {
            return R.error("已提交申请,等待处理");
        }
        if (order.getPayType()==3&&order.getStatus()>=FsStoreOrderStatusEnum.STATUS_3.getValue() ){
            return  R.error("货到付款已发货订单，不支持申请售后");
        }
//        if(storeAfterSalesParam.getRefundAmount().compareTo(order.getPayPrice())==1){
//            return R.error("退款金额不能大于支付金额");
//        }
        //已完成订单七天后不能申请退款
        if(order.getIsAfterSales()==0){
            return R.error("此订单已超过售后时间,不能提交售后");
        }
//        if (order.getStatus().equals(FsStoreOrderStatusEnum.STATUS_4.getValue())) {
//            String json = configService.selectConfigByKey("his.store");
//            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<FsStoreOrderItem> orderItems = fsStoreOrderItemMapper.selectFsStoreOrderItemListByOrderId(order.getOrderId());
        for (FsStoreOrderItem item : orderItems) {
            FsStoreAfterSalesProductDTO prosuctParam = param.getProductList().stream().filter(p -> p.getProductId().equals(item.getProductId())).findFirst().orElse(new FsStoreAfterSalesProductDTO());
            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);
                fsStoreOrderItemMapper.updateFsStoreOrderItem(orderItem);

            }
        }
        //更新订单状态
        Integer orderStatus = order.getStatus();
        order.setStatus(FsStoreOrderStatusEnum.STATUS_NE1.getValue());
        order.setRefundStatus(FsStoreOrderStatusEnum.REFUND_STATUS_1.getValue().toString());
        order.setRefundReason(param.getReasons());
        order.setRefundExplain(param.getExplains());
        order.setRefundTime(new Date());
        fsStoreOrderMapper.updateFsStoreOrder(order);
        //生成售后订单
        FsStoreAfterSales storeAfterSales = new FsStoreAfterSales();
        storeAfterSales.setOrderId(order.getOrderId());
        storeAfterSales.setStoreId(order.getStoreId());
        storeAfterSales.setDeptId(order.getDeptId());
        storeAfterSales.setRefundAmount(param.getRefundAmount());
        storeAfterSales.setRefundType(param.getRefundType());
        storeAfterSales.setReasons(param.getReasons());
        storeAfterSales.setExplains(param.getExplains());
        storeAfterSales.setExplainImg(param.getExplainImg());
        storeAfterSales.setStatus(FsStoreAfterSalesStatusEnum.STATUS_0.getValue());
        storeAfterSales.setSalesStatus(0);
        storeAfterSales.setCreateTime(Timestamp.valueOf(LocalDateTime.now()));
        storeAfterSales.setIsDel(0);
        storeAfterSales.setUserId(uesrId);
        storeAfterSales.setOrderStatus(orderStatus);
        storeAfterSales.setCompanyId(order.getCompanyId());
        storeAfterSales.setCompanyUserId(order.getCompanyUserId());
        fsStoreAfterSalesMapper.insertFsStoreAfterSales(storeAfterSales);
        //售后商品详情
        for (FsStoreAfterSalesProductDTO productParam : param.getProductList()) {
            FsStoreOrderItem item = orderItems.stream().filter(p -> p.getProductId().equals(productParam.getProductId())).findFirst().orElse(new FsStoreOrderItem());
            FsStoreAfterSalesItem storeAfterSalesItem = new FsStoreAfterSalesItem();
            storeAfterSalesItem.setAfterSalesId(storeAfterSales.getId());
            storeAfterSalesItem.setProductId(item.getProductId());
            storeAfterSalesItem.setJsonInfo(item.getJsonInfo());
            storeAfterSalesItem.setIsDel(0);
            fsStoreAfterSalesItemMapper.insertFsStoreAfterSalesItem(storeAfterSalesItem);
        }
        //操作记录
        FsStoreAfterSalesLogs logs = new FsStoreAfterSalesLogs();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(0);
        FsUser user = userService.selectFsUserByUserId(order.getUserId());
        logs.setOperator(user.getNickName());
        logs.setStoreAfterSalesId(storeAfterSales.getId());
        logs.setChangeMessage(FsStoreAfterSalesStatusEnum.STATUS_0.getDesc());
        fsStoreAfterSalesLogsMapper.insertFsStoreAfterSalesLogs(logs);
        if(order.getExtendOrderId()!=null){
            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());
            }
        }
        //更新OMS
        return R.ok();
    }

    @Override
    @Transactional
    public R revoke(long userId, FsStoreAfterSalesRevokeParam param) {
        FsStoreAfterSales storeAfterSales = fsStoreAfterSalesMapper.selectFsStoreAfterSalesById(param.getId());
        if (storeAfterSales == null) {
            throw new CustomException("未查询到售后订单信息");
        }
        if (storeAfterSales.getSalesStatus() != 0) {
            throw new CustomException("非法操作");
        }
        if (storeAfterSales.getStatus().equals(FsStoreAfterSalesStatusEnum.STATUS_2.getValue()) || storeAfterSales.getStatus().equals(FsStoreAfterSalesStatusEnum.STATUS_3.getValue()) || storeAfterSales.getStatus().equals(FsStoreAfterSalesStatusEnum.STATUS_4.getValue())) {
            throw new CustomException("已发货退款单不能撤销");
        }
        //只有未发货的可以撤销，
        if (!storeAfterSales.getOrderStatus().equals(FsStoreOrderStatusEnum.STATUS_2.getValue())) {
            throw new CustomException("只有未发货的订单可以撤销售后");
        }


        storeAfterSales.setSalesStatus(1);
        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(storeAfterSales.getOrderId());
        order.setStatus(storeAfterSales.getOrderStatus());
        order.setRefundStatus(FsStoreOrderStatusEnum.REFUND_STATUS_0.getValue().toString());
        fsStoreOrderMapper.updateFsStoreOrder(order);

        //操作记录
        FsStoreAfterSalesLogs logs = new FsStoreAfterSalesLogs();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(5);
        FsUser user = userService.selectFsUserByUserId(order.getUserId());
        logs.setOperator(user.getNickName());
        logs.setStoreAfterSalesId(storeAfterSales.getId());
        logs.setChangeMessage(FsStoreAfterSalesStatusEnum.STATUS_5.getDesc());
        fsStoreAfterSalesLogsMapper.insertFsStoreAfterSalesLogs(logs);
        if (storeAfterSales.getOrderStatus().equals(FsStoreOrderStatusEnum.STATUS_2.getValue())) {
            if (StringUtils.isNotEmpty(order.getExtendOrderId())) {
                //更新订单code
                String orderSn =  OrderCodeUtils.getOrderSn();
                if(StringUtils.isEmpty(orderSn)){
                    return R.error("订单生成失败，请重试");
                }
                FsStoreOrder orderMap=new FsStoreOrder();
                orderMap.setOrderId(order.getOrderId());
                orderMap.setOrderCode(orderSn);
                fsStoreOrderMapper.updateFsStoreOrder(orderMap);
                //生成新的订单

                if (order.getPackageOrderId()!=null){
                    FsPackageOrder fsPackageOrder = new FsPackageOrder();
                    fsPackageOrder.setOrderId(order.getPackageOrderId());
                    fsPackageOrder.setOrderSn(orderSn);
                    fsPackageOrderMapper.updateFsPackageOrder(fsPackageOrder);
                }
                if (order.getInquiryOrderId()!=null){
                    FsInquiryOrder fsInquiryOrder = new FsInquiryOrder();
                    fsInquiryOrder.setOrderSn(orderSn);
                    fsInquiryOrder.setOrderId(order.getInquiryOrderId());
                    fsInquiryOrderMapper.updateFsInquiryOrder(fsInquiryOrder);
                }

                List<FsStorePayment> payments = fsStorePaymentMapper.selectFsStorePaymentByPay(2,order.getOrderId());
                if (order.getPackageOrderId()!=null){
                    payments = fsStorePaymentMapper.selectFsStorePaymentByPay(3,order.getPackageOrderId());
                }
                for (FsStorePayment payment : payments) {
                    FsStorePayment fsStorePayment = new FsStorePayment();
                    fsStorePayment.setPaymentId(payment.getPaymentId());
                    fsStorePayment.setBusinessCode(orderSn);
                    fsStorePaymentMapper.updateFsStorePayment(fsStorePayment);
                }


                try {
                    fsStoreOrderService.createOmsOrder(order.getOrderId());
                }
                catch (Exception e){
                }
            }
        }
        fsStoreAfterSalesMapper.updateFsStoreAfterSales(storeAfterSales);
        return R.ok();

    }

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

        //操作记录
        FsStoreAfterSalesLogs logs = new FsStoreAfterSalesLogs();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(2);
        FsUser user = userService.selectFsUserByUserId(storeAfterSales.getUserId());
        logs.setOperator(user.getNickName());
        logs.setStoreAfterSalesId(storeAfterSales.getId());
        logs.setChangeMessage(FsStoreAfterSalesStatusEnum.STATUS_2.getDesc());
        fsStoreAfterSalesLogsMapper.insertFsStoreAfterSalesLogs(logs);

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

    }

    @Override
    public int depotAuditing(FsStoreAfterSales fsStoreAfterSales) {
        FsStoreAfterSales 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("非法更改");
        }
        FsStoreAfterSales fs = new FsStoreAfterSales();
        fs.setId(fsStoreAfterSales.getId());
        fs.setStatus(3);
        int i = fsStoreAfterSalesMapper.updateFsStoreAfterSales(fs);
        FsStoreAfterSalesLogs logs = new FsStoreAfterSalesLogs();
        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);
        return 1;
    }

    @Override
    public List<FsStoreAfterSalesListUVO> selectFsStoreAfterSalesListUVO(FsStoreAfterSalesListUParam param) {
        List<FsStoreAfterSalesListUVO>  list=fsStoreAfterSalesMapper.selectFsStoreAfterSalesListUVO(param);
        for(FsStoreAfterSalesListUVO vo:list){
            FsStoreAfterSalesItem map=new FsStoreAfterSalesItem();
            map.setAfterSalesId(vo.getId());
            List<FsStoreAfterSalesItem>  items=fsStoreAfterSalesItemMapper.selectFsStoreAfterSalesItemList(map);
            vo.setItems(items);
        }
        return  list;
    }

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

    @Override
    public Boolean isEntityNull(FsStoreAfterSalesParam param) {
        if (param == null) {
            return true; // 整个实体对象为null
        }

        Class<? extends FsStoreAfterSalesParam> entityClass = param.getClass();
        Field[] fields = entityClass.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(param);
                if (value != null) {
                    return false; // 实体对象中有字段不为null
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return true; // 实体对象内所有字段为null
    }

    @Override
    public Long selectFsStoreAfterSalesExcelListVOCount(FsStoreAfterSalesParam fsStoreAfterSales) {
        return fsStoreAfterSalesMapper.selectFsStoreAfterSalesExcelListVOCount(fsStoreAfterSales);
    }
    @Async
    @Override
    public void exportData(FsStoreAfterSalesParam fsStoreAfterSales) {
        List<FsStoreAfterSalesExcelVO> list = fsStoreAfterSalesMapper.selectFsStoreAfterSalesExcelListVO(fsStoreAfterSales);

        ExcelUtil<FsStoreAfterSalesExcelVO> util = new ExcelUtil<>(FsStoreAfterSalesExcelVO.class);
        AjaxResult result = util.exportExcel(list, "售后记录数据");
        FsExportTask task=fsExportTaskMapper.selectFsExportTaskByTaskId(fsStoreAfterSales.getTaskId());
        task.setFinishTime(new Date());
        task.setStatus(1);
        task.setFileUrl(result.get("msg").toString());
        fsExportTaskMapper.updateFsExportTask(task);
    }
}
