package com.yeejoin.amos.boot.module.jyjc.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.module.common.api.enums.UserPostEnum;
import com.yeejoin.amos.boot.module.jyjc.api.common.BizCommonConstant;
import com.yeejoin.amos.boot.module.jyjc.api.entity.JyjcInspectionApplication;
import com.yeejoin.amos.boot.module.jyjc.api.model.JyjcInspectionApplicationModel;
import com.yeejoin.amos.boot.module.ymt.api.entity.TzsUserInfo;
import com.yeejoin.amos.boot.module.ymt.api.mapper.TzsUserInfoMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;

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

/**
 * @author Administrator
 */
@Service
@RequiredArgsConstructor
public class InspectionChargePersonServiceImpl {

    private final JyjcInspectionApplicationServiceImpl inspectionApplicationService;

    private final TzsUserInfoMapper userInfoMapper;

    private final DataDictionaryServiceImpl iDataDictionaryService;

    public JyjcInspectionApplicationModel saveChargePersonData(String applicationSeq, JyjcInspectionApplicationModel model) {
        LambdaUpdateWrapper<JyjcInspectionApplication> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(JyjcInspectionApplication::getInspectionChargePerson, model.getInspectionChargePerson());
        updateWrapper.set(JyjcInspectionApplication::getRemark2, model.getRemark2());
        updateWrapper.eq(BaseEntity::getSequenceNbr, applicationSeq);
        inspectionApplicationService.update(updateWrapper);
        return model;
    }

    public List<TzsUserInfo> getUserList(ReginParams reginParams) {
        LambdaQueryWrapper<TzsUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TzsUserInfo::getUnitCode, reginParams.getCompany().getCompanyCode());
        queryWrapper.eq(com.yeejoin.amos.boot.biz.common.entity.BaseEntity::getIsDelete, false);
        // 业务负责人
        queryWrapper.like(TzsUserInfo::getNewPost, UserPostEnum.YWFZR.getCode());
        queryWrapper.isNotNull(TzsUserInfo::getAmosUserId);
        queryWrapper.select(com.yeejoin.amos.boot.biz.common.entity.BaseEntity::getSequenceNbr, TzsUserInfo::getAmosUserId, TzsUserInfo::getName);
        List<TzsUserInfo> userInfos = userInfoMapper.selectList(queryWrapper);
        if (userInfos.stream().noneMatch(u -> u.getAmosUserId().equals(RequestContext.getExeUserId()))) {
            // 企业注册的人没在业务人员表存，但是如果登录人是业务负责人，则也需要显示，通过判断登录人的角色信息进行判断
            Set<Long> roleSeqs = reginParams.getUserModel().getOrgRoleSeqs().values().stream().flatMap(List::stream).collect(Collectors.toSet());
            Set<Long> ywfzrRoleIds = getRoleIds();
            if (roleSeqs.stream().anyMatch(ywfzrRoleIds::contains)) {
                TzsUserInfo userInfo = new TzsUserInfo();
                userInfo.setAmosUserId(RequestContext.getExeUserId());
                userInfo.setName(reginParams.getUserModel().getRealName());
                userInfos.add(userInfo);
            }
        }
        return userInfos;
    }

    /**
     * 查询业务负责人角色id
     *
     * @return 业务负责人角色ids
     */
    private Set<Long> getRoleIds() {
        // 角色id维护到字典extend字段，多个用逗号分隔（不再写死的代码，便于调整）
        List<DataDictionary> dataDictionaries = iDataDictionaryService.getByType(BizCommonConstant.YWFZR_DICT_TYPE);
        Map<String, List<Long>> bizTypeRoleMap = dataDictionaries.stream().collect(Collectors.toMap(DataDictionary::getCode,
                d -> Arrays.stream(d.getExtend().split(",")).map(Long::parseLong).collect(Collectors.toList())));
        Set<Long> roleIds = new HashSet<>();
        roleIds.addAll(bizTypeRoleMap.get(BizCommonConstant.BIZ_TYPE_JC));
        roleIds.addAll(bizTypeRoleMap.get(BizCommonConstant.BIZ_TYPE_JY));
        roleIds.remove(null);
        return roleIds;
    }
}
