package com.fdkankan.ucenter.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.sms.SmsService;
import com.fdkankan.ucenter.common.PageInfo;
import com.fdkankan.common.util.DateUtil;
import com.fdkankan.ucenter.common.ResultData;
import com.fdkankan.ucenter.common.constants.NacosProperty;
import com.fdkankan.ucenter.constant.CameraConstant;
import com.fdkankan.ucenter.constant.LoginConstant;
import com.fdkankan.ucenter.entity.*;
import com.fdkankan.ucenter.httpClient.client.PayClient;
import com.fdkankan.ucenter.mapper.IUserIncrementMapper;
import com.fdkankan.ucenter.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.ucenter.util.DateUserUtil;
import com.fdkankan.ucenter.vo.request.IncrementParam;
import com.fdkankan.ucenter.vo.response.UserIncrementVo;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户增值权益表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-07-04
 */
@Service
public class UserIncrementServiceImpl extends ServiceImpl<IUserIncrementMapper, UserIncrement> implements IUserIncrementService {

    @Autowired
    ICameraService cameraService;
    @Autowired
    IUserService userService;
    @Autowired
    ICameraDetailService cameraDetailService;
    @Autowired
    ISceneProService sceneProService;
    @Autowired
    SmsService smsService;
    @Autowired
    IMailTemplateService mailTemplateService;
    @Autowired
    ICameraIncrementLogService cameraIncrementLogService;
    @Autowired
    IExceedSpaceSceneService exceedSpaceSceneService;
    @Autowired
    IIncrementTypeService incrementTypeService;
    @Autowired
    ICameraTypeService cameraTypeService;

