package com.hfkj.service.rebate.impl;

import com.hfkj.common.exception.BaseException;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.dao.BsRebateMerAccountOrderMapper;
import com.hfkj.dao.BsRebatePartMerMapper;
import com.hfkj.entity.BsRebateMerAccount;
import com.hfkj.entity.BsRebateMerAccountOrder;
import com.hfkj.entity.BsRebateMerAccountOrderExample;
import com.hfkj.service.rebate.BsRebateMerAccountOrderServer;
import com.hfkj.service.rebate.BsRebateMerAccountService;
import com.hfkj.service.rebate.BsRebatePartMerService;
import com.hfkj.service.rebate.model.RebateMerAccountTradeObject;
import com.hfkj.sysenum.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @className: BsRebateMerAccountOrderServerImpl
 * @author: HuRui
 * @date: 2023/10/13
 **/
@Service("rebateMerAccountOrderServer")
public class BsRebateMerAccountOrderServerImpl implements BsRebateMerAccountOrderServer {

    @Resource
    private BsRebateMerAccountOrderMapper rebateMerAccountOrderMapper;
    @Resource
    private BsRebateMerAccountService rebateMerAccountService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void editData(BsRebateMerAccountOrder order) {
        if (order.getId() == null) {
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            rebateMerAccountOrderMapper.insert(order);
        } else {
            order.setUpdateTime(new Date());
            rebateMerAccountOrderMapper.updateByPrimaryKey(order);
        }
    }

    @Override
    public BsRebateMerAccountOrder getDetailByOrderNo(String orderNo) {
        BsRebateMerAccountOrderExample example = new BsRebateMerAccountOrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo).andStatusNotEqualTo(RebatePartMerStatusEnum.status0.getNumber());
        List<BsRebateMerAccountOrder> list = rebateMerAccountOrderMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void paySuccess(String orderNo, String paySerialNo) {
        String lockKey = "REBATE_ORDER_"+orderNo;
        try {
            // 占坑锁
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(lockKey, null);
            if(lock) {
                BsRebateMerAccountOrder accountOrder = getDetailByOrderNo(orderNo);
                if (accountOrder != null && accountOrder.getStatus().equals(RebateMerAccountOrderStatus.status1.getNumber()))  {
                    accountOrder.setPaySerialNo(paySerialNo);
                    accountOrder.setPayTime(new Date());
                    accountOrder.setStatus(RebateMerAccountOrderStatus.status2.getNumber());
                    editData(accountOrder);

                    RebateMerAccountTradeObject accountTradeObject = new RebateMerAccountTradeObject();
                    accountTradeObject.setTradeObjectType(RebateMerAccountObjectTypeEnum.type1);
                    accountTradeObject.setTradeObjectId(accountOrder.getId());
                    accountTradeObject.setTradeObjectContent(Objects.requireNonNull(TradeOrderPayModeEnum.getNameByCode(accountOrder.getPayType())).getName()+"充值：" + accountOrder.getTradePrice() + "元");
                    rebateMerAccountService.income(accountOrder.getAccountNumber(),accountOrder.getTradePrice(),accountTradeObject);
                }
            } else {
                // 加锁失败，重试
                Thread.sleep(100);
                paySuccess(orderNo, paySerialNo);
            }

        } catch (BaseException baseException) {
            redisTemplate.delete(lockKey);
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, baseException.getErrorMsg());

        } catch (Exception e) {
            redisTemplate.delete(lockKey);
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "交易失败！未知错误");
        }

    }

    @Override
    public List<BsRebateMerAccountOrder> getOrderList(Map<String, Object> param) {
        BsRebateMerAccountOrderExample example = new BsRebateMerAccountOrderExample();
        BsRebateMerAccountOrderExample.Criteria criteria = example.createCriteria().andStatusNotEqualTo(RebatePartMerStatusEnum.status0.getNumber());

        if (MapUtils.getLong(param, "accountNumber") != null) {
            criteria.andAccountNumberEqualTo(MapUtils.getLong(param, "accountNumber"));
        }

        if (MapUtils.getInteger(param, "orderType") != null) {
            criteria.andOrderTypeEqualTo(MapUtils.getInteger(param, "orderType"));
        }

        if (MapUtils.getInteger(param, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(param, "status"));
        }

        example.setOrderByClause("create_time desc");
        return rebateMerAccountOrderMapper.selectByExample(example);
    }
}
