AdministerServiceImpl.java 16.9 KB
package com.subsidy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.subsidy.common.configure.SubsidyConfig;
import com.subsidy.common.exception.HttpException;

import com.subsidy.dto.administer.*;
import com.subsidy.mapper.*;
import com.subsidy.model.*;
import com.subsidy.service.AdministerService;
import com.subsidy.service.CompanyMemberMappingService;
import com.subsidy.util.*;
import com.subsidy.util.excel.ExcelUtil;
import com.subsidy.vo.administer.AuthVO;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * <p>
 * 管理平台用户 服务实现类
 * </p>
 *
 * @author Tuyp
 * @since 2024-01-11
 */
@Service
public class AdministerServiceImpl extends ServiceImpl<AdministerMapper, AdministerDO> implements AdministerService {


    @Autowired
    private SubsidyConfig subsidyConfig;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private DepartmentDictMapper departmentDictMapper;

    @Autowired
    private CompanyMemberMappingMapper companyMemberMappingMapper;

    @Autowired
    private MemberDepartmentMappingMapper  memberDepartmentMappingMapper;

    public LoginVO login(AdministerDO administerDO) {

        LoginVO loginVO = new LoginVO();

        AdministerDO administerDO1 = this.baseMapper.selectOne(new QueryWrapper<AdministerDO>()
                .lambda()
                .eq(AdministerDO::getAccountName, administerDO.getAccountName())
                .ne(AdministerDO::getRole, 2));

        if (null == administerDO1) {
            throw new HttpException(10012);
        }

        if ("0".equals(administerDO1.getStatus())) {
            throw new HttpException(10013);
        }

        if (administerDO1.getPassword().equals(administerDO.getPassword())) {
            String token = JwtUtil.generateToken(administerDO1.getId(), ConstantUtils.ADMINISTER_TERMINATE);
            loginVO.setToken(token);
            return loginVO;
        }else {
            throw new HttpException(10011);
        }
    }


    public AdministerPermissionVO getPermissions() {

        AdministerPermissionVO administerPermissionVO = new AdministerPermissionVO();
        AdministerDO administerDO = (AdministerDO) Localstorage.getUser();
        if (administerDO == null) {
            throw new HttpException(10012);
        }
        BeanUtils.copyProperties(administerDO, administerPermissionVO);

        List<PermissionsVO> list = this.baseMapper.getPermissions(administerDO.getId());
        List<PermissionsVO> treeList = new ArrayList();
        if (list != null) {
            list.forEach(permission -> {
                if (permission.getParentId() == null) {
                    treeList.add(permission);
                }

                list.forEach(p -> {
                    if (null != p.getParentId() && p.getParentId().equals(permission.getId())) {
                        if (permission.getChildren() == null) {
                            permission.setChildren(new ArrayList<>());
                        }
                        permission.getChildren().add(p);
                    }
                });
            });
        }
        administerPermissionVO.setPermissions(treeList);
//        //查询角色
//        RoleAdministerMappingDO roleAdministerMappingDO = roleAdministerMappingMapper.selectOne(new QueryWrapper<RoleAdministerMappingDO>()
//                .lambda()
//                .eq(RoleAdministerMappingDO::getAdministerId, administerDO.getId()));
//        administerPermissionVO.setRole(roleAdministerMappingDO.getRoleId());

//        CompanyDictDO companyDictDO = companyDictMapper.selectById(administerDO.getCompanyId());
//        administerPermissionVO.setCompanyName(companyDictDO.getCompanyName());
//        administerPermissionVO.setShortName(companyDictDO.getShortName());

        /**
         * 所在公司
         */
        List<GetAllCompanyVO> getAllCompanyVOS = this.baseMapper.administerCompanys(administerDO.getId());
        administerPermissionVO.setGetAllCompanyVOS(getAllCompanyVOS);

        return administerPermissionVO;
    }

