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

import com.reyun.saas.common.constants.RoleEnumType;
import com.reyun.saas.common.exception.CustomException;
import com.reyun.saas.common.model.Constant;
import com.reyun.saas.common.restResult.ResultCode;
import com.reyun.saas.mob.openapi.domain.CollaborativeProject;
import com.reyun.saas.mob.openapi.dto.AppInputDTO;
import com.reyun.saas.mob.openapi.service.OpenApiAppService;
import com.reyun.saas.mob.user.dao.AppMapper;
import com.reyun.saas.mob.user.dao.UserMapper;
import com.reyun.saas.mob.user.domain.App;
import com.reyun.saas.mob.user.domain.User;
import com.reyun.saas.mob.user.service.AuthService;
import com.reyun.saas.mob.user.service.NoSqlService;
import com.reyun.saas.mob.util.RoleUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.zip.CRC32;

/**
 * @author: hanzepeng
 * @Date: 2022/02/11/13:37
 * @Description: openApi App业务层
 */
@Slf4j
@Service
@Transactional
public class OpenApiAppServiceImpl implements OpenApiAppService {

    @Autowired
    private AppMapper appMapper;

    @Autowired
    private AuthService authService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NoSqlService noSqlService;

    @Override
    public App create(AppInputDTO appInputDTO, CollaborativeProject project) {

        //校验oid是否存在
        String oid = appInputDTO.getOid();
        Example example = new Example(User.class);
        example.and().orEqualTo("oid", oid);
        example.and().orEqualTo("delFlag", false);
        User user = userMapper.selectOneByExample(example);
        if (user == null) {
            throw new CustomException(ResultCode.OID_NOT_EXIST);
        } else {
            //校验用户角色  通过改接口创建的app用户角色只能是主账号
            if (!RoleUtil.isSupperUser(user)) {
                throw new CustomException(ResultCode.OID_NOT_EXIST);
            }
        }
        Long rootParent = RoleUtil.getRootUserId(user);

        App app = new App();
        app.setAppName(appInputDTO.getAppName());
        app.setBid(appInputDTO.getBid());
        app.setOs(appInputDTO.getStrOS());
        app.setRootParent(rootParent);//主用户id
        app.setDelFlag(false);//删除标志
        app.setDisableFlag(false);//启用标志
        app.setCreateTime(new Date());//创建时间
        app.setCreateUser(-1L);//创建人id
        app.setCreateEmail(project.getProjectName());//创建人邮箱
        appMapper.insert(app);
        CRC32 crc32 = new CRC32();
        crc32.update(app.getBid().getBytes());
        String appkey = rootParent + "D" + Long.toHexString(crc32.getValue()) + "N" + app.getId() + "A" + Constant.OSMap.get(app.getOs());
        App app1 = new App();
        app1.setId(app.getId());
        app1.setAppkey(appkey);
        appMapper.updateByPrimaryKeySelective(app1);
        app.setAppkey(appkey);

        //同步ddb  appkey——oid.os.bid 关系
        noSqlService.putAppInfo(app, oid);
        return app;
    }

    /**
     * 根據oid查询app
     */
    @Override
    public List<App> findAppsByOid(String oid) {
        //校验oid对应的用户是否存在
        Example userExample = new Example(User.class);
        userExample.and().orEqualTo("oid", oid);
        userExample.and().orEqualTo("roleCategory", RoleEnumType.SUPER_USER.getKey());
        userExample.and().orEqualTo("delFlag", false);
        User user = userMapper.selectOneByExample(userExample);
        if (user == null || !RoleUtil.isSupperUser(user)) {
            throw new CustomException(ResultCode.OID_NOT_EXIST);
        }

        //根据用户查询app
        return authService.getAppByUser(user);
    }
}
