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

import com.infoepoch.pms.dispatchassistant.common.component.SnowFlake;
import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
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.role.IRoleRepository;
import com.infoepoch.pms.dispatchassistant.domain.basic.role.IUserRoleRepository;
import com.infoepoch.pms.dispatchassistant.domain.basic.role.Role;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.organizationRela.UserOrganizationRelaService;
import com.infoepoch.pms.dispatchassistant.domain.oa.account.SBMDMMDMPageInquiryOAStandardEmpolyeeInfoSrvOutputItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class UserSyncService {

    private final static Logger logger = LoggerFactory.getLogger(UserSyncService.class);

    @Autowired
    private UserOrganizationRelaService userOrganizationRelaService;

    @Autowired
    private IOrganizationRepository organizationRepository;
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private IRoleRepository roleRepository;
    @Autowired
    private IUserRoleRepository userRoleRepository;


    /**
     * 单个用户同步（根据员工编码同步用户信息）
     *
     * @param itemList
     */
    public void userSyncForPmsSingle(List<SBMDMMDMPageInquiryOAStandardEmpolyeeInfoSrvOutputItem> itemList) {
        if (itemList == null) {
            logger.info("[1001]员工信息为空");
            return;
        }
        // 获取单个用户的用户名（列表中的用户名均一致）
        String username = itemList.get(0).getREFERENCE3();
        User old = userRepository.selectByUsername(username);
        if (old == null) {
            SBMDMMDMPageInquiryOAStandardEmpolyeeInfoSrvOutputItem item = itemList.get(0);
            User user = transferItemToUser(item);
            if (filterUser(user)) {
                // 新增员工需要插入相应的角色关联关系
                addUserRole(Collections.singletonList(user));
                userRepository.insert(user);
                userRepository.setDefaultPassword("info_epoch");
                // 更新用户组织关联关系表
                userOrganizationRelaService.updateUserOrganizationRela(user);
            }
        } else {
            User user = null;
            if (itemList.size() == 1) {
                SBMDMMDMPageInquiryOAStandardEmpolyeeInfoSrvOutputItem item = itemList.get(0);
                user = transferItemToUser(item);
            } else if (itemList.size() > 1) {
                Organization oldOrg = organizationRepository.selectById(old.getOrganizationId());
                for (SBMDMMDMPageInquiryOAStandardEmpolyeeInfoSrvOutputItem item : itemList) {
                    if (oldOrg != null && oldOrg.getOaOrgCode().equals(item.getOAORGCODE())) {
                        user = transferItemToUser(item);
                        break;
                    }
                }
                if (user == null) {
                    SBMDMMDMPageInquiryOAStandardEmpolyeeInfoSrvOutputItem item = itemList.get(0);
                    user = transferItemToUser(item);
                }
            }
            if (user != null && filterUser(user)) {
                old.modify(
                        user.getOrganizationId(),
                        user.getType(),
                        user.getPosition(),
                        user.getDisplayOrder(),
                        user.getUsername(),
                        user.getFullname(),
                        user.getSex(),
                        user.getMobile(),
                        user.getEmail(),
                        user.isDisabled(),
                        user.getJobNumber(),
                        user.getOrgConfirmStatus()
                );
                userRepository.update(old);
                // 更新用户组织关联关系表
                userOrganizationRelaService.updateUserOrganizationRela(old);
            }
        }
    }

    /**
     * 接口数据转换为用户
     *
     * @param item
     * @return
     */
    private User transferItemToUser(SBMDMMDMPageInquiryOAStandardEmpolyeeInfoSrvOutputItem item) {
        Organization organization = organizationRepository.selectByOaOrgCode(item.getOAORGCODE());
        return new User(
                organization == null ? null : organization.getId(),
                "Y".equals(item.getREFERENCE5()) ? UserType.LEADER : UserType.NORMAL,
                item.getDUTY(),
                item.getDISPLAYORDER(),
                null,
                item.getREFERENCE3(),
                item.getFULLNAME(),
                "男".equals(item.getSEX()) ? "0" : "1",
                item.getMOBILENUMBER(),
                item.getEMAIL(),
                !("0".equals(item.getREFERENCE6())),
                null,
                item.getREFERENCE7()
        );
    }

    /**
     * 过滤指定用户
     *
     * @param user
     * @return
     */
    private boolean filterUser(User user) {
        boolean flag = true;
        Organization organization = organizationRepository.selectById(user.getOrganizationId());
        if (organization == null) {
            flag = false;
        } else if ("00230081000000000000".equals(organization.getOaOrgCode())) {
            flag = false;
        }
        return flag;
    }

    /**
     * 添加用户角色
     *
     * @param userList
     */
    private void addUserRole(List<User> userList) {
        List<String> commonUserIdList = new ArrayList<>();
        List<String> courseCheckerIdList = new ArrayList<>();
        List<String> departmentLeaderIdList = new ArrayList<>();
        List<String> ids=new ArrayList<>();
        List<String> courseCheckerIds=new ArrayList<>();
        List<String> commonUserIds=new ArrayList<>();
        for (User user : userList) {
            // 所有账号默认绑定员工角色
            commonUserIdList.add(user.getId());
            commonUserIds.add(String.valueOf(SnowFlake.instant().nextId()));
            String positionNumber = getUserPositionNumber(user.getPosition());
            if (StringUtils.isBlank(positionNumber)) {
                continue;
            }
            switch (positionNumber) {
                case "JS0053":
                case "JS0052":
                    departmentLeaderIdList.add(user.getId());
                    ids.add(String.valueOf(SnowFlake.instant().nextId()));
                    break;
                case "JS0055":
                case "JS0056":
                    courseCheckerIdList.add(user.getId());
                    courseCheckerIds.add(String.valueOf(SnowFlake.instant().nextId()));
                    break;
                case "JS0054":
//                    commonUserIdList.add(user.getId());
                    break;
                default:
//                    commonUserIdList.add(user.getId());
                    break;
            }
        }
        try {
            Role role = roleRepository.selectByRoleName("部门领导");
            if (role == null) {
                throw new ValidationException("未查询到角色【部门领导】");
            }
            userRoleRepository.batchInsert(ids,role.getId(), departmentLeaderIdList);
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        try {
            Role role = roleRepository.selectByRoleName("课程审核员");
            if (role == null) {
                throw new ValidationException("未查询到角色【课程审核员】");
            }
            userRoleRepository.batchInsert(courseCheckerIds,role.getId(), courseCheckerIdList);
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        try {
            Role role = roleRepository.selectByRoleName("普通员工");
            if (role == null) {
                throw new ValidationException("未查询到角色【普通员工】");
            }
            userRoleRepository.batchInsert(commonUserIds,role.getId(), commonUserIdList);
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
    }

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


}
