package com.chinaweal.aiccs.org.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chinaweal.aiccs.aiccs.abnormal.entity.Gzaiccode;
import com.chinaweal.aiccs.aiccs.abnormal.service.IGzaiccodeService;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.door.entity.TUserportal;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.entity.TUsers;
import com.chinaweal.aiccs.org.mapper.TUsersMapper;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aicorg.model.AICOrg;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-02-07
 */
@Service
public class TUsersServiceImpl extends BaseServiceImpl<TUsersMapper, TUsers> implements TUsersService {

    @Resource
    private TUsersMapper tUsersMapper;
    @Resource
    private OrgUM orgUM;
    @Resource
    @Lazy
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    private AicorgService aicorgService;

    @Override
    public void updateTusers(TUsers tUsers) {
        tUsersMapper.updateTusers(tUsers);
    }

    @Override
    public TUsers selectTusersByUsernameAndPass(String userName, String passwordJm) {
        return tUsersMapper.selectTusersByUsernameAndPass(userName, passwordJm);
    }

    @Override
    public TUsers selectTusersByUsername(String userName) {
        return tUsersMapper.selectTusersByUsername(userName);
    }

    @Override
    public TUsers selectTusersById(String intoSponsorId) {
        return tUsersMapper.selectTusersById(intoSponsorId);
    }

    @Override
    public OrgUnits byOrgUnitName(String orgUnitName) {
        OrgUnits orgUnits = tUsersMapper.byOrgUnitName(orgUnitName);
        return orgUnits;
    }

    @Override
    public OrgUnits byOrgUnitId(String s) {
        OrgUnits orgUnits = tUsersMapper.byOrgUnitId(s);
        return orgUnits;
    }

    @Override
    public List<OrgUnits> queryAllOrg() {
        return tUsersMapper.queryAllOrg();
    }

    @Override
    public List<OrgUnits> byNextLevelPlace(String orgUnitId) {
        List<OrgUnits> list = new ArrayList<>();
        //查询本级
        OrgUnits orgUnits = tUsersMapper.byOrgUnitId(orgUnitId);
        list.add(orgUnits);
        //获取下级所
        list.addAll(tUsersMapper.listOrgParentId(orgUnitId, String.valueOf(orgUnits.getOrgLevel() + 1)));
        return list;
    }

    @Override
    public List<AICUser> findUsersByDeptAndPermission(String orgUnitId, String permission) {
        return tUsersMapper.findUsersByDeptAndPermission(orgUnitId, permission);
    }

    @Override
    public List<AICUser> findUsersByUnitAndUnDepAndPermission(String orgUnitId,String orgDeptID, String permission) {
        return tUsersMapper.findUsersByUnitAndUnDepAndPermission(orgUnitId, orgDeptID, permission);
    }

    @Override
    public Gzaiccode findOrganization(String userId) {
        AICUser aicUser = orgUM.findUserByPrimaryKey(userId);
        //判断当前用户机关是不是直属区局或者市局,所级的，再查询上级区局
        OrgUnits orgUnits = tUsersMapper.byOrgUnitId(aicUser.getOrgID());
        if (!(orgUnits.getOrgLevel() == 2 || orgUnits.getOrgLevel() == 3)) {
            orgUnits = tUsersMapper.byOrgUnitId(orgUnits.getParentId());
        }
        if (orgUnits == null) {
            return null;
        }
        LambdaQueryWrapper<Gzaiccode> gLqw = Wrappers.lambdaQuery();
        gLqw.eq(Gzaiccode::getOrgunitid, orgUnits.getOrgUnitId());
        gLqw.in(Gzaiccode::getSlevel, "3", "4");
        gLqw.orderByAsc(Gzaiccode::getSlevel);
        List<Gzaiccode> list = iGzaiccodeService.list(gLqw);
        if (list.isEmpty()) {
            return null;
        }
        Gzaiccode gzaiccode = list.get(0);
        return gzaiccode;
    }

    @Override
    public String findOrgCode(String userId) {
        Gzaiccode gzaiccode = findOrganization(userId);
        return gzaiccode.getScountrycode();
    }

    @Override
    public List<AICUser> findUserByPermissionAndOrgIds(String permission, String orgId, Boolean isArea,AICUser loginUser) {
        List<AICUser> userList = new ArrayList<>();
        permission = null;
        //获取当前部门的权限列表人
        List<AICUser> currList = aicorgService.getUsersByOrgAndPermission(permission,orgId);
//        //判断是否需要获取区局权限
//        if (isArea!=null && isArea) {
//            try {
//                AICOrg parentOrgByPK = aicorgService.toAICOrg(aicorgService.findParentOrgByPK(orgId));
//                if (parentOrgByPK != null) {
//                    OrgUnits orgUnits = tUsersMapper.byOrgUnitId(parentOrgByPK.getPrimaryKey());
//                    if (orgUnits != null && 3 == orgUnits.getOrgLevel()) {
//                        //父级是区局的查询出来
//                        userList = orgUM.findUsersByOrgAndPermission(parentOrgByPK.getPrimaryKey(), permission);
//                    }
//                }
//            }catch (Exception e){
//                log.error(e.getMessage());
//            }
//        }
        if (currList != null) {
            userList.addAll(currList);
            userList.forEach(each -> each.setPassword(null));
        }
        Collections.reverse(userList);
        return userList;
    }

    @Override
    public TUsers saveDoorUser(TUserportal tUserportal) {
        //插入用户，把用户自动新增的用户放在一个门户专属组里面，并且是没有权限的
        TUsers newUser = new TUsers();
        newUser.setUserid(UUID.randomUUID().toString());
        newUser.setUsername(tUserportal.getUsername());
        newUser.setRealname(tUserportal.getRealname());
        newUser.setPassword("C45D3989C0A5FA71");
        newUser.setLocked("0");
        newUser.setDeleted("0");
        newUser.setOrgunitid("001");
        newUser.setOrgdeptid("2bdb108a-8642-46c0-939d-7ed01c3b152a");
        newUser.setUserprop(99);
        newUser.setUserstatus("1");
        this.save(newUser);

        return newUser;
    }

    @Override
    public List<TUsers> listByUserIds(String[] userIds) {
        return this.lambdaQuery().in(TUsers::getUserid, userIds).list();
    }

    @Override
    public AICUser toAICUser(TUsers user) {
        if (user == null) {
            return null;
        }
        AICUser result = new AICUser();
        result.setUserProp(user.getUserprop());
        result.setOrgID(user.getOrgunitid());
        result.setUnitID(user.getOrgdeptid());
        result.setName(user.getRealname());
        result.setEname(user.getUsername());
        result.setPassword(user.getPassword());
        result.setPrimaryKey(user.getUserid());
        Set<String> idList = new HashSet<>();
        if (StringUtils.isNotBlank(user.getOrgunitid())) {
            idList.add(user.getOrgunitid());
        }
        if (StringUtils.isNotBlank(user.getOrgdeptid())) {
            idList.add(user.getOrgdeptid());
        }
        if (CollectionUtils.isNotEmpty(idList)) {
            List<OrgUnits> tOrgUnits = aicorgService.listByIds(idList);
            for (OrgUnits each : tOrgUnits) {
                if (each.getOrgUnitId().equals(result.getOrgID())) {
                    result.setOrgName(each.getOrgUnitName());
                    result.setRegionID(each.getOrgNumber());
                }
                if (each.getOrgUnitId().equals(result.getUnitID())) {
                    result.setUnitName(each.getOrgUnitName());
                }
            }
        }
        return result;
    }

    @Override
    public AICUser getUserById(String userId) {
        return baseMapper.selectUserById(userId);
    }

}