    public AuthVO auth(AdministerDO administerDO){

        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        String resValue = "";

        long timestamp = System.currentTimeMillis();
        String nonce = SecretUtils.getNonce(5);
        String appId = subsidyConfig.getAppId();

        String appKey = subsidyConfig.getSecurityKey();
        String mobile = administerDO.getTelephone();
        String signature = SecretUtils.gen(appKey, nonce, String.valueOf(timestamp), appId, mobile);
        try {
            client = HttpClients.createDefault();
            HttpUriRequest build = RequestBuilder
                    .post(subsidyConfig.getUrl())
                    .addHeader("Content-Type", "application/json")
                    .setEntity(new StringEntity(""))
                    .addParameter("appId", appId)
                    .addParameter("mobile", mobile)
                    .addParameter("timestamp", String.valueOf(timestamp))
                    .addParameter("signature", signature)
                    .addParameter("nonce", nonce)
                    .build();
            //请求
            response = client.execute(build);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                resValue = EntityUtils.toString(entity, "UTF-8");
                ResultMode resMode = JSON.parseObject(resValue, ResultMode.class);
                AuthVO qxyVO = new AuthVO();
                qxyVO.setToken(resMode.getData().toString());
                return qxyVO;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AuthVO();
    }


    //    @Transactional(rollbackFor = Exception.class)
    public ImportMemberResultVO importMember(Long companyId, MultipartFile multipartFile) throws Exception {

        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        //拼音小写
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        //不带声调
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        ImportMemberResultVO importMemberResultVO = new ImportMemberResultVO();

        List<ImportMemberVO> failMembers = new ArrayList<>();

        int successCount = 0;
        int failCount = 0;
        List<ImportMemberDTO> importMemberDTOS = ExcelUtil.readExcelWithoutTitle(null, ImportMemberDTO.class, multipartFile);
        for (ImportMemberDTO s : importMemberDTOS) {
            try {

                MemberDO memberDel = memberMapper.selectOne(new QueryWrapper<MemberDO>()
                        .lambda()
                        .eq(MemberDO::getTelephone, s.getTelephone()));

                MemberDO memberIdCard = memberMapper.selectOne(new QueryWrapper<MemberDO>()
                        .lambda()
                        .eq(MemberDO::getIdCard, s.getIdCard()));

                boolean departmentFlag = false;
                String[] fullName = s.getDepartments().split(",");

                for (String dep : fullName) {
                    DepartmentDictDO departmentDictDO = departmentDictMapper.selectOne(new QueryWrapper<DepartmentDictDO>()
                            .lambda()
                            .eq(DepartmentDictDO::getFullName, dep));
                    if (null == departmentDictDO) {
                        departmentFlag = true;
                    }
                }

                //日期格式
                SimpleDateFormat d = null;
                Date date = null;

                if (!StringUtils.isEmpty(s.getInductionDate())) {
                    String DATE_PATTERN = "yyyy-MM-dd";
                    SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.US);
                    date = sdf.parse(s.getInductionDate());
                    d = new SimpleDateFormat(DATE_PATTERN);
                }

                if (StringUtils.isEmpty(s.getUserName()) || StringUtils.isEmpty(s.getTelephone()) || StringUtils.isEmpty(s.getGender()) || StringUtils.isEmpty(s.getIdCard()) || StringUtils.isEmpty(s.getDepartments())) {
                    ImportMemberVO importMemberVO = new ImportMemberVO();
                    BeanUtils.copyProperties(s, importMemberVO);
                    importMemberVO.setReason("必填字段为空");
                    if (null != d && null != date) {
                        s.setInductionDate(d.format(date));
                    }
                    importMemberVO.setDepartments(s.getDepartments());
                    failMembers.add(importMemberVO);
                    failCount++;
                } else if (departmentFlag) {
                    ImportMemberVO importMemberVO = new ImportMemberVO();
                    BeanUtils.copyProperties(s, importMemberVO);
                    importMemberVO.setReason("未查询到部门名称");
                    if (null != d && null != date) {
                        s.setInductionDate(d.format(date));
                    }
                    importMemberVO.setDepartments(s.getDepartments());
                    failMembers.add(importMemberVO);
                    failCount++;
                } else if (null != s.getIdCard() && s.getIdCard().length() != 18) {
                    ImportMemberVO importMemberVO = new ImportMemberVO();
                    BeanUtils.copyProperties(s, importMemberVO);
                    importMemberVO.setReason("身份证位数不正确");
                    if (null != d && null != date) {
                        s.setInductionDate(d.format(date));
                    }
                    importMemberVO.setDepartments(s.getDepartments());
                    failMembers.add(importMemberVO);
                    failCount++;
                } else if (null != s.getTelephone() && s.getTelephone().length() != 11) {
                    ImportMemberVO importMemberVO = new ImportMemberVO();
                    BeanUtils.copyProperties(s, importMemberVO);
                    importMemberVO.setReason("手机号位数不正确");
                    if (null != d && null != date) {
                        s.setInductionDate(d.format(date));
                    }
                    importMemberVO.setDepartments(s.getDepartments());
                    failMembers.add(importMemberVO);
                    failCount++;
                } else if (null != memberDel) {
                    ImportMemberVO importMemberVO = new ImportMemberVO();
                    BeanUtils.copyProperties(s, importMemberVO);
                    importMemberVO.setReason("手机号重复");
                    if (null != d && null != date) {
                        s.setInductionDate(d.format(date));
                    }
                    importMemberVO.setDepartments(s.getDepartments());
                    failMembers.add(importMemberVO);
                    failCount++;
                } else if (null != memberIdCard) {
                    ImportMemberVO importMemberVO = new ImportMemberVO();
                    BeanUtils.copyProperties(s, importMemberVO);
                    importMemberVO.setReason("身份证重复");
                    if (null != d && null != date) {
                        s.setInductionDate(d.format(date));
                    }
                    importMemberVO.setDepartments(s.getDepartments());
                    failMembers.add(importMemberVO);
                    failCount++;
                } else {
                    MemberDO memberDO1 = new MemberDO();
                    memberDO1.setUserName(s.getUserName());
                    memberDO1.setGender(s.getGender());
                    memberDO1.setEmail(s.getEmail());

                    String accountName = PinyinHelper.toHanYuPinyinString(s.getUserName(), format, "", true);
                    //查看人员目前所在公司是否有重名的情况
                    List<MemberDO> memberDOS = companyMemberMappingMapper.companyAccountMembers(companyId, accountName);

                    if (memberDOS.size() > 0) {
                        String usernames = userName(accountName, 0, companyId);
                        memberDO1.setAccountName(usernames.replace("u:", "v"));
                    } else {
                        memberDO1.setAccountName(accountName.replace("u:", "v"));
                    }

//                    memberDO1.setCompanyId(companyId);
                    memberDO1.setFirstLogin(0);
                    memberDO1.setTelephone(s.getTelephone());
                    memberDO1.setIdCard(s.getIdCard().toUpperCase());
                    memberDO1.setStatus("启用");
                    memberDO1.setPassword("Ykhl123456");
                    memberDO1.setAccountNameEn(s.getAccountNameEn());
                    memberMapper.insert(memberDO1);

                    //人和公司的映射
                    CompanyMemberMappingDO companyMemberMappingDO = new CompanyMemberMappingDO();
                    companyMemberMappingDO.setMemberId(memberDO1.getId());
                    companyMemberMappingDO.setCompanyId(companyId);
                    companyMemberMappingDO.setMemberStatus(1);
                    companyMemberMappingDO.setWorkNo(s.getWorkNo());
                    companyMemberMappingDO.setInductionDate(DateFormatUtil.format(new Date(), DateFormatUtil.FMT_sdf_yMd));
                    companyMemberMappingMapper.insert(companyMemberMappingDO);

                    successCount++;

                    //找到对应的部门
                    if (fullName.length > 0) {
                        for (String dep : fullName) {
                            DepartmentDictDO departmentDictDO = departmentDictMapper.selectOne(new QueryWrapper<DepartmentDictDO>()
                                    .lambda()
                                    .eq(DepartmentDictDO::getFullName, dep));
                            MemberDepartmentMappingDO memberDepartmentMappingDO = new MemberDepartmentMappingDO();
                            memberDepartmentMappingDO.setDepartmentId(departmentDictDO.getId());
                            memberDepartmentMappingDO.setMemberId(memberDO1.getId());
                            memberDepartmentMappingDO.setMemberStatus(1);
                            memberDepartmentMappingMapper.insert(memberDepartmentMappingDO);
                        }
                    }
                }
            } catch (Exception e) {
                ImportMemberVO importMemberVO = new ImportMemberVO();
                BeanUtils.copyProperties(s, importMemberVO);
                String DATE_PATTERN = "yyyy-MM-dd";
                SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy", Locale.US);
                if (null != s.getInductionDate()) {
                    Date date = sdf.parse(s.getInductionDate());
                    SimpleDateFormat d = new SimpleDateFormat(DATE_PATTERN);
                    importMemberVO.setInductionDate(d.format(date));
                }
                importMemberVO.setReason("其他原因");
                importMemberVO.setDepartments(s.getDepartments());
                failCount++;
                failMembers.add(importMemberVO);
            }
        }
        importMemberResultVO.setImportMemberVOS(failMembers);
        importMemberResultVO.setSuccessCount(successCount);
        importMemberResultVO.setFailCount(failCount);
        return importMemberResultVO;
    }

    public void downloadFailMembers(DownloadFailMembersDTO downloadFailMembersDTO) {
        List<ImportMemberVO> importMemberVOS = downloadFailMembersDTO.getImportMemberVOS();
        ExcelUtil.writeExcel(importMemberVOS, ImportMemberVO.class);
    }


    public String userName(String originName, int i, Long companyId) {
        i++;
        List<MemberDO> memberDOS = memberMapper.selectList(new QueryWrapper<MemberDO>()
                .lambda()
                .eq(MemberDO::getAccountName, originName + i));
        if (memberDOS.size() > 0) {
            return userName(originName, i, companyId);
        } else {
            return originName + i;
        }
    }

}