package com.yfd.platform.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.config.TencentSmsProperties;
import com.yfd.platform.modules.basedata.domain.Substation;
import com.yfd.platform.modules.basedata.mapper.SubstationMapper;
import com.yfd.platform.system.domain.LoginUser;
import com.yfd.platform.system.domain.SysOrganization;
import com.yfd.platform.system.domain.SysRole;
import com.yfd.platform.system.domain.SysUser;
import com.yfd.platform.system.mapper.SysOrganizationMapper;
import com.yfd.platform.system.mapper.SysRoleMapper;
import com.yfd.platform.system.mapper.SysUserMapper;
import com.yfd.platform.system.service.IUserService;
import com.yfd.platform.utils.FileUtil;
import com.yfd.platform.utils.sm3.SM3Utils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户服务实现类
 * </p>
 *
 *
 * @since 2021-10-27
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements IUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;


    @Resource
    private SysOrganizationMapper sysOrganizationMapper;

    @Resource
    private SubstationMapper substationMapper;

    @Resource
    private TencentSmsProperties smsProperties;

    /**
     * 用户头像图片路径
     */
    @Value("${file-space.system}")
    private String systempath;

    /**********************************
     * 用途说明:获取当前用户账号及名称
     * 参数说明
     * 返回值说明: 系统管理员[admin]
     ***********************************/
    @Override
    public String getUsername() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginuser = (LoginUser) authentication.getPrincipal();
        String acountname =
                loginuser.getUser().getNickname();
        return acountname;
        //return "admin";
    }

    @Override
    public Map<String, String> getNameInfo() {
        Map<String, String> map = new HashMap<>();
        try {
            UsernamePasswordAuthenticationToken authentication =
                    (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
            LoginUser loginuser = (LoginUser) authentication.getPrincipal();
            String nickname = loginuser.getUser().getNickname();
            String username = loginuser.getUser().getUsername();
            map.put("nickname", nickname);
            map.put("username", username);
        } catch (Exception e) {
            throw new RuntimeException("当前登录已失效，请重新登录");
        }
        return map;
    }

    @Override
    public SysUser getUserInfo() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginuser = (LoginUser) authentication.getPrincipal();
        return loginuser.getUser();
    }

    @Override
    public ResponseResult getLoginUserInfo() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginuser = (LoginUser) authentication.getPrincipal();
        SysUser user = loginuser.getUser();
        //根据用户ID获取组织
        Map<String, String> userInfo =
                sysUserMapper.getOrganizationByid(user.getId());
        String oid = userInfo.get("oid");
        SysOrganization sysOrganization1 = sysOrganizationMapper.selectById(oid);
        if (sysOrganization1 != null) {
            if (!"0".equals(sysOrganization1.getParentid())) {
                String parentid = sysOrganization1.getParentid();
                SysOrganization sysOrganization = sysOrganizationMapper.selectById(parentid);
                userInfo.put("poid", parentid);
                userInfo.put("porgname", sysOrganization.getOrgname());
            } else {
                userInfo.put("poid", sysOrganization1.getId());
                userInfo.put("porgname", sysOrganization1.getOrgname());
            }

        }
        List<SysRole> roles =
                sysRoleMapper.selectList(new QueryWrapper<SysRole>().inSql(
                        "id ", "SELECT roleid FROM sys_role_users ru WHERE isvaild='1' and ru" +
                                ".userid = '" + user.getId() + "'"));
        List<String> collect =
                roles.stream().map(SysRole::getRolename).collect(Collectors.toList());
        ResponseResult responseResult = new ResponseResult();
        responseResult.put("userInfo", userInfo);
        responseResult.put("roles", collect);
        if (user.getUsertype() != 0) {
            if (roles.size() == 0) {
                return null;
            }
            List<Map<String, Object>> mapList = new ArrayList<>();
            List<String> orgIds =
                    roles.stream().map(SysRole::getOrgscope).collect(Collectors.toList());
            Set<String> setIds = new HashSet<>();
            for (String orgId : orgIds) {
                if (StrUtil.isBlank(orgId)) {
                    continue;
                }
                String[] split = orgId.split(",");
                List<String> stringList = Arrays.asList(split);
                setIds.addAll(stringList);
            }
            for (String setId : setIds) {
                Map<String, Object> orgMap = new HashMap<>();
                SysOrganization sysOrganization = sysOrganizationMapper.selectById(setId);
                if (sysOrganization == null) {
                    continue;
                }
                String orgcode = sysOrganization.getOrgcode();
                Substation substation =
                        substationMapper.selectOne(new LambdaQueryWrapper<Substation>().eq(Substation::getStationCode
                                , orgcode));
                if (substation == null) {
                    continue;
                }
                orgMap.put("stationCode", substation.getStationCode());
                orgMap.put("stationName", substation.getStationName());
                orgMap.put("stationId", substation.getStationId());
                orgMap.put("coordinate", substation.getCoordinate());
                orgMap.put("isStationFlag", substation.getIsStationFlag());
                orgMap.put("custom1", substation.getCustom1());
                orgMap.put("online", substation.getIsStationFlag().equals("1") ? substation.getOnline() : '1');
                orgMap.put("stationNodeid", substation.getNodeId());
                mapList.add(orgMap);
            }
            List<Map<String, Object>> custom1 =
                    mapList.stream().sorted(Comparator.comparing(m -> m.get("custom1").toString())).collect(Collectors.toList());
            responseResult.put("codeList", custom1);
        } else {
            LambdaQueryWrapper<SysOrganization> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysOrganization::getIsvaild, "1");
            List<SysOrganization> sysOrganizations = sysOrganizationMapper.selectList(queryWrapper);
            // 获取变电站编码
            Set<String> setCode =
                    sysOrganizations.stream().map(SysOrganization::getOrgcode).collect(Collectors.toSet());
            if (setCode.size() == 0) {
                responseResult.put("codeList", null);
            } else {
                LambdaQueryWrapper<Substation> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.in(Substation::getStationCode, setCode);
                queryWrapper1.select(Substation::getStationId, Substation::getStationCode, Substation::getStationName,
                        Substation::getCoordinate, Substation::getIsStationFlag, Substation::getOnline, Substation::getNodeId).orderByAsc(Substation::getCustom1);
                List<Map<String, Object>> mapList = substationMapper.selectMaps(queryWrapper1);
                mapList.forEach(m -> {
                    if ("0002".equals(m.get("stationCode").toString())) {
                        m.put("isAlarm", 1);
                    } else {
                        m.put("isAlarm", 0);
                    }
                    if (ObjUtil.isEmpty(m.get("isStationFlag")) || m.get("isStationFlag").equals("0")) {
                        m.put("online", 1);
                    }
                });
                responseResult.put("codeList", mapList);
            }

        }
        responseResult.put("permissions", loginuser.getPermissions());
        return responseResult;
    }

    /***********************************
     * 用途说明：新增用户
     * 参数说明
     *sysUser   新增用户对象
     * id       创建者id
     * roleId   角色id
     * 返回值说明: 提示字符串
     ************************************/
    @Override
    public Map addUser(SysUser sysUser, String roleids) {
        //返回信息
        Map result = new HashMap<String, String>();
        sysUser.setId(IdUtil.fastSimpleUUID());
        //普通用户
        sysUser.setUsertype(1);
        //设置缺省密码
        String cryptPassword = SM3Utils.encrypt("QAZ13579test@");
        sysUser.setPassword(cryptPassword);
        sysUser.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        sysUser.setLastmodifier(getUsername());
        sysUser.setPwdresettime(DateUtil.now());
        //账号有效
        sysUser.setStatus(1);
        //判断注册的登录账号是否存在
        if (isExistAccount(sysUser.getUsername())) {
            //新增用户
            boolean ok = this.save(sysUser);
            //新增用户分配权限
            if (StrUtil.isNotEmpty(roleids)) {
                String[] roles = roleids.split(",");
                for (String roleid : roles) {
                    //系统生成id
                    String id = IdUtil.fastSimpleUUID();
                    //新增sys_role_users表数据
                    ok = ok && sysUserMapper.addUserRoles(id, roleid,
                            sysUser.getId());
                }
            }
            //判断新增是否成功  消息提示
            if (ok) {
                result.put("status", "sucess");
                result.put("msg", "新增用户成功！");

            } else {
                result.put("status", "error");
                result.put("msg", "新增用户失败！");
            }
        } else {
            result.put("status", "error");
            result.put("msg", "用户账号已存在，不能重复添加！");
        }
        return result;
    }

    /***********************************
     * 用途说明:查询系统用户
     * 参数说明
     *page     分页集合参数
     *orgid    所属组织
     *username 用户名称
     * mobile  手机号
     * status  状态
     * 返回值说明: 用户分页集合
     ************************************/
    @Override
    public List<Map> list(String total, String size, String orgid,
                          String username, String mobile, String status) {
        List<Map> list = sysUserMapper.list(total, size, orgid, username,
                mobile, status);
        for (Map map : list) {
            List<Map> mapList =
                    sysUserMapper.getLevel(map.get("id").toString());
            String roleid = "";
            String level = "";
            String rolename = "";
            for (Map map1 : mapList) {
                roleid += map1.get("id") + ",";
                level += map1.get("level") + ",";
                rolename += map1.get("rolename") + ",";
            }
            if (roleid.endsWith(",")) {
                roleid = roleid.substring(0, roleid.length() - 1);
            }
            if (level.endsWith(",")) {
                level = level.substring(0, level.length() - 1);
            }
            if (rolename.endsWith(",")) {
                rolename = rolename.substring(0, rolename.length() - 1);
            }

            map.put("roleid", roleid);
            map.put("level", level);
            map.put("rolename", rolename);
        }
        return list; //返回分页集合
    }

    /***********************************
     * 用途说明：根据ID修改用户
     * 参数说明
     *sysUser   用户对象
     *roleids  角色id
     * 返回值说明: 是否更新成功
     ************************************/
    @Override
    public Map updateById(SysUser sysUser, String roleids) {
        //返回信息
        Map result = new HashMap<String, String>();
        //获取当前用户 最近修改者替换
        sysUser.setLastmodifier(getUsername());
        //获取当前时间 最近修改日期替换
        sysUser.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        //根据修改
        boolean ok = this.updateById(sysUser);
        if (ok) {
            if (StrUtil.isNotEmpty(roleids)) {
                String[] roles = roleids.split(",");
                List<String> list = sysUserMapper.getRoleid(sysUser.getId());
                for (String role : roles) {
                    if (!list.contains(role)) {
                        //系统生成id
                        String id = IdUtil.fastSimpleUUID();
                        //新增sys_role_users表数据
                        ok = ok && sysUserMapper.addUserRoles(id, role,
                                sysUser.getId());
                    }
                }
                //删除不包含的角色
                sysUserMapper.delInRoleUsersByUserid(sysUser.getId(), roles);

            } else {
                //根据用户id 删除该用户角色关联
                ok = ok && sysUserMapper.delRoleUsersByUserid(sysUser.getId());
            }
            result.put("status", "sucess");
            result.put("msg", "用户信息修改成功！");
        } else {
            result.put("status", "error");
            result.put("msg", "用户信息修改失败！");
        }

        return result;
    }

    @Override
    public Map getOneById(String id) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        Map map = this.getMap(queryWrapper.eq("id", id));
        List<Map> mapList = sysUserMapper.getLevel(id);
        String roleid = "";
        String level = "";
        String rolename = "";
        for (Map map1 : mapList) {
            roleid += map1.get("id") + ",";
            level += map1.get("level") + ",";
            rolename += map1.get("rolename") + ",";
        }
        if (roleid.endsWith(",")) {
            roleid = roleid.substring(0, roleid.length() - 1);
        }
        if (level.endsWith(",")) {
            level = level.substring(0, level.length() - 1);
        }
        if (rolename.endsWith(",")) {
            rolename = rolename.substring(0, rolename.length() - 1);
        }

        map.put("roleid", roleid);
        map.put("level", level);
        map.put("rolename", rolename);
        return map;
    }

    /***********************************
     * 用途说明：用户分配角色
     * 参数说明
     *listId     用户id与角色id
     * 返回值说明: 判断是否添加成功
     ************************************/
    @Override
    public boolean setUserRoles(String roleid, String userids) {
        boolean isOk = true;
        //拆分userid 数组
        String[] temp = userids.split(",");
        //遍历userid
        for (String userid : temp) {
            //根据角色id与用户id查询
            List<Map> list = sysUserMapper.getRoleUsersByid(roleid, userid);
            //判断是否用户已分配此权限
            if (list.size() == 0) {
                //系统生成id
                String id = IdUtil.fastSimpleUUID();
                //新增sys_role_users表数据
                isOk = isOk && sysUserMapper.addUserRoles(id, roleid, userid);
            }
        }
        return isOk;
    }

    /***********************************
     * 用途说明：根据id删除用户
     * 参数说明
     *id         用户id
     * 返回值说明: 判断是否删除成功
     ************************************/
    @Override
    public boolean deleteById(String id) {
        //根据id查询
        SysUser sysUser = this.getById(id);
        if(sysUser==null){
            return false;
        }
        //账号头像存储地址
        String imgName =
                systempath + File.separator + "user" + File.separator + sysUser.getAvatar();
        if (!"admin".equals(sysUser.getUsername())) {
            LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SysUser::getId, id).set(SysUser::getStatus, "3");
            boolean isOk = this.update(updateWrapper);
            //判断是否删除成功
            if (isOk) {
                //根据用户id 删除该用户角色关联
                sysUserMapper.delRoleUsersByUserid(id);
                //判断是否存在 账号头像 存在删除
                if (StrUtil.isNotEmpty(sysUser.getAvatar())) {
                    FileUtil.del(imgName);
                }
            }
        }
        return false;
    }

    /***********************************
     * 用途说明：重置用户密码(管理员)
     * 参数说明
     *id        重置密码的 用户id
     * 返回值说明: 判断是重置成功
     ************************************/
    @Override
    public boolean resetPassword(String id) throws Exception {
        boolean isOk = false;
        //根据当前用户id 查询角色表的级别 currentUser.getUser() 获取当前用户id
        SysUser userInfo = getUserInfo();
        String userId = userInfo.getId();
        String level = sysUserMapper.getMaxLevel(userId);
        //判断是否获取级别
        if (StrUtil.isNotEmpty(level)) {
            //判断当前用户级别 管理员及以上权限
            if (Integer.parseInt(level) <= 2) {
                UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
                //根据id 修改密码，密码修改时间，最近修改者，最近修改日期     将密码修改为 123456
                String cryptPassword = SM3Utils.encrypt("QAZ13579test@");
                updateWrapper.eq("id", id).set("password", cryptPassword).set(
                        "pwdresettime",
                        new Timestamp(System.currentTimeMillis())).set(
                        "lastmodifydate",
                        new Timestamp(System.currentTimeMillis())).set(
                        "lastmodifier", getUsername());
                //是否修改成功
                isOk = this.update(updateWrapper);
            }
        }
        return isOk;
    }

    /***********************************
     * 用途说明：设置账号状态(管理员)
     * 参数说明
     *id        用户id
     * status   设置状态
     * 返回值说明: 判断是否设置成功
     ************************************/
    @Override
    public boolean setStatus(String id, String status) {
        boolean isOk = false;
        //根据当前用户id 查询角色表的级别 currentUser.getUser() 获取当前用户id
        SysUser userInfo = this.getUserInfo();
        String id1 = userInfo.getId();
        String level = sysUserMapper.getMaxLevel(id1);
        //判断当前用户级别 管理员及以上权限
        //        if (Integer.parseInt(level) <= 2) {
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        //根据id修改用户状态，最近修改人，最近修改时间
        updateWrapper.eq("id", id).set("status", status).set(
                "lastmodifydate",
                new Timestamp(System.currentTimeMillis())).set(
                "lastmodifier", getUsername());
        //是否修改成功
        isOk = this.update(updateWrapper);
        //        }
        return isOk;
    }

    /***********************************
     * 用途说明：上传用户头像
     * 参数说明
     * id           用户id
     * img          账号头像
     * 返回值说明:  判断是否上传
     ***********************************/
    @Override
    public boolean uploadAvatar(String id, MultipartFile img) {
        //根据id查询
        SysUser sysUser = this.getById(id);
        //账号头像存储地址
        String imgPath = systempath + "user";
        String avatar = sysUser.getAvatar();
        if (StrUtil.isNotBlank(avatar)) {
            String imgName = imgPath + File.separator + avatar;
            FileUtil.del(imgName);
        }
        //上传图片 并获取图片名称   (图片格式修改成png)
        String imgName = FileUtil.upload(img, imgPath,
                IdUtil.fastSimpleUUID() + "." + FileUtil.getExtensionName(img.getOriginalFilename())).getName();
        //修改 账户头像
        sysUser.setAvatar(imgName);
        //修改 最近修改者
        sysUser.setLastmodifier(getUsername());
        //修改 最近修改日期
        sysUser.setLastmodifydate(new Timestamp(System.currentTimeMillis()));
        //更新用户表
        boolean isOk = this.updateById(sysUser);
        return isOk;
    }

    /***********************************
     * 用途说明：新增系统角色用户对照表 对用户分配角色(单个)
     * 参数说明
     * id       生成的id
     * roleid   角色id
     * userid   用户id
     * 返回值说明:
     ************************************/
    @Override
    public boolean addUserRoles(String roleid, String userid) {
        boolean isOk = true;
        //根据角色id与用户id查询
        List<Map> list = sysUserMapper.getRoleUsersByid(roleid, userid);
        //判断是否用户已分配此权限
        if (list.size() == 0) {
            //系统生成id
            String id = IdUtil.fastSimpleUUID();
            //新增sys_role_users表数据
            isOk = sysUserMapper.addUserRoles(id, roleid, userid);
        }
        return isOk;
    }

    @Override
    public Page<Map<String, Object>> queryUsers(String orgid,
                                                String username,
                                                String status,
                                                Page<SysUser> page) {
        Page<Map<String, Object>> mapPage = sysUserMapper.queryUsers(orgid,
                username, status, page);
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> records = mapPage.getRecords();
        for (Map<String, Object> record : records) {
            String id = (String) record.get("id");
//            if (ObjectUtil.isNotEmpty(record.get("phone"))) {
//                String phone = record.get("phone").toString();
//                record.put("phone", DesensitizedUtil.mobilePhone(phone));
//            }
//            if (ObjectUtil.isNotEmpty(record.get("email"))) {
//                String email = record.get("email").toString();
//                record.put("email", DesensitizedUtil.email(email));
//            }
            List<SysRole> sysRoles = sysRoleMapper.getRoleByUserId(id);
            record.put("roles", sysRoles);
            list.add(record);
        }
        mapPage.setRecords(list);
        return mapPage;
    }

    /***********************************
     * 用途说明：根据ID批量删除用户
     * 参数说明
     *ids        用户id集合
     * 返回值说明: 判断是否删除成功
     ************************************/
    @Override
    public boolean deleteUserByIds(String id) {
        String[] splitId = id.split(",");
        List<String> ids = Arrays.asList(splitId);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysUser::getId, ids);
        List<SysUser> sysUsers = sysUserMapper.selectList(queryWrapper);
        List<String> names =
                sysUsers.stream().map(SysUser::getUsername).collect(Collectors.toList());
        if (names.contains("admin")) {
            return false;
        } else {
            int result = sysUserMapper.deleteBatchIds(ids);
            if (result <= 0) {
                return false;
            }
            // 根据ID删除用户与角色的关联信息
            sysUserMapper.delRoleUsersByUserIds(ids);
            List<String> avatars =
                    sysUsers.stream().map(SysUser::getAvatar).collect(Collectors.toList());
            if (avatars.size() > 0) {
                for (String avatar : avatars) {
                    //账号头像存储地址
                    String imgName =
                            systempath + File.separator + "user" + File.separator + avatar;
                    FileUtil.del(imgName);
                }
            }
            return true;
        }
    }

    /***********************************
     * 用途说明：根据用户表id查询角色表所有角色id
     * 参数说明
     * userid     用户id
     * 返回值说明:
     ************************************/
    @Override
    public List<String> getRoleId(String userId) {
        return sysUserMapper.getRoleid(userId);
    }

    /***********************************
     * 用途说明:比较登录名称是否有重复
     * 参数说明
     * account  登录名称
     * 返回值说明: 重复返回 false 否则返回 true
     ************************************/
    private boolean isExistAccount(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        //判断 查询登录账号 结果集是否为null  重复返回 false 否则返回 tree
        return this.list(queryWrapper.eq("username", username)).size() <= 0;
    }

    //根据账号获取用户信息
    @Override
    public SysUser getUserInfo(String username) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<SysUser> list = this.list(queryWrapper);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    //检测密码是否一致
    @Override
    public boolean checkPassword(String username, String password) {
        SysUser sysUser = getUserInfo(username);
        String storedEncodedPassword = sysUser.getPassword();
        // 进行密码校验
        boolean matches = SM3Utils.matches(password, storedEncodedPassword);
        return matches;
    }

    //用户更新密码
    @Override
    public boolean updatePassword(String username, String password) {
        SysUser sysUser = getUserInfo(username);
        String EncodedPassword = SM3Utils.encrypt(password);
        sysUser.setPassword(EncodedPassword);
        sysUser.setPwdresettime(DateUtil.now());
        this.updateById(sysUser);
        return true;
    }

    @Override
    public List<Map> getLevel(String id) {
        return sysUserMapper.getLevel(id);
    }

    /***********************************
     * 用途说明: 获取审计管理员用户
     * 参数说明
     * 返回值说明: java.util.List<com.yfd.platform.system.domain.SysUser>
     ***********************************/
    @Override
    public List<SysUser> getAuditManagement() {
        return sysUserMapper.getAuditManagement();
    }

    @Override
    public boolean sendVerCodeToPhone(String phoneNum, String sessionContext, String templateId,
                                      String[] templateParamSet) {
        try {
            /* 必要步骤：
             * 实例化一个认证对象，入参需要传入腾讯云账户密钥对secretId，secretKey。
             * 这里采用的是从环境变量读取的方式，需要在环境变量中先设置这两个值。
             * 你也可以直接在代码中写死密钥对，但是小心不要将代码复制、上传或者分享给他人，
             * 以免泄露密钥对危及你的财产安全。
             * CAM密匙查询: https://console.cloud.tencent.com/cam/capi*/
            Credential cred = new Credential(smsProperties.getSecretId(),
                    smsProperties.getSecretKey());

            // 实例化一个http选项，可选，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            // 设置代理
            // httpProfile.setProxyHost("真实代理ip");
            // httpProfile.setProxyPort(真实代理端口);
            /* SDK默认使用POST方法。*/
            httpProfile.setReqMethod("POST");
            /* SDK有默认的超时时间，非必要请不要进行调整
             * 如有需要请在代码中查阅以获取最新的默认值 */
            httpProfile.setConnTimeout(60);
            /* SDK会自动指定域名。通常是不需要特地指定域名的，但是如果你访问的是金融区的服务
             * 则必须手动指定域名，例如sms的上海金融区域名： sms.ap-shanghai-fsi.tencentcloudapi.com */
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            /* 非必要步骤:
             * 实例化一个客户端配置对象，可以指定超时时间等配置 */
            ClientProfile clientProfile = new ClientProfile();
            /* SDK默认用TC3-HMAC-SHA256进行签名
             * 非必要请不要修改这个字段 */
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);
            /* 实例化要请求产品(以sms为例)的client对象
             * 第二个参数是地域信息，可以直接填写字符串ap-guangzhou，或者引用预设的常量 */
            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
            /* 实例化一个请求对象，根据调用的接口和实际情况，可以进一步设置请求参数
             * 你可以直接查询SDK源码确定接口有哪些属性可以设置
             * 属性可能是基本类型，也可能引用了另一个数据结构
             * 推荐使用IDE进行开发，可以方便的跳转查阅各个接口和数据结构的文档说明 */
            SendSmsRequest req = new SendSmsRequest();

            /* 填充请求参数,这里request对象的成员变量即对应接口的入参
             * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
             * 基本类型的设置:
             * sms helper: https://cloud.tencent.com/document/product/382/3773 */

            /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
            String sdkAppId = smsProperties.getSdkAppId();
            req.setSmsSdkAppid(sdkAppId);

            /* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名，签名信息可登录 [短信控制台] 查看 */
            String signName = smsProperties.getSignName();
            req.setSign(signName);

            /* 国际/港澳台短信 SenderId: 国内短信填空，默认未开通，如需开通请联系 [sms helper] */
            String senderid = smsProperties.getSenderid();
            req.setSenderId(senderid);

            /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
            //            String sessionContext = "xxx";
            req.setSessionContext(sessionContext);

            /* 短信号码扩展号: 默认未开通，如需开通请联系 [sms helper] */
            String extendCode = smsProperties.getExtendCode();
            req.setExtendCode(extendCode);

            /* 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看 */
            // String templateId = smsProperties.getTemplateIdMap().get("register");
            req.setTemplateID(templateId);

            /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
             * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号 */
            String[] phoneNumberSet = {phoneNum};
            req.setPhoneNumberSet(phoneNumberSet);

            /* 模板参数: 若无模板参数，则设置为空 */
            // String[] templateParamSet = {"5678", "5"};
            req.setTemplateParamSet(templateParamSet);

            /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
             * 返回的 res 是一个 SendSmsResponse 类的实例，与请求对象对应 */
            SendSmsResponse res = client.SendSms(req);


        } catch (Exception  e) {
            log.error(e.getMessage());;
            return false;
        }
        return true;
    }

}
