package com.ruoyi.system.service.impl;


import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.ProposalInfo;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.activity.ZxActivity;
import com.ruoyi.system.domain.activity.ZxActivityUser;
import com.ruoyi.system.domain.assessment.ZxAssessment;
import com.ruoyi.system.domain.bonus.ZxBonus;
import com.ruoyi.system.domain.conference.ZxConference;
import com.ruoyi.system.domain.conference.ZxConferenceUser;
import com.ruoyi.system.domain.member.MemberAssessmentInfo;
import com.ruoyi.system.domain.member.MemberInfo;
import com.ruoyi.system.domain.member.MemberInfoTree;
import com.ruoyi.system.domain.speak.ZxSpeak;
import com.ruoyi.system.domain.sqmy.SqmyInfo;
import com.ruoyi.system.domain.vo.MemberInfoVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IMemberInfoService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.CommonConstants.*;
import static java.math.BigInteger.ZERO;

/**
 * 委员信息Service业务层处理
 *
 * @author boman
 * @date 2024-03-07
 */
@Service
public class MemberInfoServiceImpl implements IMemberInfoService {
    @Autowired
    private MemberInfoMapper memberInfoMapper;
    @Autowired
    private ZxConferenceMapper zxConferenceMapper;
    @Autowired
    private ZxActivityMapper zxActivityMapper;
    @Autowired
    private ZxSpeakMapper zxSpeakMapper;

    @Autowired
    private ProposalInfoMapper proposalInfoMapper;

    @Autowired
    private SqmyInfoMapper sqmyInfoMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private ZxAssessmentMapper zxAssessmentMapper;
    @Autowired
    private ZxBonusMapper zxBonusMapper;

    @Autowired
    private MemberAssessmentInfoMapper memberAssessmentInfoMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private SysUserRoleMapper userRoleMapper;


    /**
     * 查询委员信息
     *
     * @param memberId 委员信息主键
     * @return 委员信息
     */
    @Override
    public MemberInfo selectMemberInfoByMemberId(Long memberId) {
        return memberInfoMapper.selectMemberInfoByMemberId(memberId);
    }

    /**
     * 获取委员履职信息详细信息
     */
    @Override
    public MemberInfoVo getInfoJop(MemberInfo memberInfos) {
        MemberInfoVo memberInfoVo = new MemberInfoVo();
        Long userId = memberInfos.getUserId();
        Long memberId = memberInfos.getMemberId();
        MemberInfo memberInfo = memberInfoMapper.selectMemberInfoByMemberId(memberId);
        memberInfoVo.setMemberInfo(memberInfo);
        ZxConference zxConference = new ZxConference();
        zxConference.setUserId(userId);
        List<ZxConference> zxConferences = zxConferenceMapper.selectZxConferenceList(zxConference);
        if (zxConferences != null) {
            memberInfoVo.setZxConferenceList(zxConferences);
        }
        ZxActivity zxActivity = new ZxActivity();
        zxActivity.setUserId(userId);
        List<ZxActivity> zxActivities = zxActivityMapper.selectZxActivityList(zxActivity);
        if (zxActivities != null) {
            memberInfoVo.setZxActivityList(zxActivities);
        }
        ZxSpeak zxSpeak = new ZxSpeak();
        zxSpeak.setUserId(userId);
        List<ZxSpeak> zxSpeaks = zxSpeakMapper.selectZxSpeakList(zxSpeak);
        if (zxSpeaks != null) {
            memberInfoVo.setZxSpeakList(zxSpeaks);
        }
        return memberInfoVo;
    }

