package com.infoepoch.pms.dispatchassistant.domain.basic.user.organizationRela;

import com.infoepoch.pms.dispatchassistant.common.utils.LambdaTool;
import com.infoepoch.pms.dispatchassistant.common.utils.StringUtils;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.IOrganizationRepository;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.Organization;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.OrganizationCriteria;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.IUserRepository;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.User;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.UserCriteria;
import com.infoepoch.pms.dispatchassistant.domain.oa.user.IUserPmsRepository;
import com.infoepoch.pms.dispatchassistant.domain.oa.user.UserPms;
import com.infoepoch.pms.dispatchassistant.domain.oa.user.UserPmsCriteria;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserOrganizationRelaService {

    @Autowired
    private IUserOrganizationRelaRepository userOrganizationRelaRepository;
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private IUserPmsRepository userPmsRepository;
    @Autowired
    private IOrganizationRepository organizationRepository;

    /**
     * 根据OA用户接口表数据更新用户组织关联关系表
     */
    public void updateUserOrganizationRelaAll() {
        int totalCount = userRepository.selectByCriteriaCount(new UserCriteria());
        if (totalCount < 1000) {
            updateUserOrganizationRela(1, totalCount);
        } else {
            int pageSize = 1000;
            int remainder = totalCount % pageSize;
            int pageCount = totalCount / pageSize + (remainder > 0 ? 1 : 0);
            for (int i = 1; i <= pageCount; i++) {
                updateUserOrganizationRela(i, pageSize);
            }
        }
    }

    /**
     * 根据OA用户接口表数据更新用户组织关联关系表
     *
     * @param pageIndex
     * @param pageSize
     */
    private void updateUserOrganizationRela(int pageIndex, int pageSize) {
        UserCriteria userCriteria = new UserCriteria();
        userCriteria.setPageIndex(pageIndex);
        userCriteria.setPageSize(pageSize);
        List<User> userList = userRepository.selectByCriteriaPage(userCriteria, userCriteria.getPageIndex(), userCriteria.getPageSize());
        updateUserOrganizationRela(userList);
    }

    /**
     * 更新用户组织关联关系
     *
     * @param userList
     */
    private void updateUserOrganizationRela(List<User> userList) {
        if (CollectionUtils.isEmpty(userList))
            return;
        List<String> reference3List = userList.stream().map(User::getUsername).collect(Collectors.toList());
        UserPmsCriteria userPmsCriteria = new UserPmsCriteria();
        userPmsCriteria.setReference3List(reference3List);
        List<UserPms> userPmsList = userPmsRepository.selectByCriteria(userPmsCriteria);
        Map<String, List<UserPms>> userPmsListMap = LambdaTool.changeCollectionToHashListMap(userPmsList, UserPms::getReference3);
        Map<String, Organization> organizationMap = getOrganizationMap(userPmsList);
        List<UserOrganizationRela> userOrganizationRelaList = new ArrayList<>();
        userList.forEach(user -> {
            List<UserPms> list = userPmsListMap.get(user.getUsername());
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(userPms -> {
                    Organization organization = organizationMap.get(userPms.getOaOrgCode());
                    if (organization != null) {
                        String position = getUserPositionNumber(userPms.getDuty());
                        boolean majorPositionFlag = false;
                        if (StringUtils.isNotBlank(userPms.getReference8()) && userPms.getReference8().equals("P")) {
                            majorPositionFlag = true;
                        }
                        UserOrganizationRela userOrganizationRela = new UserOrganizationRela(
                                user.getId(),
                                organization.getId(),
                                position,
                                majorPositionFlag
                        );
                        userOrganizationRelaList.add(userOrganizationRela);
                    }
                });
            }
        });
        if (CollectionUtils.isNotEmpty(userOrganizationRelaList)) {
            List<String> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(userIdList)) {
                userOrganizationRelaRepository.deleteByUserIdList(userIdList);
            }
            userOrganizationRelaRepository.batchInsert(userOrganizationRelaList);
        }
    }

    /**
     * 更新用户组织关联关系
     *
     * @param user
     */
    public void updateUserOrganizationRela(User user) {
        if (user == null)
            return;
        List<UserPms> userPmsList = userPmsRepository.selectByReference3(user.getUsername());
        if (CollectionUtils.isEmpty(userPmsList))
            return;
        Map<String, Organization> organizationMap = getOrganizationMap(userPmsList);
        List<UserOrganizationRela> userOrganizationRelaList = new ArrayList<>();
        userPmsList.forEach(userPms -> {
            Organization organization = organizationMap.get(userPms.getOaOrgCode());
            if (organization != null) {
                String position = getUserPositionNumber(userPms.getDuty());
                boolean majorPositionFlag = false;
                if (StringUtils.isNotBlank(userPms.getReference8()) && userPms.getReference8().equals("P")) {
                    majorPositionFlag = true;
                }
                UserOrganizationRela userOrganizationRela = new UserOrganizationRela(
                        user.getId(),
                        organization.getId(),
                        position,
                        majorPositionFlag
                );
                userOrganizationRelaList.add(userOrganizationRela);
            }
        });
        if (CollectionUtils.isNotEmpty(userOrganizationRelaList)) {
            List<String> userIdList = Collections.singletonList(user.getId());
            if (CollectionUtils.isNotEmpty(userIdList)) {
                userOrganizationRelaRepository.deleteByUserIdList(userIdList);
            }
            userOrganizationRelaRepository.batchInsert(userOrganizationRelaList);
        }
    }

    /**
     * 获取组织MAP
     * KEY-OA组织编码 VALUE-组织对象
     *
     * @param userPmsList
     * @return
     */
    private Map<String, Organization> getOrganizationMap(List<UserPms> userPmsList) {
        Map<String, Organization> resultMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(userPmsList)) {
            List<String> oaOrgCodeList = userPmsList.stream().map(UserPms::getOaOrgCode).collect(Collectors.toList());
            OrganizationCriteria organizationCriteria = new OrganizationCriteria();
            organizationCriteria.setOaOrgCodeList(oaOrgCodeList);
            List<Organization> organizationList = organizationRepository.selectByCriteria(organizationCriteria);
            resultMap = LambdaTool.changeCollectionToHashMap(organizationList, Organization::getOaOrgCode);
        }
        return resultMap;
    }

    /**
     * 根据duty获取用户职位
     *
     * @param duty
     * @return
     */
    private String getUserPositionNumber(String duty) {
        if (StringUtils.isBlank(duty))
            return null;
        String[] arr = duty.split("-");
        return arr[arr.length - 1];
    }

}
