package com.infoepoch.pms.dispatchassistant.controller.basic;

import com.infoepoch.pms.dispatchassistant.common.component.Result;
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.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.basic.user.organizationRela.IUserOrganizationRelaRepository;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.organizationRela.UserOrganizationRela;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.organizationRela.UserOrganizationRelaCriteria;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.organizationRela.UserOrganizationRelaService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 用户组织关联关系
 */
@RestController
@RequestMapping("/user-organization-rela")
public class UserOrganizationRelaController {

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

    @Autowired
    private UserOrganizationRelaService service;

    @Autowired
    private IUserOrganizationRelaRepository repository;
    @Autowired
    private IUserRepository userRepository;
    @Autowired
    private IOrganizationRepository organizationRepository;

    private static boolean initAllFlag = false;

    /**
     * 初始化所有用户与组织的关联关系（通过接口表数据初始化）
     *
     * @return
     */
    @GetMapping("/init-all")
    public Result initAll() {
        if (initAllFlag) {
            throw new ValidationException("初始化正在执行中，请勿重复操作");
        }
        initAllFlag = true;
        try {
            service.updateUserOrganizationRelaAll();
        } catch (Exception e) {
            logger.info(e.getMessage());
            initAllFlag = false;
        } finally {
            initAllFlag = false;
        }
        return Result.success();
    }

    /**
     * 关联关系列表
     *
     * @param criteria
     * @return
     */
    @PostMapping("/list")
    public Result pageList(@RequestBody UserOrganizationRelaCriteria criteria) {
        Map<String, Object> resultMap = new HashMap<>();
        if (!criteria.byPage()) {
            throw new ValidationException("请设置分页参数");
        }
        List<UserOrganizationRela> list = repository.selectCriteriaByPage(criteria, criteria.getPageIndex(), criteria.getPageSize());
        fillListData(list);
        int totalCount = repository.selectCountByCriteria(criteria);
        resultMap.put("list", list);
        resultMap.put("totalCount", totalCount);
        return Result.successData(resultMap);
    }

    /**
     * 填充列表显示所需数据
     *
     * @param list
     */
    private void fillListData(List<UserOrganizationRela> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            Set<String> userIdSet = new HashSet<>();
            Set<String> orgIdSet = new HashSet<>();
            for (UserOrganizationRela entity : list) {
                userIdSet.add(entity.getUserId());
                orgIdSet.add(entity.getOrganizationId());
            }
            List<User> userList = new ArrayList<>();
            if (!userIdSet.isEmpty()) {
                UserCriteria userCriteria = new UserCriteria();
                userCriteria.setUserIds(new ArrayList<>(userIdSet));
                userList = userRepository.selectByCriteria(userCriteria);
            }
            Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
            List<Organization> organizationList = new ArrayList<>();
            if (!orgIdSet.isEmpty()) {
                OrganizationCriteria organizationCriteria = new OrganizationCriteria();
                organizationCriteria.setOrgIdList(new ArrayList<>(orgIdSet));
                organizationList = organizationRepository.selectByCriteria(organizationCriteria);
            }
            Map<String, Organization> organizationMap = organizationList.stream().collect(Collectors.toMap(Organization::getId, Function.identity()));
            for (UserOrganizationRela entity : list) {
                User user = userMap.get(entity.getUserId());
                if (user != null) {
                    entity.setName(user.getFullname());
                    entity.setUsername(user.getUsername());
                }
                Organization organization = organizationMap.get(entity.getOrganizationId());
                if (organization != null) {
                    entity.setOrganizationName(organization.getName());
                }
            }
        }
    }

    /**
     * 删除关联关系
     *
     * @param id
     * @return
     */
    @GetMapping("/remove/{id}")
    public Result remove(@PathVariable String id) {
        UserOrganizationRela old = repository.selectById(id);
        if (old == null)
            throw new ValidationException("该记录不存在");
        repository.delete(id);
        return Result.success();
    }

    /**
     * 保存
     *
     * @param entity
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody UserOrganizationRela entity) {
        entity.verify();
        if (StringUtils.isBlank(entity.getId())) {
            UserOrganizationRelaCriteria relaCriteria = new UserOrganizationRelaCriteria();
            relaCriteria.setUserId(entity.getUserId());
            List<UserOrganizationRela> list = repository.selectByCriteria(relaCriteria);
            boolean hasMajor = false;
            for (UserOrganizationRela rela : list) {
                if (rela.getMajorPositionFlag() != null && rela.getMajorPositionFlag()) {
                    hasMajor = true;
                }
            }
            if (hasMajor) {
                if (entity.getMajorPositionFlag() != null && entity.getMajorPositionFlag()) {
                    throw new ValidationException("该用户已存在主职岗位，请先修改主职岗位");
                }
            }
            entity.initializePk();
            repository.insert(entity);
        } else {
            UserOrganizationRelaCriteria relaCriteria = new UserOrganizationRelaCriteria();
            relaCriteria.setUserId(entity.getUserId());
            List<UserOrganizationRela> list = repository.selectByCriteria(relaCriteria);
            boolean hasMajor = false;
            for (UserOrganizationRela rela : list) {
                if (rela.getMajorPositionFlag() != null && rela.getMajorPositionFlag()) {
                    if (!rela.getId().equals(entity.getId())) {
                        hasMajor = true;
                    }
                }
            }
            if (hasMajor) {
                if (entity.getMajorPositionFlag() != null && entity.getMajorPositionFlag()) {
                    throw new ValidationException("该用户已存在主职岗位，请先修改主职岗位");
                }
            }
            entity.setRecordTime(new Date());
            repository.update(entity);
        }
        return Result.successData(entity);
    }

}
