package com.kmall.api.service;

import com.google.common.collect.Maps;
import com.kmall.api.dao.ApiOrderExceptionRecordMapper;
import com.kmall.api.dao.ApiOrderProcessRecordMapper;
import com.kmall.api.dao.ApiOrderRefundMapper;
import com.kmall.api.dao.cus.pay.data.open.ApiCusPayDataOpenMapper;
import com.kmall.api.entity.*;
import com.kmall.api.entity.cus.pay.data.open.CusPayDataOpenVo;
import com.kmall.api.fromcomm.entity.FormIdsEntity;
import com.kmall.manager.manager.wechat.WechatUtil;
import com.kmall.api.fromcomm.service.FormIdsService;
import com.kmall.manager.manager.pay.wxpay.WxPayPropertiesBuilder;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.Constant;
import com.kmall.common.utils.DateUtils;
import com.kmall.common.utils.MapUtils;
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 ApiPayService {
    private static Log logger = LogFactory.getLog(ApiPayService.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;
    @Autowired
    private ApiCusPayDataOpenMapper cusPayDataOpenMapper;


    @Transactional
    public void payPrepay(Map<Object, Object> resultObj, Map<String, Object> resultUn, String nonceStr, List<OrderVo> orderVoList) {
        String prepay_id = MapUtils.getString("prepay_id", resultUn);
        // 先生成paySign 参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
        //resultObj.put("appId", ResourceUtil.getConfigByName("wx.appId"));
        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, ResourceUtil.getConfigByName("wx.paySignKey"));
        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_weixin.getItem());
            orderInfo.setPay_status(Integer.parseInt(Dict.payStatus.item_1.getItem())); // 付款中
            orderInfo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_100.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) {
                payerChildOrderRealService.save(entity);//记录微信返回的支付单与子订单信息
            }else{
                for (PayerChildOrderRealEntity payerChildOrderRealEntity:list) {
                    entity.setId(payerChildOrderRealEntity.getId());
                    payerChildOrderRealService.update(entity);
                }
            }
            if(orderInfo.getPay_status() == Integer.parseInt(Dict.payStatus.item_2.getItem())) {
                FormIdsEntity formIdsEntity = formIdsService.getFormIdsByMerchOrderSn(orderInfo.getMerchOrderSn());
                if (formIdsEntity == null) {
                    // 保存form_id，已废弃_2020-1-10
                    // formIdsService.save(orderInfo.getUser_id(), prepay_id, 1, orderInfo.getMerchOrderSn());
                } else {
                    FormIdsEntity formIds = new FormIdsEntity();
                    formIds.setMerchOrderSn(orderInfo.getMerchOrderSn());
                    formIds.setFormId(prepay_id);
                    formIds.setId(formIdsEntity.getId());
                    formIds.setValidNum(formIdsEntity.getValidNum() + 1);
                    formIdsService.releaseFormIds(formIds);
                }
            }
        }
    }

    @Transactional
    public void notify(String out_trade_no, String total_fee, String transaction_id, String time_end, String reponseStr) {
        // 支付成功业务处理
        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(Math.round(orderInfo.getActual_price().multiply(Constant.ONE_HUNDRED).doubleValue()));
                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.setExceptionContent("微信支付回调返回的订单金额与商户订单金额不一致");
                    mallOrderExceptionRecord.setCreateTime(new Date());
                    mallOrderExceptionRecordMapper.save(mallOrderExceptionRecord);//支付订单异常记录
                }
                if((Dict.orderStatus.item_100.getItem().equalsIgnoreCase(orderInfo.getOrder_status()+"")
                        && Dict.payStatus.item_1.getItem().equalsIgnoreCase(orderInfo.getPay_status()+""))
                        || (Dict.orderStatus.item_0.getItem().equalsIgnoreCase(orderInfo.getOrder_status()+"")
                        && Dict.payStatus.item_0.getItem().equalsIgnoreCase(orderInfo.getPay_status() + ""))
                        || (Dict.orderStatus.item_101.getItem().equalsIgnoreCase(orderInfo.getOrder_status()+"")
                        && Dict.payStatus.item_0.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().toString()));
                        entity.setId(processRecordEntity.getId());
                        entity.setPaySuccTime(timeEnd);//微信下单完成时间
                        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.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_0.getItem()) ||
                            orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_101.getItem())) {
                        orderInfo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_201.getItem()));
                    }
                    orderService.update(orderInfo);
                    orderProcessRecordMapper.updateBatch(processRecordEntityList);//更新订单流转信息
                    /*// 处理团购 todo 一期不实现团购
                    if (null != orderInfo.getOrder_type() && orderInfo.getOrder_type().equals("2")) {
                        GoodsGroupOpenDetailVo openDetailVo = apiGoodsGroupOpenDetailService.queryObject(orderInfo.getActivity_id());
                        if (null != openDetailVo) {
                            openDetailVo.setAttend_status(1);
                            apiGoodsGroupOpenDetailService.update(openDetailVo);
                        }
                        GoodsGroupOpenVo openVo = apiGoodsGroupOpenService.queryObject(openDetailVo.getOpen_id());
                        openVo.setAttend_num(openVo.getAttend_num() + 1);
                        if (openVo.getMin_open_group() <= openVo.getAttend_num()) { // 一人拼团，直接结束
                            openVo.setAttend_status(2);
                            Map param = Maps.newHashMap();
                            param.put("open_id", openDetailVo.getOpen_id());
                            apiGoodsGroupOpenDetailService.updateComplete(param);
                        } else {
                            openVo.setAttend_status(1);
                        }
                        apiGoodsGroupOpenService.update(openVo);
                    }*/

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

                   /* // 打印机打印 todo 后台打印小票，后期需要可放开注释
                    try {
                        orderService.printMsg(orderInfo.getId());
                    } catch (Exception e) {
                        logger.error("打印机打印异常【" + e.getMessage() + "】");
                    }*/
                }
                if(orderInfo.getPay_status() == Integer.parseInt(Dict.payStatus.item_2.getItem())) {
                    FormIdsEntity formIdsEntity = formIdsService.getFormIdsByMerchOrderSn(orderInfo.getMerchOrderSn());
                    if (formIdsEntity == null) {
                        // 保存form_id，已废弃_2020-1-10
                        // formIdsService.save(orderInfo.getUser_id(), orderInfo.getPay_id(), 1, orderInfo.getMerchOrderSn());
                    } else {
                        FormIdsEntity formIds = new FormIdsEntity();
                        formIds.setMerchOrderSn(orderInfo.getMerchOrderSn());
                        formIds.setFormId(orderInfo.getPay_id());
                        formIds.setId(formIdsEntity.getId());
                        formIds.setValidNum(formIdsEntity.getValidNum() + 1);
                        formIdsService.releaseFormIds(formIds);
                    }
                }

                if(!orderInfo.getOrderBizType().equalsIgnoreCase(Dict.orderBizType.item_11.getItem())) {
                    CusPayDataOpenVo cusPayDataOpen = cusPayDataOpenMapper.queryObjectByOrderNo(orderInfo.getOrder_sn());
                    if (cusPayDataOpen != null) {
                        cusPayDataOpen.setInitalResponse(reponseStr);
                        cusPayDataOpen.setPayTransactionId(transaction_id);
                        cusPayDataOpen.setTotalAmount(new BigDecimal(total_fee).divide(Constant.ONE_HUNDRED));
                        cusPayDataOpen.setVerDept(Dict.verDept.item_3.getItem());
                        cusPayDataOpen.setPayType(Dict.payType.item_1.getItem());
                        cusPayDataOpen.setCurrency(Constant.CURRENCY_142);
                        cusPayDataOpen.setTradingTime(time_end);
                        cusPayDataOpen.setModTime(new Date());
                        cusPayDataOpenMapper.update(cusPayDataOpen);
                    }
                }
            }
        }
    }


   /* *//**
     * 退款
     * @param
     *//*
    @Transactional
    public void refund(OrderVo orderInfo,WechatRefundApiResult result,String reason) {
        boolean needUpdateStock = true;
        if (orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_300.getItem())) {
            orderInfo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_402.getItem()));
        } else if (orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_301.getItem())) {
            orderInfo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_402.getItem()));
        } else if (orderInfo.getOrder_status() == Integer.parseInt(Dict.orderStatus.item_201.getItem())) {
            orderInfo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_401.getItem()));
        } else {
            orderInfo.setOrder_status(Integer.parseInt(Dict.orderStatus.item_101.getItem()));
        }
        orderInfo.setPay_status(Integer.parseInt(Dict.payStatus.item_4.getItem()));
        // 判断是否有优惠券
        UserCouponVo couponVo = apiUserCouponMapper.queryByOrderId(orderInfo.getId());
        if (null != couponVo) {
            apiUserCouponMapper.cancelOrder(couponVo);
        }
        orderService.update(orderInfo);

        MallOrderRefund mallOrderRefund = mallOrderRefundMapper.queryObjectByOrderId(orderInfo.getId()+"");

        MallOrderRefund orderRefund = new MallOrderRefund();
        orderRefund.setRefundId(result.getRefund_id());
        orderRefund.setRefundType(Integer.parseInt(Dict.RefundType.item_1.getItem()));
        orderRefund.setOutRefundNo(result.getOut_refund_no());
        orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(result.getRefund_fee())).divide(Constant.ONE_HUNDRED));
        orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));
        orderRefund.setModTime(new Date());

        if(mallOrderRefund !=null){
            orderRefund.setId(mallOrderRefund.getId());
            mallOrderRefundMapper.update(orderRefund);
        }else{
            orderRefund.setOrderId(Integer.parseInt(orderInfo.getId()+""));
            orderRefund.setUserId(Integer.parseInt(orderInfo.getUser_id()+""));
            orderRefund.setRefundReason(reason);
            orderRefund.setCreateTime(new Date());
            mallOrderRefundMapper.save(orderRefund);//退款记录
        }

        if (!needUpdateStock) {
            return;
        }
        // 更新库存
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("order_id", orderInfo.getId());
        List<OrderGoodsVo> orderGoodsVoList = apiOrderGoodsMapper.queryList(map);
        for (OrderGoodsVo orderGoodsEntity : orderGoodsVoList) {
            ProductStoreRelaVo storeRelaEntity = apiProductStoreRelaMapper.queryByStoreIdProductId(Long.valueOf(orderInfo.getStore_id()), Long.valueOf(orderGoodsEntity.getProduct_id()));
            if (null == storeRelaEntity || null == storeRelaEntity.getSellVolume()) {
                storeRelaEntity.setSellVolume(0);
            }
            BigDecimal sellVolume = new BigDecimal(storeRelaEntity.getSellVolume()).subtract(new BigDecimal(orderGoodsEntity.getNumber()));//销售量
            if (sellVolume.compareTo(Constant.ZERO) < 0) {
                sellVolume = Constant.ZERO;
            }
            storeRelaEntity.setSellVolume(Integer.parseInt(String.valueOf(sellVolume)));
            if (null == storeRelaEntity.getStockNum()) {
                storeRelaEntity.setStockNum(0);
            }
            storeRelaEntity.setStockNum(storeRelaEntity.getStockNum() + orderGoodsEntity.getNumber());//库存数量
            apiProductStoreRelaMapper.update(storeRelaEntity);
        }
    }*/


    @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) {
                OrderVo orderVo = new OrderVo();
                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();
                    if(mallOrderRefund != null){
                        orderRefund.setRefundTime(successTime);//退款成功时间
                        orderRefund.setOutRefundNo(refundApiResult.getOut_refund_no());
                        orderRefund.setRefundId(refundApiResult.getRefund_id());
                        orderRefund.setRefundMoney(BigDecimal.valueOf(Long.valueOf(refundApiResult.getRefund_fee())).divide(Constant.ONE_HUNDRED));
                        if (refundApiResult.getRefund_status().equalsIgnoreCase("SUCCESS")) {
                            orderVo.setPay_status(Integer.parseInt(Dict.payStatus.item_4.getItem()));
                            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_2.getItem()));
                            orderRefund.setWechatRefundStatusDes("退款成功");
                        } else if (refundApiResult.getRefund_status().equalsIgnoreCase("REFUNDCLOSE")) {
                            orderVo.setPay_status(Integer.parseInt(Dict.payStatus.item_5.getItem()));
                            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
                            orderRefund.setWechatRefundStatusDes("退款关闭");
                        } else if (refundApiResult.getRefund_status().equalsIgnoreCase("PROCESSING")) {
                            orderVo.setPay_status(Integer.parseInt(Dict.payStatus.item_3.getItem()));
                            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_5.getItem()));
                            orderRefund.setWechatRefundStatusDes("退款处理中");
                        } else if (refundApiResult.getRefund_status().equalsIgnoreCase("CHANGE")) {
                            orderVo.setPay_status(Integer.parseInt(Dict.payStatus.item_6.getItem()));
                            orderRefund.setRefundStatus(Integer.parseInt(Dict.RefundStatus.item_4.getItem()));
                            orderRefund.setWechatRefundStatusDes("退款异常");
                        }
                        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);
                    }
                }
            }
        }
    }

}
