package com.example.removetolocal.service.impl;

import com.example.removetolocal.newuser.dao.*;
import com.example.removetolocal.newuser.domin.*;
import com.example.removetolocal.olddevice.dao.DevAcrossunitDao;
import com.example.removetolocal.olddevice.domin.DevAcrossunit;
import com.example.removetolocal.olduser.dao.*;
import com.example.removetolocal.olduser.domin.*;
import com.example.removetolocal.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    DevAreaDao devAreaDao;
    @Autowired
    DevManagerDao devManagerDao;
    @Autowired
    DevMgrcertDao devMgrcertDao;
    @Autowired
    SysCompanyDao sysCompanyDao;
    @Autowired
    SysUserDao sysUserDao;
    @Autowired
    UserDao userDao;
    @Autowired
    UnitsDao unitsDao;
    @Autowired
    MgrcertDao mgrcertDao;
    @Autowired
    AreaDao areaDao;
    @Autowired
    DevAcrossunitDao devAcrossunitDao;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    UserRoleDao userRoleDao;
    /**
     * 区域、部门、用户
     */
    @Override
    public void changeEntity() {
        //转换区域
        //找到最高级
        DevAreaEntity devAreaEntity = devAreaDao.findByPid("0");
        //浙江省
        DevAreaEntity devAreaEntity1 = devAreaDao.findByPid(devAreaEntity.getId());
        Area area = new Area();
        area.setName(devAreaEntity1.getAreaname());
        area.setOrders(String.valueOf(devAreaEntity1.getShoworder()));
        area.setOldId(devAreaEntity1.getId());
        area.setType(devAreaEntity1.getLevel());
        Area area1 = areaDao.save(area);
        Integer fatherId = area1.getId();
        changeUnitsByArea(devAreaEntity1.getId(),fatherId);
        setAcrossUnit();
//        setAcrossUser();
        changeByFatherArea(devAreaEntity1.getId(),fatherId);
    }

    @Override
    public User getUserByOldId(String oldId) {
        if (checkcountname(oldId)){
            return null;
        }
        else {
            return userDao.findByOldCode(oldId) == null ? userDao.findByOldId(oldId) : userDao.findByOldCode(oldId);
        }
    }

    @Override
    public String getUserNameByOldId(String oldId) {
        if (checkcountname(oldId)){
            return oldId;
        }
        else {
            return sysUserDao.findById(oldId).isPresent() ? sysUserDao.findById(oldId).get().getUserName() : devManagerDao.findAllById(oldId).get(0).getUsername();
        }
    }

    @Override
    public String getUnitNameByOldId(String oldId) {
        if (sysCompanyDao.findById(oldId).isPresent()) {
            return sysCompanyDao.findById(oldId).get().getCompanyName();
        }
        else {
            return devAcrossunitDao.findById(oldId).get().getUnitname();
        }
    }

    @Override
    public Units getUnitByOldId(String oldId) {
       return unitsDao.findByOldId(oldId);
    }

    /**
     * 重制用户的密码
     */
    @Override
    public void updateUserPass() {
        String encode = bCryptPasswordEncoder.encode("qwer1234");
        List<User> users=  userDao.findAll();
        users.forEach(
                user -> {
                    if (user.getUnitsId()>0) {
                        user.setPassword(encode);
                        user.setNoPassword("qwer1234");
                    }
                }
        );
        userDao.saveAll(users);
    }

    /**
     * 绑定用户角色
     */
    @Override
    public void setUserRole() {
        userDao.findAll().forEach(user -> {
            if (userRoleDao.findByUserId(user.getUserId())==null&&user.getUnitsId()!=0){
                Integer level = unitsDao.findById(user.getUnitsId()).get().getLevel();
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getUserId());
                userRole.setRoleId(level);
                userRoleDao.save(userRole);
            }
        });
    }

    /**
     * @param oldFatherId 旧表父类Id
     * @param newFatherId 新表父类id
     * 递归转换父类旗下所有区域
     */
    void changeByFatherArea(String oldFatherId,Integer newFatherId){
        List<DevAreaEntity> devAreaEntityList = devAreaDao.findAllByPid(oldFatherId);
        if (devAreaEntityList.size()>0){
            devAreaEntityList.forEach(areaEntity -> {
                Area area2 = new Area();
                area2.setName(areaEntity.getAreaname());
                area2.setOrders(String.valueOf(areaEntity.getShoworder()));
                area2.setOldId(areaEntity.getId());
                area2.setType(areaEntity.getLevel());
                area2.setFatherId(newFatherId);
                Area area = areaDao.save(area2);
                changeByFatherArea(areaEntity.getId(),area.getId());
                changeUnitsByArea(areaEntity.getId(),area.getId());
            });
        }
    }

    /**
     * @param oldAreaId 旧表区域Id
     * @param newAreaId 新表区域Id
     * 转换区域下所有单位
     */
    void changeUnitsByArea(String oldAreaId,Integer newAreaId){
        List<SysCompanyEntity> sysCompanyEntities = sysCompanyDao.findAllByAreaId(oldAreaId);
        if (sysCompanyEntities.size()>0){
            sysCompanyEntities.forEach(sysCompanyEntity -> {
                Units units = new Units();
                units.setName(sysCompanyEntity.getCompanyName());
                units.setUnitDesc(sysCompanyEntity.getCompanyDesc());
                units.setLevel(sysCompanyEntity.getLevel());
                units.setIdDel(sysCompanyEntity.getIsdel());
                units.setCode(sysCompanyEntity.getCode());
                units.setOldId(sysCompanyEntity.getCompanyId());
                units.setType(1);
                units.setAreaId(1);
                units.setShowOrder(sysCompanyEntity.getShoworder().intValue());
                if (sysCompanyEntity.getLevel()==2) {
                    units.setAreaId(newAreaId);
                }
                else if (sysCompanyEntity.getLevel()==1) {
                    units.setAreaId(1);
                }
                //区县
                else if (sysCompanyEntity.getLevel()==3){
                    //添加新区域
                    Area area = new Area();
                    area.setType(3);
                    area.setOrders(String.valueOf(sysCompanyEntity.getShoworder()));
                    area.setFatherId(newAreaId);
                    area.setName(sysCompanyEntity.getCompanyName().substring(0,3));
                    Area area1 = areaDao.save(area);
                    units.setAreaId(area1.getId());
                }
                Units units1 = unitsDao.save(units);
                changeUsersByUnit(sysCompanyEntity.getCompanyId(), units1.getUnitId());
            });
        }
    }

    /**
     * 迁移非系统单位
     */
    void setAcrossUnit(){
        List<SysCompanyEntity> sysCompanyEntities = sysCompanyDao.findAllByLevel(0);
        if (sysCompanyEntities.size()>0){
            sysCompanyEntities.forEach(sysCompanyEntity -> {
                Units units = new Units();
                units.setName(sysCompanyEntity.getCompanyName());
                units.setUnitDesc(sysCompanyEntity.getCompanyDesc());
                units.setLevel(0);
                units.setIdDel(sysCompanyEntity.getIsdel());
                units.setCode(sysCompanyEntity.getCode());
                units.setOldId(sysCompanyEntity.getCompanyId());
                units.setAreaId(0);
                units.setType(3);
                units.setShowOrder(sysCompanyEntity.getShoworder().intValue());
                Units units1 = unitsDao.save(units);
                changeUsersByUnit(sysCompanyEntity.getCompanyId(), units1.getUnitId());
            });
        }
        List<DevAcrossunit> devAcrossunits = devAcrossunitDao.findAll();
        if (devAcrossunits.size()>0){
            devAcrossunits.forEach(devAcrossunit -> {
                List<String> unitNames = Arrays.asList("省机科技处设备部分","省机通信报务处");
                Boolean isSpecialUnit = unitNames.contains(devAcrossunit.getUnitname());
                Units units = new Units();
                units.setName(devAcrossunit.getUnitname());
                units.setUnitDesc(devAcrossunit.getUnitname());
                if (isSpecialUnit){
                    units.setLevel(3);
                    units.setType(1);
                }
                else {
                    units.setLevel(4);
                    units.setType(2);
                }
                units.setIdDel(0);
                units.setOldId(devAcrossunit.getId());
                units.setAreaId(0);
                units.setShowOrder(devAcrossunit.getShoworder().intValue());
                unitsDao.save(units);
            });
        }
    }

    /**
     * 迁移非系统用户
     */
    void setAcrossUser(){
        List<DevManagerEntity> devManagerEntities = devManagerDao.findAll().stream()
                .filter(devManagerEntity -> sysUserDao.findAllByCode(devManagerEntity.getId()).isEmpty())
                .collect(Collectors.toList());
        devManagerEntities.forEach(devManagerEntity -> {
            User user = new User();
            user.setName(devManagerEntity.getUsername());
            user.setOldCode(devManagerEntity.getId());
            user.setSex(devManagerEntity.getSex());
            user.setMobile(devManagerEntity.getMobile());
            user.setTelphone(devManagerEntity.getTel());
            if (devManagerEntity.getShoworder()!=null) {
                user.setShowOrder(devManagerEntity.getShoworder().intValue());
            }
            user.setPosition(1);
            user.setTrainStatus(5);
            user.setUnitsId(0);
            if (devManagerEntity.getIsLock()==1&&devManagerEntity.getStatus()==0){
                user.setIsDel(1);
            }
            userDao.save(user);
        });
    }


    /**
     * @param oldUnitId 旧表单位Id
     * @param newUnitId 新表单位Id
     * 转换单位下所有专管员及证书
     */
    void changeUsersByUnit(String oldUnitId,Integer newUnitId){
        List<SysUserEntity> sysUserEntities = sysUserDao.findAllByCompanyId(oldUnitId);
        if (sysUserEntities.size()>0){
            sysUserEntities.forEach(sysUserEntity -> {
                User user = new User();
                List<DevManagerEntity> devManagerEntities = devManagerDao.findAllById(sysUserEntity.getCode()).stream().sorted(Comparator.comparing(DevManagerEntity::getCreateTime,Comparator.nullsLast(Date::compareTo)).reversed()).collect(Collectors.toList());
                if (sysUserEntity.getLoginid()!=null&&!"".equals(sysUserEntity.getLoginid())) {
                    if (sysUserEntity.getCode() != null && !devManagerEntities.isEmpty()) {
                        DevManagerEntity devManagerEntity = devManagerEntities.get(0);
                        user.setName(sysUserEntity.getUserName());
                        user.setPassword("123456");
                        user.setNoPassword("123456");
                        user.setUsername(sysUserEntity.getLoginid());
                        user.setShowOrder(sysUserEntity.getShoworder().intValue());
                        user.setMobile(devManagerEntity.getMobile());
                        user.setTelphone(devManagerEntity.getTel());
                        user.setEmail(sysUserEntity.getEmail());
                        user.setFax(sysUserEntity.getFax());
                        user.setIsDel(sysUserEntity.getIsdel());
                        if (devManagerEntity.getStatus() == 0 || devManagerEntity.getStatus() == 4) {
                            user.setIsDel(1);
                        }
                        user.setIdCard(sysUserEntity.getIdcardno());
                        user.setSex(sysUserEntity.getSex());
                        user.setUnitsId(newUnitId);
                        user.setPosition(1);
                        user.setOldId(sysUserEntity.getUserId());
                        user.setOldCode(devManagerEntity.getId());
                    } else {
                        user.setName(sysUserEntity.getUserName());
                        user.setPassword("123456");
                        user.setNoPassword("123456");
                        user.setUsername(sysUserEntity.getLoginid());
                        if (sysUserEntity.getShoworder() != null) {
                            user.setShowOrder(sysUserEntity.getShoworder().intValue());
                        }
                        user.setMobile(sysUserEntity.getMobile());
                        user.setTelphone(sysUserEntity.getTelphone());
                        user.setEmail(sysUserEntity.getEmail());
                        user.setFax(sysUserEntity.getFax());
                        user.setIsDel(sysUserEntity.getIsdel());
                        user.setIdCard(sysUserEntity.getIdcardno());
                        user.setSex(sysUserEntity.getSex());
                        user.setUnitsId(newUnitId);
                        user.setPosition(1);
                        user.setOldId(sysUserEntity.getUserId());
                        user.setOldCode("0");
                    }
                    User user1 = userDao.save(user);
                    List<DevMgrcertEntity> devMgrcertEntities = new ArrayList<>();
                    devMgrcertEntities.addAll(devMgrcertDao.findAllByCertMgr(String.valueOf(user1.getOldCode())));
                    devMgrcertEntities.addAll(devMgrcertDao.findAllByCertMgr(String.valueOf(user1.getOldId())));
                    if (devMgrcertEntities.size() > 0) {
                        DevMgrcertEntity devMgrcertEntity = devMgrcertEntities.get(0);
                        user1.setTrainStatus(0);
                        userDao.save(user1);
                        Mgrcert mgrcert = new Mgrcert();
                        mgrcert.setCertName(devMgrcertEntity.getName());
                        mgrcert.setUserId(user1.getUserId());
                        mgrcert.setCertNum(devMgrcertEntity.getCertNum());
                        mgrcert.setIssueDate(devMgrcertEntity.getIssueDate());
                        mgrcert.setExpiryDate(devMgrcertEntity.getExpiryDate());
                        mgrcert.setIsExpiry(devMgrcertEntity.getIsExpiry());
                        mgrcert.setName(user1.getName());
                        mgrcert.setOldId(devMgrcertEntity.getId());
                        mgrcertDao.save(mgrcert);
                    } else {
                        user1.setTrainStatus(2);
                        userDao.save(user1);
                    }
                }
            });
        }
    }

    public boolean checkcountname(String countname){
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(countname);
        if (m.find()) {
            return true;
        }
        return false;
    }
}
