package com.yida.data.system.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.agent.EduAgent;
import com.yida.data.common.core.entity.system.Role;
import com.yida.data.common.core.entity.system.SystemUser;
import com.yida.data.common.core.entity.system.enums.RoleEnum;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.system.dto.AgentAdminAccountSaveDTO;
import com.yida.data.system.dto.AgentSaveDTO;
import com.yida.data.system.dto.AgentSelectPageDTO;
import com.yida.data.system.mapper.EduAgentMapper;
import com.yida.data.system.mapper.UserMapper;
import com.yida.data.system.service.EduAgentService;
import com.yida.data.system.service.IRoleService;
import com.yida.data.system.service.IUserService;
import com.yida.data.system.vo.AgentAdminAccountDetailVO;
import com.yida.data.system.vo.AgentDetailVO;
import com.yida.data.system.vo.AgentSelectPageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;

/**
 * 代理商表 Service实现
 *
 * @author ZYJ
 * @date 2021-09-26 11:19:45
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class EduAgentServiceImpl extends ServiceImpl
        <EduAgentMapper, EduAgent> implements EduAgentService {

    private final UserMapper userMapper;

    private final IRoleService roleService;

    private final IUserService userService;

    /**
     * 查询代理商列表数据
     *
     * @param agentSelectPageDTO 代理商后台列表请求类
     * @return com.yida.data.common.core.common.ResultBean<com.baomidou.mybatisplus.core.metadata.IPage < com.yida.data.system.vo.AgentSelectPageVO>>
     * @author ZYJ
     * @date 2021/9/26 11:41
     */
    @Override
    public ResultBean<IPage<AgentSelectPageVO>> listAgentPage(AgentSelectPageDTO agentSelectPageDTO) {
        IPage<AgentSelectPageVO> iPage = this.baseMapper.listAgentPage(agentSelectPageDTO.toPage(), agentSelectPageDTO);
        return ResultBean.buildSuccess(iPage);
    }

    /**
     * 保存代理商数
     *
     * @param agentSaveDTO 保存代理商请求类
     * @return com.yida.data.common.core.common.ResultBean<java.lang.String>
     * @author ZYJ
     * @date 2021/9/26 13:58
     */
    @Override
    public ResultBean<String> saveAgent(AgentSaveDTO agentSaveDTO) {
        EduAgent eduAgent = new EduAgent();
        BeanUtils.copyProperties(agentSaveDTO, eduAgent);
        // 新增
        if (!Optional.ofNullable(Objects.requireNonNull(eduAgent).getId()).isPresent()) {
            // 设置新增数据
            eduAgent.setCreateDate(LocalDateTime.now());
            eduAgent.setCreateId(Objects.requireNonNull(FebsUtil.getCurrentUser()).getUserId());
        } else {
            // 编辑
            eduAgent.setUpdateDate(LocalDateTime.now());
            eduAgent.setUpdateId(Objects.requireNonNull(FebsUtil.getCurrentUser()).getUserId());
        }
        this.saveOrUpdate(eduAgent);
        return ResultBean.buildSuccess();
    }

    /**
     * 获取代理商详情
     *
     * @param agentId 代理商id
     * @return com.yida.data.common.core.common.ResultBean<com.yida.data.system.vo.AgentDetailVO>
     * @author ZYJ
     * @date 2021/9/26 14:59
     */
    @Override
    public ResultBean<AgentDetailVO> getAgentInfo(Long agentId) {
        EduAgent eduAgent = this.getById(agentId);
        AgentDetailVO agentDetailVO = new AgentDetailVO();
        Optional.ofNullable(eduAgent).ifPresent(agent -> BeanUtils.copyProperties(agent, agentDetailVO));
        return ResultBean.buildSuccess(agentDetailVO);
    }

    /**
     * 获取代理商管理员账号详情
     *
     * @param agentId 代理商id
     * @return com.yida.data.common.core.common.ResultBean<com.yida.data.system.vo.AgentAdminAccountDetailVO>
     * @author ZYJ
     * @date 2021/9/29 16:02
     */
    @Override
    public ResultBean<AgentAdminAccountDetailVO> getAgentAdminAccountInfo(Long agentId) {
        // 获取代理商管理员账号详情
        SystemUser systemUser = this.userMapper.getAgentAdminAccountInfo(agentId, RoleEnum.ROLE_AGENT_ADMIN.getValue());
        // 返回数据
        AgentAdminAccountDetailVO agentAdminAccountDetailVO = new AgentAdminAccountDetailVO();
        Optional.ofNullable(systemUser).ifPresent(user -> {
            BeanUtils.copyProperties(systemUser, agentAdminAccountDetailVO);
            agentAdminAccountDetailVO.setUserName(systemUser.getUsername());
        });
        return ResultBean.buildSuccess(agentAdminAccountDetailVO);
    }

    /**
     * 创建代理商管理员账号
     *
     * @param agentAdminAccountSaveDTO 保存代理商管理员账号请求类
     * @return com.yida.data.common.core.common.ResultBean<java.lang.String>
     * @author ZYJ
     * @date 2021/9/29 16:14
     */
    @Override
    public ResultBean<String> saveAgentAdminAccount(AgentAdminAccountSaveDTO agentAdminAccountSaveDTO) {
        SystemUser systemUser = new SystemUser();
        systemUser.setUserId(agentAdminAccountSaveDTO.getUserId());
        systemUser.setUsername(agentAdminAccountSaveDTO.getUserName());
        systemUser.setAgentId(agentAdminAccountSaveDTO.getAgentId());
        systemUser.setNickname(agentAdminAccountSaveDTO.getNickname());
        // 查询代理商管理员角色数据
        Role role = this.roleService.getOne(Wrappers.lambdaQuery(new Role())
                .eq(Role::getRolePerms, RoleEnum.ROLE_AGENT_ADMIN.getValue()));
        systemUser.setRoleId(String.valueOf(role.getRoleId()));
        // 新增
        if (systemUser.getUserId() == null) {
            SystemUser checkUser = this.userMapper.findUserByUsername(agentAdminAccountSaveDTO.getUserName());
            if (Objects.nonNull(checkUser)) {
                throw new FebsException("该用户名已存在！");
            }
            systemUser.setCreateDate(LocalDateTime.now());
            this.userService.createUser(systemUser);
        } else {
            // 编辑
            systemUser.setUpdateDate(LocalDateTime.now());
            this.userService.updateUser(systemUser);
        }
        return ResultBean.buildSuccess();
    }
}
