package com.reyun.saas.mob.user.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.reyun.saas.common.exception.CustomException;
import com.reyun.saas.common.framework.component.AwsDynamoDBComponent;
import com.reyun.saas.common.restResult.ResultCode;
import com.reyun.saas.mob.user.dao.PackageLevelMapper;
import com.reyun.saas.mob.user.dao.UserAndRoleMapper;
import com.reyun.saas.mob.user.dao.UserCoreConfigMapper;
import com.reyun.saas.mob.user.dao.UserMapper;
import com.reyun.saas.mob.user.domain.PackageLevel;
import com.reyun.saas.mob.user.domain.User;
import com.reyun.saas.mob.user.domain.UserAndRole;
import com.reyun.saas.mob.user.domain.UserCoreConfig;
import com.reyun.saas.mob.user.dto.user.UserCoreConfigDTO;
import com.reyun.saas.mob.user.service.UserCoreConfigService;
import com.reyun.saas.mob.util.RoleUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

@Slf4j
@Service
@Transactional
public class UserCoreConfigServiceImpl implements UserCoreConfigService {

    /**
     * ddb的rta白名单表明
     */
    private static final String RTA_TABLE_NAME = "yy_rta_whitelist";

    /**
     * ddb的rta白名单主键
     */
    private static final String RTA_WHITE_LIST_KEY = "oid";

    @Resource
    private UserCoreConfigMapper userCoreConfigMapper;

    @Resource
    private UserAndRoleMapper userAndRoleMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private AwsDynamoDBComponent awsDynamoDBComponent;

    @Resource
    private PackageLevelMapper packageLevelMapper;

    @Override
    public UserCoreConfigDTO findByRootParent(Long rootParent) {
        Example example = new Example(UserCoreConfig.class);
        example.and().andEqualTo("rootParent", rootParent);
        UserCoreConfig userCoreConfig = userCoreConfigMapper.selectOneByExample(example);
        if(userCoreConfig==null){
            throw new CustomException(ResultCode.USER_TO_AUDITED);
        }
        UserCoreConfigDTO outpDTO = new UserCoreConfigDTO();
        BeanUtils.copyProperties(userCoreConfig, outpDTO);
        return outpDTO;
    }


    @Override
    public void audited(UserCoreConfigDTO inputDTO) {
        Example example = new Example(UserCoreConfig.class);
        example.and().andEqualTo("rootParent", inputDTO.getRootParent());
        UserCoreConfig CoreConfig = userCoreConfigMapper.selectOneByExample(example);

        if (CoreConfig != null) {
            //该用户已审核
            throw new CustomException(ResultCode.USER_HAS_APPROVED);
        }
        UserCoreConfig userCoreConfig = new UserCoreConfig();
        BeanUtils.copyProperties(inputDTO,userCoreConfig);

        //todo 后面的创建人需要从系统中获取运营人员的id

        userCoreConfig.setCreateTime(DateUtil.now());
        userCoreConfig.setPubDate(DateUtil.today());
        DateTime date = DateUtil.date(System.currentTimeMillis() + (1000L * 60L * 60L * 24L * 365L));
        String format = DateUtil.format(date, "yyyy-MM-dd");
        userCoreConfig.setPastDate(format);

        //默认每个用户rta白名单ip数量为20个
        userCoreConfig.setRtaipNum(20);
        userCoreConfigMapper.insert(userCoreConfig);

        //todo 后续可能会根根据角色 存入用户角色关系
        UserAndRole userAndRole = new UserAndRole();
        userAndRole.setRoleId(1L);
        userAndRole.setUserId(userCoreConfig.getRootParent());
        userAndRoleMapper.insert(userAndRole);

        //修改用户状态
        User user = new User();
        user.setId(userCoreConfig.getRootParent());
        user.setStatus(1);
        userMapper.updateByPrimaryKeySelective(user);

        User mysqlUser = userMapper.selectByPrimaryKey(userCoreConfig.getRootParent());
        //todo 目前只要用户通过审核就在ddb中插入一条数据  后续可能需要根据用户的套餐 同步DDB中的RTA白名单的权限
        //todo 如果流量用尽或者超出到期时间7日后 重新审核时是否恢复之前配置的rta白名单ip
        Item item = new Item();
        item.withPrimaryKey(RTA_WHITE_LIST_KEY,mysqlUser.getOid());
        awsDynamoDBComponent.writeItem(RTA_TABLE_NAME,item);
    }


    /**
     * 根据用户查询该用户的 流量套餐/APP数量等核心信息
     * @return
     */
    @Override
    public UserCoreConfig findRootCoreConfig(User user) {

        UserCoreConfig result = new UserCoreConfig();

        //主用户id
        Long rootId = RoleUtil.getRootUserId(user);

        //获取用户核心配置
        Example example = new Example(UserCoreConfig.class);
        example.and().andEqualTo("rootParent", rootId);
        result = userCoreConfigMapper.selectOneByExample(example);
        if(result==null){
            throw new CustomException(ResultCode.USER_TO_AUDITED);
        }

        //获取用户套餐
        PackageLevel packageLevel  = packageLevelMapper.selectByPrimaryKey(result.getPackageLevelId());

        //查询流量上限和app数量   如果UserCoreConfig的TrackFlow为0   查询套餐详情  如果不为零以UserCoreConfig的TrackFlow为主  appNum同理
        Long trackFlow = result.getTrackFlow().equals(0L)?packageLevel.getTrackFlow(): result.getTrackFlow();
        Integer appNum  = result.getAppNum().equals(0)?packageLevel.getAppNum():result.getAppNum();

        result.setTrackFlow(trackFlow);
        result.setAppNum(appNum);

        return result;
    }


}
