package com.jiayue.ssi.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiayue.ssi.backenum.ApproveOperaterEnum;
import com.jiayue.ssi.backenum.ApproveStatusEnum;
import com.jiayue.ssi.constant.ApproveConstants;
import com.jiayue.ssi.constant.SecretKeyConstants;
import com.jiayue.ssi.entity.SysApprove;
import com.jiayue.ssi.entity.SysUser;
import com.jiayue.ssi.entity.SysUserRole;
import com.jiayue.ssi.mapper.SysApproveMapper;
import com.jiayue.ssi.mapper.SysUserMapper;
import com.jiayue.ssi.mapper.SysUserRoleMapper;
import com.jiayue.ssi.service.SysApproveService;
import com.jiayue.ssi.service.SysUserService;
import com.jiayue.ssi.util.ResponseVO;
import com.jiayue.ssi.util.SM2CryptUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* 用户管理服务类
* @author xsl
* @date 2023/2/16
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    SysApproveMapper sysApproveMapper;
    @Autowired
    SysApproveService sysApproveService;

    /**
     * 获取所有用户
     * @return List<SysUser>
     */
    @Override
    public List<SysUser> queryAllUsers(){
        return this.list();
    }
    /**
     * 保存用户
     * @param sysUser
     * @return boolean
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean saveUser(SysUser sysUser){
       return this.save(sysUser);
    }
    /**
     * 更新用户
     * @param sysUser
     * @return boolean
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean updateUser(SysUser sysUser){
        return this.updateById(sysUser);
    }
    /**
     * 删除用户
     * @param id
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteUser(String id){
        return this.removeById(id);
    }
    /**
     * 根据账号查找
     * @param username
     * @return SysUser
     */
    @Override
    public SysUser queryUserName(String username){
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername,username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        return sysUser;
    }
    /**
     * 根据邮箱查找
     * @param mailbox
     * @return SysUser
     */
    @Override
    public SysUser queryMailBox(String mailbox){
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getMailbox,mailbox);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        return sysUser;
    }
    /**
     * 删除用户
     * @param sysUser
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean removeUserById(SysUser sysUser) {
        // 插入审批表
        SysApprove sysApprove = new SysApprove();
        sysApprove.setModuleName(ApproveConstants.MODULE_NAME_USER);
        sysApprove.setOperation(String.valueOf(ApproveOperaterEnum.DELETE.getCode()));
        sysApprove.setApproveStatus(String.valueOf(ApproveStatusEnum.DSP.getCode()));
        sysApprove.setEntityName("SysUser");
        sysApprove.setParameterContent(JSONUtil.parse(sysUser).toString());
        sysApprove.setMasterId(String.valueOf(sysUser.getId()));
        int count = sysApproveMapper.insert(sysApprove);
        if (count > 0) {
            return true;
        }
        return false;

//        LambdaUpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<SysUser>().lambda();
//        updateWrapper.eq(SysUser::getId, id).set(SysUser::getDelFlag, 1);
//        int count = sysUserMapper.update(new SysUser(), updateWrapper);
//        if (count > 0) {
//            return true;
//        }
    }
    /**
     * 初始/重置密码
     * @param id            主键id
     * @param initPassword  初始密码
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean resetPassword(Integer id,String initPassword,String checkPassword,String bakPassword) {
        int count = sysUserMapper.resetPassword(Long.parseLong(id+""),initPassword,checkPassword,bakPassword);
        if (count > 0) {
            return true;
        }
        return false;
    }
    /**
     * 解锁用户
     * @param id
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean relockUserById(Integer id, String expDate) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<SysUser>().lambda();
        if (StringUtils.isNotBlank(expDate)){
            Date eDate = DateUtil.parseDate(expDate);
            updateWrapper.eq(SysUser::getId, id).set(SysUser::getStatus, 0).set(SysUser::getLockTime,0).set(SysUser::getExpDate,eDate);
        }
        else{
            updateWrapper.eq(SysUser::getId, id).set(SysUser::getStatus, 0).set(SysUser::getLockTime,0);
        }

        int count = sysUserMapper.update(new SysUser(), updateWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }
    /**
     * 用户授权角色
     *
     * @param userId 用户ID
     * @param roleId 角色ID
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public int insertUserAuth(Long userId, Long roleId) {
        int returnVal = 0;
        sysUserRoleMapper.deleteUserRoleByUserId(userId);
        if (roleId!=null){
            // 新增用户与角色管理
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            returnVal = sysUserRoleMapper.insert(ur);
        }
        return returnVal;
    }

    /**
     * 通过角色ID查找用户
     * @param roleId 角色Id
     * @return
     */
    @Override
    public List<SysUser> selectUserByRole(String roleId){
        return sysUserMapper.selectUserByRole(roleId);

    }

    /**
     * 获取全部用户数据，并且字段解密后的
     * @return
     */
    @Override
    public List<SysUser> queryAllUserByDecrypt(){
        // 查询全部
        List<SysUser> sysUserList = this.list();
        for (SysUser sysUser:sysUserList){
            sysUser.setMailbox(SM2CryptUtils.decrypt(sysUser.getMailbox(), SecretKeyConstants.SERVER_PRIVATE_KEY));
            sysUser.setPhonenumber(SM2CryptUtils.decrypt(sysUser.getPhonenumber(), SecretKeyConstants.SERVER_PRIVATE_KEY));
            sysUser.setNickname(SM2CryptUtils.decrypt(sysUser.getNickname(), SecretKeyConstants.SERVER_PRIVATE_KEY));
            sysUser.setIdcard(SM2CryptUtils.decrypt(sysUser.getIdcard(), SecretKeyConstants.SERVER_PRIVATE_KEY));
        }
        return sysUserList;
    }

    /**
     * 新增用户
     * @param id
     * @param sysApprove
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean addUserByApprove(Long id,SysApprove sysApprove) {
        LambdaUpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<SysUser>().lambda();
        updateWrapper.eq(SysUser::getId, id).set(SysUser::getSignstr, "1");
        sysUserMapper.update(new SysUser(), updateWrapper);
        boolean bo = sysApproveService.save(sysApprove);
        return bo;
    }
}
