package com.fdkankan.platform.task;

import com.fdkankan.common.constant.Constant;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.ServerCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.common.util.PatternUtils;
import com.fdkankan.platform.goods.entity.CameraDetail;
import com.fdkankan.platform.goods.entity.CameraSpace;
import com.fdkankan.platform.goods.service.ICameraDetailService;
import com.fdkankan.platform.goods.service.ICameraSpaceService;
import com.fdkankan.platform.order.mapper.IOrderMapper;
import com.fdkankan.platform.order.service.IVirtualOrderService;
import com.fdkankan.platform.user.entity.User;
import com.fdkankan.platform.user.entity.UserIncrement;
import com.fdkankan.platform.user.service.IUserIncrementService;
import com.fdkankan.platform.user.service.IUserService;
import com.fdkankan.scene.api.dto.ScenePODTO;
import com.fdkankan.scene.api.feign.SceneUserSceneClient;
import com.fdkankan.sms.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TaskService {

    @Autowired
    private SceneUserSceneClient sceneUserSceneClient;

    @Autowired
    private ICameraSpaceService cameraSpaceService;

    @Autowired
    private ICameraDetailService cameraDetailService;

    @Autowired
    private IUserIncrementService userIncrementService;

    @Autowired
    private IVirtualOrderService virtualOrderService;

    @Autowired
    private IUserService userService;
    @Autowired
    private SmsService smsService;

    @Resource
    private IOrderMapper orderMapper;

    @Value("${upload.type}")
    private String ossType;

    public void autoDedu() {
        ResultData<List<ScenePODTO>> resultData = sceneUserSceneClient.findAllByYesterday();
        if(resultData.getCode() != ServerCode.SUCCESS.code()){
            log.error("获取场景数据出错:findAllByYesterday:{}",resultData.getMessage());
        }
        List<ScenePODTO> scenes = resultData.getData();
        for (ScenePODTO scene : scenes){
            if (scene.getSceneScheme() == 4){
                continue;
            }
            CameraDetail detailEntity = cameraDetailService.getByCameraId(scene.getCameraId());
            int amount = Integer.parseInt(detailEntity.getBalance()) - Constant.MONEY_SCENE;
            if (amount < 0){
                log.warn("余额不足，Num：" + scene.getNum());
                sceneUserSceneClient.updatePayStatus(scene.getNum(),-1);
            }else{
                sceneUserSceneClient.updatePayStatus(scene.getNum(),1);
                detailEntity.setBalance(String.valueOf(amount));
                cameraDetailService.updateById(detailEntity);
                virtualOrderService.insertVirtualOrderBigScene(scene.getCameraId(), scene.getNum(), detailEntity.getUserId(), detailEntity.getCountry());
            }
        }
    }

    public void autoUpdateOrderStatus() {
        orderMapper.autoUpdateOrderStatus();
    }

    public void maturitySpace() {
        List<CameraSpace> expiredList = cameraSpaceService.findExpiredList();
        if (expiredList != null && expiredList.size() > 0){
            UserIncrement userIncrementEntity = null;
            for (CameraSpace cameraSpaceEntity : expiredList){
                if(cameraSpaceEntity.getSpaceType() !=1 && cameraSpaceEntity.getSpaceType() !=2){
                    continue;
                }
                cameraSpaceEntity.setTbStatus(1);
                cameraSpaceService.updateById(cameraSpaceEntity);

                CameraDetail detailEntity = cameraDetailService.getByCameraId(cameraSpaceEntity.getCameraId());
                if (cameraSpaceEntity.getSpaceType() == 1){ // 处理期限容量
                    detailEntity.setCameraType(1);
                }
                detailEntity.setTotalSpace(Long.valueOf (Constant.CAMERA_BASE_SPACE_VALUE));
                cameraDetailService.updateById(detailEntity);

                //判断是否有绑定用户权益，无则封存场景
                userIncrementEntity = userIncrementService.getByCameraId(cameraSpaceEntity.getCameraId());
                if(userIncrementEntity == null){
                    if (detailEntity.getTotalSpace().compareTo(detailEntity.getUsedSpace()) == -1){
                        sceneUserSceneClient.lockBeyondSpaceScenes(detailEntity.getUsedSpace(), detailEntity.getTotalSpace(), cameraSpaceEntity.getCameraId());
                    }
                }
            }
        }
    }

    public void incrementExpire() {
        //查找所有刚过期的会员权益
        List<UserIncrement> expireData = userIncrementService.findExpireData();
        if(expireData != null && expireData.size() > 0){
            for (UserIncrement userIncrementEntity : expireData) {
                //调用接触绑定方法，并封存超过容量的场景，但是不解除绑定的相机
                userIncrementService.unbindCamera(userIncrementEntity.getUserId(), userIncrementEntity.getId(), false,null,userIncrementEntity);
                //删除已经过期的会员权益
                userIncrementEntity.setIsExpired(1);
                userIncrementService.updateById(userIncrementEntity);
            }
        }
    }

    public void incrementExpireSendSms() throws Exception {
        //查找所有即将到期的会员权益
        List<UserIncrement> expireData30 = userIncrementService.findReadyExpire(30, 0);
        List<UserIncrement> expireData15 = userIncrementService.findReadyExpire(15, 0);
        List<UserIncrement> expireData5 = userIncrementService.findReadyExpire(5, 0);
        List<UserIncrement> expireData = userIncrementService.findReadyExpire(-1, 1);

        Map<Long, Integer> userIds = new HashMap<>();
        for (UserIncrement userIncrementEntity : expireData30) {
            if(userIncrementEntity.getUserId() != null){
                userIds.put(userIncrementEntity.getUserId(), 30);
            }
        }

        for (UserIncrement userIncrementEntity : expireData15) {
            if(userIncrementEntity.getUserId() != null){
                userIds.put(userIncrementEntity.getUserId(), 15);
            }
        }

        for (UserIncrement userIncrementEntity : expireData5) {
            if(userIncrementEntity.getUserId() != null){
                userIds.put(userIncrementEntity.getUserId(), 5);
            }
        }

        for (UserIncrement userIncrementEntity : expireData) {
            if(userIncrementEntity.getUserId() != null){
                userIds.put(userIncrementEntity.getUserId(), -1);
            }
        }

        User userEntity = null;
        String cnCode = "SMS_216275556";
        String expireCode = "SMS_216425565";
        for (Long userId : userIds.keySet()) {
            userEntity = userService.getById(userId);
            if(userEntity != null){
                if (!"s3".equals(ossType)){
                    if (!PatternUtils.isPhoneNumber(userEntity.getUserName())){
                        throw new BusinessException(ErrorCode.FAILURE_CODE_3013);
                    }
                    if(userIds.get(userId) == -1){
                        smsService.sendSms(userEntity.getUserName(), "{\"time\":\"" + userIds.get(userId) + "\"}", expireCode);
                        continue;
                    }
                    smsService.sendSms(userEntity.getUserName(), "{\"time\":\"" + userIds.get(userId) + "\"}", cnCode);
                }
            }
        }
    }
}