    /**
     * 获取委员履职年度报告
     */
    @Override
    public MemberInfoVo getMemberReport(MemberInfo memberInfo) {
        MemberInfoVo memberInfoVo = new MemberInfoVo();
        //查询的年份
        String year = memberInfo.getYear();
        //查询出委员信息
        Long userId = memberInfo.getUserId();
        MemberInfo memberInfoSelect = memberInfoMapper.selectMemberInfoByUserId(memberInfo.getUserId());
        memberInfoVo.setMemberInfo(memberInfoSelect);
        //履职状况初始化
        Map<String, Object> map = new HashMap<>(5);
        //提案
        map.put("proposalInfoNum", 0);
        //社情民意
        map.put("sqmyInfoNum", 0);
        //会议
        map.put("conferenceNum", 0);
        //全会
        map.put("plenarySessionNum", 0);
        //活动
        map.put("activityNum", 0);
        //发言数量
        map.put("speakNum", 0);
        //查询提案情况
        ProposalInfo proposalInfo = new ProposalInfo();
        proposalInfo.setProposalUserId(userId);
        proposalInfo.setYear(year);
        List<ProposalInfo> proposalInfos = proposalInfoMapper.selectProposalInfoListByUser(proposalInfo);
        memberInfoVo.setProposalInfoList(proposalInfos);
        if (proposalInfos != null && proposalInfos.size() >0){
            map.put("proposalInfoNum", proposalInfos.size());
        }
        //查询社情民意
        SqmyInfo sqmyInfo = new SqmyInfo();
        sqmyInfo.setSqmyUserId(userId);
        sqmyInfo.setYear(year);
        List<SqmyInfo> sqmyInfos = sqmyInfoMapper.selectSqmyInfoList(sqmyInfo);
        memberInfoVo.setSqmyInfoList(sqmyInfos);
        if (sqmyInfos != null && sqmyInfos.size() >0){
            map.put("sqmyInfoNum", sqmyInfos.size());
        }

        //查询政协会议
        ZxConference zxConference = new ZxConference();
        zxConference.setUserId(userId);
        zxConference.setYear(year);
        List<ZxConference> zxConferences = zxConferenceMapper.selectZxConferenceList(zxConference);
        memberInfoVo.setZxConferenceList(zxConferences);
        if (zxConferences != null && zxConferences.size() > 0){
            long count = zxConferences.stream().filter(e -> e.getConferenceType().equals(ONE)).count();
            map.put("plenarySessionNum", count);
        }
        //查询活动
        ZxActivity zxActivity = new ZxActivity();
        zxActivity.setUserId(userId);
        zxActivity.setYear(year);
        List<ZxActivity> zxActivities = zxActivityMapper.selectZxActivityList(zxActivity);
        memberInfoVo.setZxActivityList(zxActivities);
        if (zxActivities != null && zxActivities.size() >0){
            map.put("activityNum", zxActivities.size());
        }

        //查询发言不计算分
        ZxSpeak zxSpeak = new ZxSpeak();
        zxSpeak.setUserId(userId);
        zxSpeak.setYear(year);
        List<ZxSpeak> zxSpeaks = zxSpeakMapper.selectZxSpeakList(zxSpeak);
        memberInfoVo.setZxSpeakList(zxSpeaks);
        if (zxSpeaks != null && zxSpeaks.size() >0){
            map.put("speakNum", zxSpeaks.size());
        }
        //查询委员得分和排名
        MemberAssessmentInfo memberAssessmentInfo = new MemberAssessmentInfo();
        memberAssessmentInfo.setUserId(userId);
        memberAssessmentInfo.setYear(year);
        List<MemberAssessmentInfo> memberAssessmentInfos = memberAssessmentInfoMapper.selectMemberAssessmentInfoList(memberAssessmentInfo);
        if (memberAssessmentInfos != null && memberAssessmentInfos.size() >0){
            MemberAssessmentInfo memberAssessmentInfoNew = memberAssessmentInfos.get(0);
            memberInfoVo.setMemberAssessmentInfo(memberAssessmentInfoNew);
        }else {
            memberInfoVo.setMemberAssessmentInfo(new MemberAssessmentInfo());
        }
        memberInfoVo.setMap(map);
        return memberInfoVo;
    }

