package com.hai.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.utils.DateUtil;
import com.hai.common.utils.IDGenerator;
import com.hai.config.CommonSysConst;
import com.hai.config.RechargeConfig;

import com.hai.dao.OutRechargeOrderMapper;
import com.hai.entity.*;

import com.hai.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("apiOpenService")
public class ApiOpenServiceImpl implements ApiOpenService {

    @Resource
    private ApiOrderRecordService apiOrderRecordService;

    @Resource
    private ApiMerchantsService apiMerchantsService;

    @Resource
    private ApiProductService apiProductService;

    @Resource
    private ApiAmountRecordService apiAmountRecordService;

    @Resource
    private OutRechargeOrderMapper outRechargeOrderMapper;

    @Resource
    private OutRechargeChildOrderService outRechargeChildOrderService;

    @Resource
    private BsRequestRecordService bsRequestRecordService;


    @Override
    @Transactional(rollbackFor=Exception.class,isolation = Isolation.SERIALIZABLE,propagation= Propagation.REQUIRES_NEW)
    public void createOrder(JSONObject object , ApiMerchants apiMerchants , ApiProductConfig productConfig) throws  Exception {

        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("sourceOrderNo" , object.getString("orderNo"));

        // 查询是否用重复订单
        ApiOrderRecord apiOrderRecord = apiOrderRecordService.queryOrderResult(orderMap);


        if (apiOrderRecord != null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.ORDER_ALREADY_EXISTS);
        }

        ApiProduct apiProduct = apiProductService.findById(productConfig.getProductId());


