package com.fdkankan.ucenter.pay.strategy.impl;

import com.fdkankan.ucenter.entity.*;
import com.fdkankan.ucenter.pay.strategy.OrderStrategy;
import com.fdkankan.ucenter.service.*;
import com.fdkankan.ucenter.util.DateUserUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Log4j2
@Component
public class IncrementOrderImpl implements OrderStrategy {
    @Autowired
    private IIncrementOrderService incrementOrderService;
    @Autowired
    private IUserIncrementService userIncrementService;
    @Autowired
    private IUserService userService;
    @Autowired
    ISceneProService sceneProService;
    @Autowired
    ICameraDetailService cameraDetailService;
    @Autowired
    IIncrementTypeService incrementTypeService;
    @Autowired
    IAgentNewLogService agentNewLogService;
    @Autowired
    IIncrementAutoOrderService incrementAutoOrderService;

    @Override
    public void handleOrder(String orderSn, String tradeNo, String openId, int paymentTypeName, Long incrementId) throws Exception {

        IncrementOrder responseIncrementOrder = incrementOrderService.getByOrderSnNoPay(orderSn);
        if (responseIncrementOrder == null) {
            log.error("找不到订单：" + orderSn);
            throw new Exception("找不到订单，out_trade_no错误");
        }
        IncrementAutoOrder incrementAutoOrder = null;
        if(responseIncrementOrder.getAutoOrderId() != null){
            incrementAutoOrder = incrementAutoOrderService.getById(responseIncrementOrder.getAutoOrderId());
            if(incrementAutoOrder != null && incrementAutoOrder.getUserIncrementId() !=null){
                responseIncrementOrder.setIncrementId(incrementAutoOrder.getUserIncrementId());
            }
        }
        // 更新增值权益订单
        boolean result = incrementOrderService.paySuccessIncrementOrder(orderSn, tradeNo, paymentTypeName);
        if (!result){
            log.error("更新增值权益订单失败");
            throw new Exception("更新增值权益订单失败");
        }
        UserIncrement userIncrementEntity = null;
        IncrementType incrementType = incrementTypeService.getById(responseIncrementOrder.getIncrementType());
        if(incrementType == null){
            throw new Exception("更新增值权益订单失败");
        }
        Boolean flag = agentNewLogService.addByOrder(responseIncrementOrder);

        Integer expired = 0;
        Date date =  new Date();
        if(responseIncrementOrder.getIncrementId() == null){
            //新的增值权益套餐方案
            date = DateUserUtil.getDateTime(new Date(),incrementType,responseIncrementOrder.getMonthQy()).toDate();

            if(responseIncrementOrder.getCount() > 0){
                for(int i = 0, len = responseIncrementOrder.getCount(); i < len; i++){
                    userIncrementEntity = new UserIncrement();
                    userIncrementEntity.setKeyWord(UUID.randomUUID().toString().replace("-", ""));
                    userIncrementEntity.setUserId(responseIncrementOrder.getUserId());
                    userIncrementEntity.setOrderSn(orderSn);
                    userIncrementEntity.setIncrementStartTime(DateUserUtil.getDate(new Date()));
                    userIncrementEntity.setIncrementEndTime(DateUserUtil.getDate(date));
                    userIncrementEntity.setIsExpired(expired);
                    userIncrementEntity.setIncrementTypeId(responseIncrementOrder.getIncrementType());
                    userIncrementEntity.setMemberLevels(responseIncrementOrder.getMemberLevels());
                    if(incrementAutoOrder!= null){
                        userIncrementEntity.setSubscriptionOrder(incrementAutoOrder.getSubscriptionId());
                    }
                    userIncrementService.save(userIncrementEntity);
                    incrementAutoOrderService.setIncrementId(incrementAutoOrder,userIncrementEntity.getId());
                }
            }
        }else {
            userIncrementEntity = userIncrementService.getById(responseIncrementOrder.getIncrementId());
            date = DateUserUtil.getDateTime(DateUserUtil.getDate(userIncrementEntity.getIncrementEndTime()),incrementType,responseIncrementOrder.getMonthQy()).toDate();

            userIncrementEntity.setIncrementEndTime(DateUserUtil.getDate(date));
            userIncrementEntity.setOrderSn(userIncrementEntity.getOrderSn() + "," + orderSn);
            userIncrementEntity.setUpdateTime(DateUserUtil.getDate(new Date()));
            userIncrementEntity.setIsExpired(expired);
            if(incrementAutoOrder!= null){
                userIncrementEntity.setSubscriptionOrder(incrementAutoOrder.getSubscriptionId());
            }
            userIncrementEntity.setMonthQy(responseIncrementOrder.getMonthQy());
            userIncrementService.updateById(userIncrementEntity);

            if(userIncrementEntity.getAgentId() != null && !flag){
                agentNewLogService.addByUserIncrement(userIncrementEntity,orderSn);
            }

            //解封所有场景
            if(userIncrementEntity.getUserId() != null && userIncrementEntity.getCameraId() != null){
                CameraDetail cameraDetail = cameraDetailService.getByCameraId(userIncrementEntity.getCameraId());
                sceneProService.lockOrUnLockBySpace(cameraDetail, userIncrementEntity.getCameraId());
            }
        }

        //增加用户下载次数
        if(userIncrementEntity != null && userIncrementEntity.getUserId()!=null){
            User userEntity = userService.getById(userIncrementEntity.getUserId());
            if(userEntity != null && incrementType.getDownloadNum() >0){
                userEntity.setDownloadNumTotal(userEntity.getDownloadNumTotal() + (responseIncrementOrder.getMonthQy() == null?1:responseIncrementOrder.getMonthQy()) * responseIncrementOrder.getCount() * incrementType.getDownloadNum() );
                userService.updateById(userEntity);
            }
        }
    }


    @Override
    public String getType() {
        return "increment";
    }



}