    /**
     * 查询委员信息列表
     *
     * @param memberInfo 委员信息
     * @return 委员信息
     */
    @Override
    public List<MemberInfo> selectMemberInfoList(MemberInfo memberInfo) {
        return memberInfoMapper.selectMemberInfoList(memberInfo);
    }

    /**
     * 获取委员菜单下拉树列表
     */
    @Override
    public List<MemberInfoTree> buildMemberInfoTreeSelect(List<MemberInfo> memberInfo) {
        //查询字典值，政协委员级别
        List<MemberInfoTree> memberInfoTreeList = new ArrayList<>();
        if (memberInfo != null && memberInfo.size() > 0) {
            List<SysDictData> dictDataList = dictDataMapper.selectDictDataByType("grade");
            if (dictDataList != null && dictDataList.size() > 0) {
                for (SysDictData sysDictData : dictDataList) {
                    MemberInfoTree memberInfoTree = new MemberInfoTree();
                    memberInfoTree.setUserId(sysDictData.getDictValue());
                    memberInfoTree.setName(sysDictData.getDictLabel());
                    memberInfoTreeList.add(memberInfoTree);
                }
                for (MemberInfoTree memberInfoTree : memberInfoTreeList) {
                    //委员级别id
                    String id = memberInfoTree.getUserId();
                    List<MemberInfo> memberInfoList = new ArrayList<>();
                    for (MemberInfo info : memberInfo) {
                        if (info.getGrade().contains(id)) {
                            memberInfoList.add(info);
                        }
                    }
                    memberInfoTree.setChildren(memberInfoList);
                }
            }
        }
        return memberInfoTreeList;
    }

    /**
     * 新增委员信息
     *
     * @param memberInfo 委员信息
     * @return 结果
     */
    @Override
    public int insertMemberInfo(MemberInfo memberInfo) {
        memberInfo.setUserId(SecurityUtils.getUserId());
        memberInfo.setCreateTime(DateUtils.getNowDate());
        return memberInfoMapper.insertMemberInfo(memberInfo);
    }

    /**
     * 修改委员信息
     *
     * @param memberInfo 委员信息
     * @return 结果
     */
    @Override
    public int updateMemberInfo(MemberInfo memberInfo) {
        memberInfo.setUpdateTime(DateUtils.getNowDate());
        return memberInfoMapper.updateMemberInfo(memberInfo);
    }

    /**
     * 批量删除委员信息
     *
     * @param memberIds 需要删除的委员信息主键
     * @return 结果
     */
    @Override
    public int deleteMemberInfoByMemberIds(Long[] memberIds) {
        return memberInfoMapper.deleteMemberInfoByMemberIds(memberIds);
    }

    /**
     * 删除委员信息信息
     *
     * @param memberId 委员信息主键
     * @return 结果
     */
    @Override
    public int deleteMemberInfoByMemberId(Long memberId) {
        return memberInfoMapper.deleteMemberInfoByMemberId(memberId);
    }

    @Override
    @Transactional
    public String importData(List<MemberInfo> list, boolean updateSupport, String operName) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (MemberInfo member : list)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(member.getPhonenumber());
                if (StringUtils.isNull(u))
                {
                    SysUser user = new SysUser();
                    user.setDeptId(100L);
                    user.setUserName(member.getPhonenumber());
                    user.setNickName(member.getName());
                    user.setPhonenumber(member.getPhonenumber());
                    user.setStatus("0");
                    user.setDelFlag("0");
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    //新增角色
                    Long[] roleIds = {3L};
                    insertUserRole(user.getUserId(),roleIds);
                    //新增委员
                    member.setUserId(user.getUserId());
                    member.setCreateTime(DateUtils.getNowDate());
                    memberInfoMapper.insertMemberInfo(member);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + member.getPhonenumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + member.getPhonenumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

}
