package com.kmall.api.service.wxGlobal;

import com.google.common.collect.Maps;
import com.kmall.api.fromcomm.entity.FormIdsEntity;
import com.kmall.manager.manager.wechat.WechatGlobalUtil;
import com.kmall.manager.manager.wechat.WechatUtil;
import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalNotifyResult;
import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalQueryApiResult;
import com.kmall.api.fromcomm.service.FormIdsService;
import com.kmall.common.constant.Dict;
import com.kmall.api.dao.*;
import com.kmall.api.entity.*;
import com.kmall.api.service.ApiOrderService;
import com.kmall.api.service.PayerChildOrderRealService;
import com.kmall.manager.manager.pay.wxpay.WxPayPropertiesBuilder;
import com.kmall.common.utils.Constant;
import com.kmall.common.utils.DateUtils;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 小程序form_id收集Service实现类
 *
 * @author Scott
 * @email
 * @date 2017-12-16 15:32:50
 */
@Service
public class ApiWxGlobalPayService {
    private Log logger = LogFactory.getLog(ApiWxGlobalPayService.class);
    @Autowired
    private ApiOrderService orderService;
    @Autowired
    private FormIdsService formIdsService;
    @Autowired
    private PayerChildOrderRealService payerChildOrderRealService;
    @Autowired
    private ApiOrderExceptionRecordMapper mallOrderExceptionRecordMapper;
    @Autowired
    private ApiOrderProcessRecordMapper orderProcessRecordMapper;
    @Autowired
    private ApiOrderRefundMapper mallOrderRefundMapper;


    @Transactional
    public void payPrepay(Map<Object, Object> resultObj, WechatGlobalQueryApiResult queryApiResult, String nonceStr, List<OrderVo> orderVoList) {
        logger.info("payPrepay》》》》更新订单状态");
        String prepay_id = queryApiResult.getPrepay_id();
        resultObj.put("appId", WxPayPropertiesBuilder.instance().getAppId());
        resultObj.put("timeStamp", DateUtils.timeToStr(System.currentTimeMillis() / 1000, DateUtils.DATE_TIME_PATTERN));
        resultObj.put("nonceStr", nonceStr);
        resultObj.put("package", "prepay_id=" + prepay_id);
        resultObj.put("signType", "MD5");
        String paySign = WechatUtil.arraySign(resultObj, WxPayPropertiesBuilder.instance().getPaySignKey());
        resultObj.put("paySign", paySign);
        for (OrderVo orderInfo: orderVoList) {
            // 业务处理
            orderInfo.setPay_id(prepay_id);
            orderInfo.setPayFlag(Dict.payFlag.item_wxglobalpay.getItem());
            orderInfo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_100.getItem()));
            orderInfo.setPay_status(Integer.parseInt(Dict.payStatus.item_1.getItem())); // 付款中
            orderService.update(orderInfo);

