package com.zcloud.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zcloud.common.utils.DateUtil;
import com.zcloud.common.utils.FileUploadUtil;
import com.zcloud.common.utils.PageUtils;
import com.zcloud.common.utils.R;
import com.zcloud.modules.sys.dao.SysUserDao;
import com.zcloud.modules.sys.entity.BusImgfilesEntity;
import com.zcloud.modules.sys.entity.SysUserEntity;
import com.zcloud.modules.sys.service.BusImgfilesService;
import com.zcloud.modules.sys.service.SysUserRoleService;
import com.zcloud.modules.sys.service.SysUserService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;


/**
 * 系统用户
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Resource
    private BusImgfilesService busImgfilesService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<Map<String, Object>> page = new Page<>(Integer.parseInt(params.get("curPage").toString()), Integer.parseInt(params.get("limit").toString()));
        params.put("isDelete", 0);
        IPage<SysUserEntity> ipage = baseMapper.listPage(page, params);
        return new PageUtils(ipage);
    }

    @Override
    public SysUserEntity queryById(String userId) {
        return baseMapper.queryById(userId);
    }

    @Override
    public List<String> queryAllPerms(String userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public List<String> queryAllMenuId(String userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public SysUserEntity queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }

    @Override
    @Transactional
    public R saveUser(SysUserEntity user,MultipartFile file) throws IOException {
        user.setStatus(1);
        //sha256加密
        user.setPassword(new Sha256Hash("Aqsc@2024", user.getUsername()).toHex());
        this.save(user);
        //保存证书图片
        if (saveImg(user,file)) return R.error(200, "上传文件格式不正确");
        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
        return R.ok();
    }

    @Override
    @Transactional
    public void update(SysUserEntity user) {

        this.updateById(user);
        //删除图片
        //保存用户与角色关系
        if (user.getRoleIdList() != null) {
            sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
        }
    }

    @Override
    public R updateSysUserInfo(SysUserEntity user, MultipartFile file) throws IOException {
        this.updateById(user);
        if (saveImg(user,file)) return R.error(200, "上传文件格式不正确");
        //保存用户与角色关系
        if (user.getRoleIdList() != null) {
            sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
        }
        return R.ok();
    }

    @Override
    @Transactional
    public void deleteBatch(String[] userId) {
        baseMapper.deleteBatchIds(Arrays.asList(userId));
    }

    @Override
    public boolean updatePassword(String userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }

    @Override
    public List<SysUserEntity> listAll(Map<String, Object> params) {
        return baseMapper.listAll(params);
    }

    @Override
    public List<SysUserEntity> listForSelect(Map<String, Object> params) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.ne("user_id", "1");
        queryWrapper.isNull("corpinfo_id");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public SysUserEntity findByMobile(String phone) {
        LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserEntity::getMobile, phone);
        queryWrapper.eq(SysUserEntity::getIsDelete, 0);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void editOpenid(String phone, String openid) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setOpenid(openid);
        this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("mobile", phone));
    }

    private String get32UUID() {
        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
        return uuid;
    }

    /**
     * 校验手机号
     *
     * @param phoneNumber
     * @return
     */
    public static boolean isValidPhoneNumber(String phoneNumber) {
        if ((phoneNumber != null) && (!phoneNumber.isEmpty())) {
            return Pattern.matches("^1[3-9]\\d{9}$", phoneNumber);
        }
        return false;
    }

    /**
     * 校验邮箱
     *
     * @param email
     * @return
     */
    public static boolean isValidEmail(String email) {
        if ((email != null) && (!email.isEmpty())) {
            return Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", email);
        }
        return false;
    }

    private boolean saveImg(SysUserEntity param, MultipartFile file) {
        if (file != null) {
//            for (MultipartFile multipartFile : files) {
                String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
                if (!"pdf".equals(suffixName) && !"jpg".equals(suffixName) && !"jpeg".equals(suffixName) && !"png".equals(suffixName) && !"mp4".equals(suffixName)) {
                    return true;
                }
//            }
//            for (MultipartFile file : files) {
                String ffile = DateUtil.getDays();
                String fileName = this.get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                FileUploadUtil.sshSftp(file, fileName, "/uploadFiles/" + param.getUserId() + "/" + ffile);
                BusImgfilesEntity img = new BusImgfilesEntity();
                img.setFilepath("/uploadFiles/" + param.getUserId() + "/" + ffile + "/" + fileName);
                img.setType(6);
                img.setForeignKey(param.getUserId());
                img.setCorpinfoId(param.getCorpinfoId());
                img.setFilename(fileName);
                busImgfilesService.save(img);
//            }
        }
        return false;
    }

}