    @Override
    public Long getCountByUserId(Long userId, int type) {
        LambdaQueryWrapper<UserIncrement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserIncrement::getUserId,userId);
        if(type == 0){
            wrapper.eq(UserIncrement::getIsExpired,0);
        }else if(type == 1){
            wrapper.isNotNull(UserIncrement::getCameraId);
        }
        return this.count(wrapper);
    }

    @Override
    public PageInfo pageList(IncrementParam param) {
        Page<UserIncrementVo> pageVo = new Page<>(param.getPageNum(), param.getPageSize());
        User user = userService.getByUserName(param.getUserName());
        List<Long> cameraIdList = null;
        if(StrUtil.isNotEmpty(param.getSnCode()) && StrUtil.isNotEmpty(param.getSnCode().trim())){
            List<Camera> cameraEntityList = cameraService.getCameraLikeSnCode(param.getSnCode().trim());
            if(cameraEntityList == null || cameraEntityList.size()<=0){
                return PageInfo.PageInfo(pageVo);
            }
            cameraIdList = cameraEntityList.stream().map(Camera::getId)
                    .collect(Collectors.toList());
        }
        Page<UserIncrement> page = new Page<>(param.getPageNum(), param.getPageSize());
        LambdaQueryWrapper<UserIncrement> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserIncrement::getUserId,user.getId());
        queryWrapper.and(i ->i.eq(UserIncrement::getIsExpired,0).or().isNotNull(UserIncrement::getCameraId));
        if(cameraIdList!=null ){
            queryWrapper.in(UserIncrement::getCameraId,cameraIdList);
        }
        queryWrapper.orderByDesc(UserIncrement::getId);
        Page<UserIncrement> pageEntity = this.page(page, queryWrapper);

        List<UserIncrementVo> responseList = convert(pageEntity.getRecords());
        pageVo.setTotal(pageEntity.getTotal());
        pageVo.setRecords(responseList);
        return PageInfo.PageInfo(pageVo);
    }


    public List<UserIncrementVo> convert(List<UserIncrement> list) {
        List<UserIncrementVo> result = new ArrayList<>();
        if(list == null){
            return result;
        }
        UserIncrementVo responseUserIncrement = new UserIncrementVo();
        for (UserIncrement userIncrementEntity : list) {
            responseUserIncrement = new UserIncrementVo();
            BeanUtils.copyProperties(userIncrementEntity, responseUserIncrement);
            if(responseUserIncrement.getCameraId() != null){
                Camera cameraEntity = cameraService.getById(responseUserIncrement.getCameraId());
                responseUserIncrement.setSnCode(cameraEntity != null ? cameraEntity.getSnCode() : null);
            }
            responseUserIncrement.setIsExpire(userIncrementEntity.getIsExpired() != 0);
            result.add(responseUserIncrement);
        }
        return result;
    }

    @Override
    public HashMap<Long, UserIncrement> findByCameraIds(List<Long> cameraIdList) {
        HashMap<Long, UserIncrement> map = new HashMap<>();
        LambdaQueryWrapper<UserIncrement> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserIncrement::getCameraId,cameraIdList);
        List<UserIncrement> list = this.list(wrapper);
        list.forEach(entity -> map.put(entity.getCameraId(),entity));
        return map;
    }

    @Override
    public Long getValidCountByCameraId(Long cameraId) {
        LambdaQueryWrapper<UserIncrement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserIncrement::getCameraId,cameraId);
        wrapper.gt(UserIncrement::getIncrementEndTime, DateUtil.date2String(new Date(),DateUtil.DEFAULT_DATE_FORMAT));
        return this.count(wrapper);
    }

    @Override
    public void unbindCamera(List<Long> cameraIds) {
        if(cameraIds.size() >0){
            LambdaUpdateWrapper<UserIncrement> wrapper = new LambdaUpdateWrapper<>();
            wrapper.in(UserIncrement::getCameraId,cameraIds);
            if("local".equals(NacosProperty.uploadType)){
                this.remove(wrapper);
            }else {
                wrapper.set(UserIncrement::getCameraId,null);
                this.update(wrapper);
            }
        }

    }


    @Override
    public UserIncrement getByCameraId(Long cameraId) {
        LambdaQueryWrapper<UserIncrement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserIncrement::getCameraId,cameraId);
        List<UserIncrement> list = this.list(wrapper);
        if(list !=null && list.size() >0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public void bindCamera(IncrementParam param) {
        if(param.getId() == null || param.getSnCode() == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        UserIncrement userIncrement = this.getById(param.getId());
        if(userIncrement == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3030, LoginConstant.FAILURE_MSG_3030);
        }
        if(userIncrement.getIsExpired() == 1 || DateUserUtil.getDate(userIncrement.getIncrementEndTime()).getTime() <= new Date().getTime() ){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3030, LoginConstant.FAILURE_MSG_3030);
        }
        Camera cameraEntity = cameraService.getBySnCode(param.getSnCode());
        if(cameraEntity == null){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6003, CameraConstant.FAILURE_MSG_6003);
        }
        UserIncrement byCameraId = this.getByCameraId(cameraEntity.getId());
        if(byCameraId != null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3032, LoginConstant.FAILURE_MSG_3032);
        }
        CameraDetail cameraDetailEntity = cameraDetailService.getByCameraId(cameraEntity.getId());
        if(cameraDetailEntity == null){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6003, CameraConstant.FAILURE_MSG_6003);
        }
        User user = userService.getByUserName(param.getUserName());
        if(user == null){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6003, CameraConstant.FAILURE_MSG_6003);
        }
        if(cameraDetailEntity.getUserId() == null || !cameraDetailEntity.getUserId().equals(user.getId())){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6005, CameraConstant.FAILURE_MSG_6005);
        }
        userIncrement.setCameraId(cameraEntity.getId());
        userIncrement.setUpdateTime(DateUserUtil.getDate(new Date()));
        this.updateById(userIncrement);
        cameraIncrementLogService.saveLog(cameraEntity.getId(),userIncrement.getId(),user.getId(),0);
        sceneProService.lockOrUnLockBySpace(cameraDetailEntity,cameraEntity.getId());
    }

    @Override
    public void unbindCamera(IncrementParam param) {
        if(param.getId() == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3001, LoginConstant.FAILURE_MSG_3001);
        }
        UserIncrement userIncrement = this.getById(param.getId());
        if(userIncrement == null){
            throw new BusinessException(LoginConstant.FAILURE_CODE_3030, LoginConstant.FAILURE_MSG_3030);
        }
        if(userIncrement.getCameraId() == null){
            return;
        }
        CameraDetail cameraDetail = cameraDetailService.getByCameraId(userIncrement.getCameraId());
        if(cameraDetail == null){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6003, CameraConstant.FAILURE_MSG_6003);
        }
        User user = userService.getByUserName(param.getUserName());
        if(user == null){
            throw new BusinessException(CameraConstant.FAILURE_CODE_6003, CameraConstant.FAILURE_MSG_6003);
        }
        cameraIncrementLogService.saveLog(userIncrement.getCameraId(),userIncrement.getId(),user.getId(),1);
        LambdaUpdateWrapper<UserIncrement> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserIncrement::getId,param.getId());
        wrapper.set(UserIncrement::getCameraId,null);
        this.update(wrapper);
        CameraType cameraType = cameraTypeService.getByCameraType(cameraDetail.getType());
        if(!"aws".equals(NacosProperty.uploadType) && cameraType.getIsLaser() == 0){
            sceneProService.lockOrUnLockBySpace(cameraDetail,cameraDetail.getCameraId());
        }
        if("aws".equals(NacosProperty.uploadType) ){
            sceneProService.lockOrUnLockBySpace(cameraDetail,cameraDetail.getCameraId());     //封存场景
        }
    }

    @Override
    public void incrementExpire() {
        //查找所有刚过期的会员权益
        LambdaQueryWrapper<UserIncrement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserIncrement::getIsExpired,0);
        wrapper.lt(UserIncrement::getIncrementEndTime,DateUserUtil.getDate(new Date()));
        List<UserIncrement> list = this.list(wrapper);
        lockScene(list);
    }

    public void lockScene(List<UserIncrement> list){
        for (UserIncrement userIncrement : list) {
            if(DateUserUtil.getDate(userIncrement.getIncrementEndTime()).getTime() > new Date().getTime()){
                userIncrement.setIsExpired(0);
            }else {
                userIncrement.setIsExpired(1);
            }
            userIncrement.setUpdateTime(null);
            this.updateById(userIncrement);
            //解除相机权益
            if(userIncrement.getCameraId() != null){
                CameraDetail cameraDetail = cameraDetailService.getByCameraId(userIncrement.getCameraId());
                if(cameraDetail == null){
                    continue;
                }
                CameraType cameraType = cameraTypeService.getByCameraType(cameraDetail.getType());
                if(!"aws".equals(NacosProperty.uploadType) && cameraType.getIsLaser() == 0){
                    sceneProService.lockOrUnLockBySpace(cameraDetail,cameraDetail.getCameraId());
                }
                if("aws".equals(NacosProperty.uploadType) ){
                    sceneProService.lockOrUnLockBySpace(cameraDetail,cameraDetail.getCameraId());
                }
            }
        }
    }

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

        Map<Long, Integer> userIdsRP = new HashMap<>();
        Map<Long, Integer> userIdsSE = new HashMap<>();
        for (UserIncrement userIncrementEntity : expireData30) {
            if(userIncrementEntity.getUserId() != null){
                if(StringUtils.isBlank(userIncrementEntity.getMemberLevels() ) ||  "PR".equals(userIncrementEntity.getMemberLevels())){
                    userIdsRP.put(userIncrementEntity.getUserId(), 30);
                }
            }
        }

        for (UserIncrement userIncrementEntity : expireData15) {
            if(userIncrementEntity.getUserId() != null){
                if(StringUtils.isBlank(userIncrementEntity.getMemberLevels() ) ||"PR".equals(userIncrementEntity.getMemberLevels())){
                    userIdsRP.put(userIncrementEntity.getUserId(), 15);
                }
            }
        }

        for (UserIncrement userIncrementEntity : expireData5) {
            if(userIncrementEntity.getUserId() != null){
                if(StringUtils.isBlank(userIncrementEntity.getMemberLevels() ) ||"PR".equals(userIncrementEntity.getMemberLevels())){
                    userIdsRP.put(userIncrementEntity.getUserId(), 5);
                }
                if("SE".equals(userIncrementEntity.getMemberLevels())){
                    userIdsSE.put(userIncrementEntity.getUserId(), 5);
                }
            }
        }
        for (UserIncrement userIncrementEntity : expireData3) {
            if(userIncrementEntity.getUserId() != null){
                if("SE".equals(userIncrementEntity.getMemberLevels())){
                    userIdsSE.put(userIncrementEntity.getUserId(), 3);
                }
            }
        }
        for (UserIncrement userIncrementEntity : expireData0) {
            if(userIncrementEntity.getUserId() != null){
                if(StringUtils.isBlank(userIncrementEntity.getMemberLevels() ) ||"PR".equals(userIncrementEntity.getMemberLevels())){
                    userIdsRP.put(userIncrementEntity.getUserId(), 0);
                }
                if("SE".equals(userIncrementEntity.getMemberLevels())){
                    userIdsSE.put(userIncrementEntity.getUserId(), 0);
                }
            }
        }

        for (UserIncrement userIncrementEntity : expireData) {
            if(userIncrementEntity.getUserId() != null){
                if(StringUtils.isBlank(userIncrementEntity.getMemberLevels() ) ||"PR".equals(userIncrementEntity.getMemberLevels())){
                    userIdsRP.put(userIncrementEntity.getUserId(), -1);
                }
                if("SE".equals(userIncrementEntity.getMemberLevels())){
                    userIdsSE.put(userIncrementEntity.getUserId(), -1);
                }
            }
        }
        this.sendMsg(userIdsRP,"PR");
        this.sendMsg(userIdsSE,"SE");
    }

    @Value("${sms.template.increment-to-be-expire}")
    private String cnCode;
    @Value("${sms.template.increment-expire}")
    private String expireCode;
    private void sendMsg(Map<Long, Integer> userIds,String msgType) throws Exception {
        for (Long userId : userIds.keySet()) {
            User userEntity = userService.getById(userId);
            if(userEntity != null){
                if("oss".equals(NacosProperty.uploadType) && StringUtil.isNotBlank(userEntity.getUserName()) && StringUtils.isNumeric(userEntity.getUserName())){
                    if(userIds.get(userId) == -1){
                        smsService.sendSms(userEntity.getUserName(), "{\"time\":\"" + userIds.get(userId) + "\"}", expireCode);
                        continue;
                    }
                    smsService.sendSms(userEntity.getUserName(), "{\"time\":\"" + userIds.get(userId) + "\"}", cnCode);
                }
                if("aws".equals(NacosProperty.uploadType)  && StringUtil.isNotBlank(userEntity.getUserName())){
                    Integer days = userIds.get(userId);
                    if(days == null || days<0){
                        mailTemplateService.sendPeExMail(userEntity.getUserName(),msgType);
                        continue;
                    }
                    if(days > 0){
                        mailTemplateService.sendPeNoExMail(userEntity.getUserName(),userIds.get(userId),msgType);
                        continue;
                    }
                    mailTemplateService.sendPeTodayExMail(userEntity.getUserName(),msgType);

                }
            }
        }
    }

    @Override
    public void addByCameraAndUser(List<Long> cameraIds, Long userId) {
        this.delByCameraId(cameraIds);
        for (Long cameraId : cameraIds) {
            UserIncrement userIncrement = new UserIncrement();
            userIncrement.setKeyWord(UUID.randomUUID().toString().replace("-", ""));
            userIncrement.setIsExpired(0);
            userIncrement.setIncrementStartTime(DateUserUtil.getDate(new Date()));
            userIncrement.setCameraId(cameraId);
            userIncrement.setIncrementTypeId(1);
            userIncrement.setIncrementEndTime("2199-01-01 00:00:00");
            userIncrement.setUserId(userId);
            this.save(userIncrement);
        }
    }

    @Override
    public void delByCameraId(List<Long> cameraIds) {
        if(cameraIds.size() >0){
            LambdaQueryWrapper<UserIncrement> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(UserIncrement::getCameraId,cameraIds);
            this.remove(wrapper);
        }
    }

    @Override
    public HashMap<String, List<Long>> getByOrderSnList(Set<String> orderSns) {
        HashMap<String, List<Long>> map = new HashMap<>();
        if(orderSns.size() >0){
            for (String orderSn : orderSns) {
                LambdaQueryWrapper<UserIncrement> wrapper = new LambdaQueryWrapper<>();
                wrapper.like(UserIncrement::getOrderSn,orderSn);
                List<UserIncrement> list = this.list(wrapper);

                for (UserIncrement userIncrement : list) {
                    map.computeIfAbsent(orderSn, k -> new ArrayList<>());
                    map.get(orderSn).add(userIncrement.getId());
                }
            }

        }

        return map;
    }

    @Override
    public List<UserIncrement> getByAutoOrderSn(String orderSn) {
        LambdaQueryWrapper<UserIncrement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserIncrement::getSubscriptionOrder,orderSn);
        wrapper.orderByAsc(UserIncrement::getCreateTime);
        return this.list(wrapper);
    }

    /**
     * 续费1单位
     */
    @Override
    public void delay(UserIncrement increment) {
        LambdaUpdateWrapper<UserIncrement> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserIncrement::getId,increment.getId());
        wrapper.set(UserIncrement::getIsExpired,0);

        IncrementType incrementType = incrementTypeService.getById(increment.getIncrementTypeId());
        Date date = DateUserUtil.getDateTime(new Date(),incrementType,1).toDate();
        wrapper.set(UserIncrement::getIncrementEndTime,date);
        this.update(wrapper);
    }

    @Override
    public void cancelSubscriptions(UserIncrement increment) {
        LambdaUpdateWrapper<UserIncrement> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserIncrement::getId,increment.getId());
        wrapper.set(UserIncrement::getSubscriptionOrder,null);
        this.update(wrapper);
    }

    @Autowired
    PayClient payClient;
    @Autowired
    IIncrementAutoOrderService incrementAutoOrderService;

    @Override
    public void cancelSubscription(Long incrementId) {
        UserIncrement userIncrement = this.getById(incrementId);
        if(userIncrement == null){
            throw new BusinessException(ErrorCode.VALUE_NOT_EXIST);
        }
        ResultData resultData = payClient.cancelSubscription(userIncrement.getSubscriptionOrder());
        if(resultData.getCode() !=200){
            throw new BusinessException(resultData.getCode(),resultData.getMessage());
        }
        this.cancelSubscriptions(userIncrement);
        incrementAutoOrderService.delByIncrementId(incrementId);
    }
}