            Map map = Maps.newHashMap();
            map.put("orderSn", orderInfo.getOrder_sn());
            List<PayerChildOrderRealEntity> list = payerChildOrderRealService.queryList(map);
            PayerChildOrderRealEntity entity = new PayerChildOrderRealEntity();
            entity.setGoodsBizType(orderInfo.getOrderBizType());
            entity.setOrderSn(orderInfo.getOrder_sn());
            entity.setMerchSn(orderInfo.getMerchSn());
            entity.setMerchOrderSn(orderInfo.getMerchOrderSn());
            entity.setPayNo(orderInfo.getPay_id());
            entity.setPayPrice(orderInfo.getActual_price());
            entity.setCreateTime(new Date());
            entity.setModTime(new Date());
            entity.setUserId(Integer.parseInt(orderInfo.getUser_id() + ""));
            if(list.size() > 0) {
                for (PayerChildOrderRealEntity payerChildOrderRealEntity:list) {
                    entity.setId(payerChildOrderRealEntity.getId());
                    payerChildOrderRealService.update(entity);
                }
            }else{
                payerChildOrderRealService.save(entity);//记录微信返回的支付单与子订单信息
            }
            FormIdsEntity formIdsEntity = formIdsService.getFormIdsByMerchOrderSn(orderInfo.getMerchOrderSn());
            if(formIdsEntity != null){
                FormIdsEntity formIds = new FormIdsEntity();
                formIds.setMerchOrderSn(orderInfo.getMerchOrderSn());
                formIds.setFormId(prepay_id);
                formIds.setValidNum(formIdsEntity.getValidNum()+1);
                formIds.setId(formIdsEntity.getId());
                formIdsService.releaseFormIds(formIds);
            }else{
                // 保存form_id
                formIdsService.save(orderInfo.getUser_id(), prepay_id, 1, orderInfo.getMerchOrderSn());
            }
        }
    }

    @Transactional
    public void notify(WechatGlobalNotifyResult result) {
        String time_end = result.getTime_end();
        String out_trade_no = result.getOut_trade_no();//商户订单号
        String transaction_id = result.getTransaction_id();//微信支付订单号
        String total_fee = result.getTotal_fee();//订单编号
        // 支付成功业务处理
        List<OrderVo> orderVoList = orderService.queryObjectByMerchOrderSn(out_trade_no);
        List<OrderProcessRecordEntity> processRecordEntityList = new ArrayList<>();
        Date timeEnd = DateUtils.convertStringToDate(time_end,DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
        if(orderVoList != null && orderVoList.size()>0) {
            for(OrderVo orderInfo:orderVoList) {
                //校验返回的订单金额是否与商户侧的订单金额一致
                String actualPrice = String.valueOf(orderInfo.getActual_price().multiply(Constant.ONE_HUNDRED));
                if(!total_fee.equalsIgnoreCase(actualPrice)){//不一致
                    MallOrderExceptionRecord mallOrderExceptionRecord = new MallOrderExceptionRecord();
                    mallOrderExceptionRecord.setUserId(Integer.parseInt(orderInfo.getUser_id()+""));
                    mallOrderExceptionRecord.setOrderSn(orderInfo.getOrder_sn());
                    mallOrderExceptionRecord.setExceptionStatus(Dict.exceptionStatus.item_04.getItem());
                    mallOrderExceptionRecord.setCreateTime(new Date());
                    mallOrderExceptionRecord.setExceptionContent("微信支付回调返回的订单金额与商户订单金额不一致");
                    mallOrderExceptionRecordMapper.save(mallOrderExceptionRecord);//支付订单异常记录
                }
                if(Dict.orderStatus.item_100.getItem().equalsIgnoreCase(orderInfo.getOrder_status()+"")
                        && Dict.payStatus.item_1.getItem().equalsIgnoreCase(orderInfo.getPay_status()+"")){
                    OrderProcessRecordEntity processRecordEntity = orderProcessRecordMapper.queryObjectByOrderSn(orderInfo.getOrder_sn());
                    if(processRecordEntity != null){
                        OrderProcessRecordEntity entity = new OrderProcessRecordEntity();
                        entity.setOrderSn(orderInfo.getOrder_sn());
                        entity.setUserId(Integer.valueOf(orderInfo.getUser_id()+""));
                        entity.setPaySuccTime(timeEnd);//微信下单完成时间
                        entity.setId(processRecordEntity.getId());
                        processRecordEntityList.add(entity);
                    }

                    orderInfo.setPayTransactionId(transaction_id);
                    orderInfo.setPay_status(Integer.parseInt(Dict.payStatus.item_2.getItem()));
                    orderInfo.setPay_time(timeEnd);//微信下单完成时间
                    if (orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_100.getItem())) {
                        orderInfo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_201.getItem()));
                    }
                    orderInfo.setTotalFee(Integer.parseInt(result.getTotal_fee()));//标价金额
                    orderInfo.setFeeType(result.getFee_type());//标价币种
                    orderInfo.setCashFee(Integer.parseInt(result.getCash_fee()));//用户支付金额
                    orderInfo.setCashFeeType(result.getCash_fee_type());//用户支付金额币种
                    orderInfo.setRate(result.getRate_value());//汇率
                    orderService.update(orderInfo);
                    orderProcessRecordMapper.updateBatch(processRecordEntityList);//更新订单流转信息

                    // 微信支付成功通知
                    orderService.notifyPaySuccess(orderInfo);
                }
            }
        }
    }


    @Transactional
    public void refundNotify(WechatRefundApiResult refundApiResult) {
        String success_time = refundApiResult.getSuccess_time();
        String out_trade_no = refundApiResult.getOut_trade_no();//商户订单号
        // 业务处理
        List<OrderVo> orderVoList = orderService.queryOrderByMerchOrderSnAndRefundStatus(out_trade_no);
        Date successTime = DateUtils.strToDate(success_time);
        if(orderVoList != null && orderVoList.size()>0) {
            for(OrderVo orderInfo:orderVoList) {
                if(orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_201.getItem())
                        || orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_401.getItem())){
                    MallOrderRefund mallOrderRefund = mallOrderRefundMapper.queryObjectByOrderId(orderInfo.getId()+"");
                    MallOrderRefund orderRefund = new MallOrderRefund();
                    OrderVo orderVo = new OrderVo();
                    if(mallOrderRefund != null){
                        orderRefund.setOutRefundNo(refundApiResult.getOut_refund_no());
                        orderRefund.setRefundTime(successTime);//退款成功时间
                        orderRefund.setRefundId(refundApiResult.getRefund_id());
                        orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(refundApiResult.getRefund_fee())).divide(Constant.ONE_HUNDRED));
                        if (refundApiResult.getRefund_status().equalsIgnoreCase(WechatGlobalUtil.WXTradeState.SUCCESS.getCode())) {
                            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));
                            orderRefund.setWechatRefundStatusDes("退款成功");
                            orderVo.setPay_status(Integer.parseInt(Dict.payStatus.item_4.getItem()));
                        } else if (refundApiResult.getRefund_status().equalsIgnoreCase("PROCESSING")) {
                            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));
                            orderRefund.setWechatRefundStatusDes("退款处理中");
                            orderVo.setPay_status(Integer.parseInt(Dict.payStatus.item_3.getItem()));
                        } else if (refundApiResult.getRefund_status().equalsIgnoreCase("REFUNDCLOSE")) {
                            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
                            orderRefund.setWechatRefundStatusDes("退款关闭");
                            orderVo.setPay_status(Integer.parseInt(Dict.payStatus.item_5.getItem()));
                        } else if (refundApiResult.getRefund_status().equalsIgnoreCase("CHANGE")) {
                            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
                            orderRefund.setWechatRefundStatusDes("退款异常");
                            orderVo.setPay_status(Integer.parseInt(Dict.payStatus.item_6.getItem()));
                        }
                        orderRefund.setRefundRecvAccout(refundApiResult.getRefund_recv_accout());
                        orderRefund.setId(mallOrderRefund.getId());
                        mallOrderRefundMapper.update(orderRefund);//更新订单退款信息

                        orderVo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
                        orderVo.setId(orderInfo.getId());
                        orderService.update(orderVo);
                    }
                }
            }
        }
    }

}
