package com.ytpm.middle.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.constant.StrConstant;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.middle.dao.MiddleUserMapper;
import com.ytpm.middle.model.YtMiddleRole;
import com.ytpm.middle.model.YtMiddleUser;
import com.ytpm.middle.model.YtMiddleUserRole;
import com.ytpm.middle.param.MiddleUserListParam;
import com.ytpm.middle.param.MiddleUserParam;
import com.ytpm.middle.service.UserService;
import com.ytpm.middle.util.RedisUtil;
import com.ytpm.middle.view.MiddleRoleVO;
import com.ytpm.middle.view.MiddleUserInfo;
import com.ytpm.oauth.model.YtPlatformUser;
import com.ytpm.util.IDUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private MiddleUserMapper userMapper;
    @Resource
    private RedisUtil redisService;

    /**
     * 查询用户列表
     */
    @Override
    public ResultTable<MiddleUserInfo> queryList(MiddleUserListParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        return ResultTable.resultTableOk(new PageInfo<>(userMapper.queryList(param)));
    }

    /**
     * 新增用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> addOne(MiddleUserParam param) {
        MiddleUserInfo byPhone = userMapper.getByPhone(param.getPhone());
        if(Objects.nonNull(byPhone)){
            return Result.resultErr(RepMessage.OBJECT_ALREADY_EXIST);
        }
        //新增用户信息
        YtPlatformUser user = new YtPlatformUser();
        BeanUtils.copyProperties(param, user);
        user.setUserId(IDUtil.generateFlowID("middle_"));
        user.setUserType(99);
        user.setRegistryTime(new Date());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setEncryptPwd(encoder.encode(param.getPassword()));
        userMapper.insertOne(user);
        param.setUserId(user.getUserId());
        //新增用户角色信息
        if(CollUtil.isNotEmpty(param.getRoleList())){
            addUserRole(param);
        }
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }
    /**
     * 修改用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> updateOne(MiddleUserParam param,String loginName) {
        MiddleUserInfo byPhone = userMapper.selectPrimary(param.getUserId());
        if(Objects.isNull(byPhone)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        //修改用户信息
        YtPlatformUser user = new YtPlatformUser();
        BeanUtils.copyProperties(param, user);
        if(StrUtil.isNotBlank(param.getPassword())){
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            user.setEncryptPwd(encoder.encode(param.getPassword()));
        }
        userMapper.updateById(user);
        param.setUserId(user.getUserId());
        //角色列表先删后增
        userMapper.deleteByUserId(param.getUserId());
        if(CollUtil.isNotEmpty(param.getRoleList())){
            addUserRole(param);
        }
        //清除redis用户信息
        redisService.del(StrConstant.ADS_USER_INFO_PRE+loginName);
        return Result.resultOk(RepMessage.MODIFY_SUCCESS);
    }

    /**
     * 删除用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> delOne(String userId) {
        MiddleUserInfo old = userMapper.selectPrimary(userId);
        if(Objects.isNull(old)){
            return Result.resultErr(RepMessage.OBJECT_NOT_EXIST);
        }
        YtPlatformUser platformUser = new YtPlatformUser();
        platformUser.setUserId(userId);
        platformUser.setAccountStatus(2);
        userMapper.updateById(platformUser);
        userMapper.deleteByUserId(userId);
        return Result.resultOk(RepMessage.DELETE_SUCCESS);
    }

    /**
     * 增加用户角色
     */
    private void addUserRole(MiddleUserParam param) {
        userMapper.addUserRoleList(param.getUserId(),param.getRoleList(),param.getOperatorId());
    }
}