        // 当前账号余额是否可以充值当前金额
        if (apiMerchants.getAmounts().compareTo(productConfig.getDiscountPrice()) < 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.INSUFFICIENT_BALANCE);
        }

        // 插入金额记录
        // 变更前金额
        BigDecimal beforeAmount = apiMerchants.getAmounts();
        // 计算金额
        apiMerchants.setAmounts(apiMerchants.getAmounts().subtract(productConfig.getDiscountPrice()));
        // 变更后金额
        BigDecimal afterAmount = apiMerchants.getAmounts();

        apiMerchantsService.updateApiMerchants(apiMerchants);

        ApiAmountRecord apiAmountRecord = new ApiAmountRecord();

        apiAmountRecord.setCreateTime(new Date());
        apiAmountRecord.setUpdateTime(new Date());
        apiAmountRecord.setMchId(apiMerchants.getMchId());

        apiAmountRecord.setStatus(100);
        apiAmountRecord.setAmount(productConfig.getDiscountPrice());
        apiAmountRecord.setAfterAmount(afterAmount);
        apiAmountRecord.setBeforeAmount(beforeAmount);
        apiAmountRecord.setAmountType(2);
        apiAmountRecord.setSourceType(3);
        apiAmountRecord.setSourceOrderNo(object.getString("orderNo"));
        apiAmountRecord.setSourceId(apiProduct.getId());
        apiAmountRecord.setSourceContent(apiMerchants.getMerchantName() + "|" + object.getString("mobile") + "充值" + apiProduct.getRechargePrice() + "｜扣款" + productConfig.getDiscountPrice());

        apiAmountRecordService.insertAmountRecord(apiAmountRecord);

        // 充值订单
        OutRechargeOrder outRechargeOrder = new OutRechargeOrder();
        outRechargeOrder.setPayStatus(102);
        outRechargeOrder.setRechargeStatus(204);
        outRechargeOrder.setOrderNo("RCG" + DateUtil.date2String(new Date(), "yyyyMMddHHmmss") + IDGenerator.nextId(5));
        outRechargeOrder.setPaySerialNo("22" + DateUtil.date2String(new Date(), "yyyyMMddHHmmss") + IDGenerator.nextId(5));
        outRechargeOrder.setRechargePrice(apiProduct.getRechargePrice());
        outRechargeOrder.setRechargeType(apiProduct.getPhoneRechargeType());
        outRechargeOrder.setOrderPrice(productConfig.getDiscountPrice());
        outRechargeOrder.setPayPrice(productConfig.getDiscountPrice());
        outRechargeOrder.setRechargeContent(object.getString("mobile"));
        outRechargeOrder.setPayTime(new Date());
        outRechargeOrder.setUserName(apiMerchants.getUserName());
        outRechargeOrder.setUserPhone(apiMerchants.getPhone());
        outRechargeOrder.setPayType(6);
        outRechargeOrder.setCompanyId(6666L);
        outRechargeOrder.setType(1);
        outRechargeOrder.setCreateTimed(new Date());
        outRechargeOrder.setOperatorName(apiProduct.getOperatorName());
        outRechargeOrder.setOperatorType(apiProduct.getOperatorType());
        outRechargeOrder.setGoodsId(apiProduct.getId());
        outRechargeOrder.setMerchId(apiMerchants.getMchId());
        outRechargeOrder.setUserId(apiMerchants.getId());

        outRechargeOrderMapper.insert(outRechargeOrder);
        pollRequest(outRechargeOrder);

        // 插入订单记录
        ApiOrderRecord apiOrderRecordPost = new ApiOrderRecord();
        apiOrderRecordPost.setStatus(103);
        apiOrderRecordPost.setOrderNo(outRechargeOrder.getOrderNo());
        apiOrderRecordPost.setSourceOrderNo(apiAmountRecord.getSourceOrderNo());
        apiOrderRecordPost.setCreateTime(new Date());
        apiOrderRecordPost.setMchId(apiMerchants.getMchId());
        apiOrderRecordPost.setOrderId(outRechargeOrder.getId());
        apiOrderRecordPost.setGoodsId(productConfig.getId().toString());
        apiOrderRecordPost.setNotifyUrl(object.getString("notifyUrl"));
        apiOrderRecordPost.setUpdateTime(new Date());

        apiOrderRecordService.insertOrderRecord(apiOrderRecordPost);
    }

    private void pollRequest(OutRechargeOrder outRechargeOrder) throws Exception {

        // 查询充值产品
        ApiProduct apiProduct = apiProductService.findById(outRechargeOrder.getGoodsId());

        // 查询充值子订单
        Map<String, Object> childOrderMap = new HashMap<>();

        childOrderMap.put("parent_order_id", outRechargeOrder.getId());
        childOrderMap.put("status", 102);

        List<OutRechargeChildOrder> childOrderList = outRechargeChildOrderService.getListRechargeChildOrder(childOrderMap);

        OutRechargeChildOrder childOrder = new OutRechargeChildOrder();

        // 1:尖椒 2：龙阅 3：畅停
        int type = 0;
        int rechargePlatformType = 0;

        // 判断子订单是否存在充值中订单
        if (childOrderList.size() > 0) {
            childOrder = childOrderList.get(0);
            childOrder.setStatus(103);
            childOrder.setUpdateTime(new Date());
            outRechargeChildOrderService.updateOrder(childOrder);
            type = childOrder.getRechargePlatform();

        } else {
            // 查询充值子订单
            Map<String, Object> childOrderMap103 = new HashMap<>();

            childOrderMap.put("parent_order_id", outRechargeOrder.getId());
            childOrderMap.put("status", 103);

            List<OutRechargeChildOrder> childOrderList103 = outRechargeChildOrderService.getListRechargeChildOrder(childOrderMap103);
            if (childOrderList103.size() > 0) {
                type = childOrderList103.get(0).getRechargePlatform();
            }
        }

        if (type == 2) {
            type = 1;
        } else {
            type++;
        }


        JSONObject object = new JSONObject();

        String orderNo = "CZ" + DateUtil.date2String(new Date(), "yyyyMMddHHmmss") + IDGenerator.nextId(5);

        String[] rechargePlatform = apiProduct.getRechargePlatform().split("-");

        for (String s : rechargePlatform) {
            // 尖椒充值
            if (s.equals("1") && type == 1) {
                object.put("out_order_id", orderNo);
                object.put("amount", apiProduct.getRechargePrice());
                object.put("mobile", outRechargeOrder.getRechargeContent());
                object.put("notifyUrl", CommonSysConst.getSysConfig().getJjNotifyUrl());
                if (apiProduct.getRechargeType() == 1) {
                    object.put("is_fast", 1);
                }
                JSONObject returnObject = RechargeConfig.rechargeOrderByJj(object);
                object.put("return_content", returnObject);
                if (returnObject != null && returnObject.getLong("code") == 200) {
                    childOrder.setStatus(102);
                } else {
                    childOrder.setStatus(103);
                }
                rechargePlatformType = 1;
                break;
            }
            if (s.equals("2") && type == 2) {
                object.put("out_trade_num", orderNo);
                object.put("product_id", apiProduct.getProductId());
                object.put("mobile", outRechargeOrder.getRechargeContent());
                object.put("notifyUrl", CommonSysConst.getSysConfig().getLyNotifyUrl());
                JSONObject returnObject = RechargeConfig.rechargeOrderByLy(object);
                object.put("return_content", returnObject);
                if (returnObject != null && returnObject.getLong("errno") == 0) {
                    childOrder.setStatus(102);
                } else {
                    childOrder.setStatus(103);
                }
                rechargePlatformType = 2;
                break;
            }
        }

        childOrder.setOrderNo(orderNo);
        childOrder.setCreateTime(new Date());
        childOrder.setParentOrderId(outRechargeOrder.getId());
        childOrder.setRechargePlatform(rechargePlatformType);
        childOrder.setUpdateTime(new Date());
        outRechargeChildOrderService.insertOrder(childOrder);

        // 创建提交记录
        BsRequestRecord requestRecord = new BsRequestRecord();
        requestRecord.setCreateTime(new Date());
        requestRecord.setUpdateTime(new Date());
        requestRecord.setOrderNo(orderNo);
        requestRecord.setRequestContent(object.toJSONString());
        requestRecord.setOperatorId(0L);
        requestRecord.setOperatorName("系统生成");
        requestRecord.setSourceId(childOrder.getId().toString());
        requestRecord.setSourceType(1);

        bsRequestRecordService.insertRequestRecord(requestRecord);

        // 判断是否充值提交成功
        if (childOrder.getStatus() == 102) {
            outRechargeOrder.setRechargeStatus(201);
        }

        if (childOrder.getStatus() == 103) {
            outRechargeOrder.setRechargeStatus(204);
        }
        outRechargeOrderMapper.updateByPrimaryKey(outRechargeOrder);

    }

}
