package com.vctgo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Splitter;
import com.vctgo.common.core.constant.SecurityConstants;
import com.vctgo.common.core.exception.ServiceException;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.DateUtils;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.RemoteExpertWorkingPlatformService;
import com.vctgo.system.api.RemotePlatformUserService;
import com.vctgo.system.api.domain.*;
import com.vctgo.system.api.domain.dto.VoteExpertWorkingPlatformDto;
import com.vctgo.system.api.domain.dto.VoteSubmissionItemVo;
import com.vctgo.system.api.domain.vo.VoteExpertSubmissionCountVo;
import com.vctgo.system.api.domain.vo.VoteExpertSubmissionVo;
import com.vctgo.system.api.domain.vo.VoteExpertWorkingPlatformVo;
import com.vctgo.system.domain.SysPlatformExpert;
import com.vctgo.system.domain.SysPlatformUserRole;
import com.vctgo.system.mapper.SysPlatformExpertMapper;
import com.vctgo.system.mapper.SysPlatformUserMapper;
import com.vctgo.system.mapper.SysPlatformUserRoleMapper;
import com.vctgo.system.service.ISysPlatformExpertService;
import com.vctgo.system.util.ConstantUtils;
import com.vctgo.system.util.DataEncoder;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.CollateExpression;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 专家附属信息Service业务层处理
 *
 * @author caesar
 * @date 2024-03-27
 */
@Slf4j
@Service
public class SysPlatformExpertServiceImpl implements ISysPlatformExpertService {

    @Autowired
    private SysPlatformUserMapper sysPlatformUserMapper;

    @Autowired
    private SysPlatformExpertMapper sysPlatformExpertMapper;

    @Autowired
    private SysPlatformUserRoleMapper sysPlatformUserRoleMapper;

    @Autowired
    private RemoteExpertWorkingPlatformService remoteExpertWorkingPlatformService;

    @Autowired
    private DataEncoder dataEncoder;

    /**
     * 查询专家附属信息
     *
     * @param id 专家附属信息主键
     * @return 专家附属信息
     */
    @Override
    public SysPlatformExpert selectSysPlatformExpertById(Long id) {
        SysPlatformExpert sysPlatformExpert = sysPlatformExpertMapper.selectExpertByUserId(id.toString());
        if (Objects.nonNull(sysPlatformExpert)) {
            LambdaQueryWrapper<SysPlatformUserRole> sysPlatformUserRoleWrapper = new LambdaQueryWrapper<>();
            sysPlatformUserRoleWrapper.eq(SysPlatformUserRole::getUserId, id);
            List<SysPlatformUserRole> sysPlatformUserRoleList = sysPlatformUserRoleMapper.selectList(sysPlatformUserRoleWrapper);
            if (CollectionUtils.isNotEmpty(sysPlatformUserRoleList)) {
                sysPlatformExpert.setRoleIds(sysPlatformUserRoleList.stream().map(SysPlatformUserRole::getRoleId).toArray(Long[]::new));
            }
        }
        return sysPlatformExpert;
    }

    /**
     * 查询专家附属信息列表-分页
     *
     * @param sysPlatformExpert 专家附属信息
     * @return 专家附属信息
     */
    @Override
    public IPage<SysPlatformExpert> selectSysPlatformExpertPage(SysPlatformExpert sysPlatformExpert) {
        Page mpPage = new Page(Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L), Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L));
        IPage<SysPlatformExpert> sysPlatformExpertIPage = sysPlatformExpertMapper.selectSysPlatformExpertList(mpPage, sysPlatformExpert);
        if (CollectionUtils.isNotEmpty(sysPlatformExpertIPage.getRecords())) {
            sysPlatformExpertIPage.getRecords().forEach(sysPlatformExpertTmp -> {
                String roleIdString = sysPlatformExpertTmp.getRoleIdString();
                if (StringUtils.isNotEmpty(roleIdString)) {
                    sysPlatformExpertTmp.setRoleIds(Splitter.on(",").splitToList(roleIdString).stream().map(Long::new).toArray(Long[]::new));
                }
            });
        }
        return sysPlatformExpertIPage;
    }

    /**
     * 查询专家附属信息列表
     *
     * @param sysPlatformExpert 专家附属信息
     * @return 专家附属信息
     */
    @Override
    public List<SysPlatformExpert> selectSysPlatformExpertList(SysPlatformExpert sysPlatformExpert) {
        return sysPlatformExpertMapper.selectSysPlatformExpertList(sysPlatformExpert);
    }

    /**
     * 新增专家附属信息
     *
     * @param sysPlatformExpert 专家附属信息
     * @return 结果
     */
    @Override
    public int insertSysPlatformExpert(SysPlatformExpert sysPlatformExpert) {

        /**
         * 判断当前手机号是否被使用了
         */
        LambdaQueryWrapper<SysPlatformUser> sysPlatformUserWrapper = new LambdaQueryWrapper<>();
        sysPlatformUserWrapper.eq(SysUserTempalte::getDelFlag, ConstantUtils.IS_DELETED_0);
        sysPlatformUserWrapper.eq(SysUserTempalte::getUserName, sysPlatformExpert.getPhonenumber());
        List<SysPlatformUser> sysPlatformUsers = sysPlatformUserMapper.selectList(sysPlatformUserWrapper);
        if (CollectionUtils.isNotEmpty(sysPlatformUsers)) {
            throw new SecurityException("手机号已被使用");
        }

        SysPlatformUser sysPlatformUser = new SysPlatformUser();
        sysPlatformUser.setIsExpert(ConstantUtils.IS_EXPERT_1);
        sysPlatformUser.setCreateById(SecurityUtils.getUserId());
        sysPlatformUser.setCreateTime(DateUtils.getNowDate());
        sysPlatformUser.setStatus(ConstantUtils.ACCOUNT_STATUS_2);
        sysPlatformUser.setAvatar(sysPlatformExpert.getAvatar());
        sysPlatformUser.setNickName(sysPlatformExpert.getNickName());
        sysPlatformUser.setDelFlag(ConstantUtils.IS_DELETED_0);
        sysPlatformUser.setPhonenumber(sysPlatformExpert.getPhonenumber());
        sysPlatformUser.setSex(sysPlatformExpert.getSex());
        sysPlatformUser.setUserName(sysPlatformUser.getPhonenumber());
        sysPlatformUser.setEmail(sysPlatformExpert.getEmail());
        sysPlatformUserMapper.insert(sysPlatformUser);

        /**
         * 保存专家附属信息
         */
        sysPlatformExpert.setUserId(sysPlatformUser.getUserId());
        sysPlatformExpert.setCreateById(SecurityUtils.getUserId());
        sysPlatformExpert.setIsDeleted(ConstantUtils.IS_DELETED_0);
        sysPlatformExpert.setCreateTime(DateUtils.getNowDate());
        return sysPlatformExpertMapper.insert(sysPlatformExpert);
    }

    /**
     * 修改专家附属信息
     *
     * @param sysPlatformExpert 专家附属信息
     * @return 结果
     */
    @Override
    public int updateSysPlatformExpert(SysPlatformExpert sysPlatformExpert) {

        /**
         * 保存专家的基本信息
         *
         */
        LambdaQueryWrapper<SysPlatformUser> sysPlatformUserWrapper = new LambdaQueryWrapper<>();
        sysPlatformUserWrapper.eq(SysUserTempalte::getDelFlag, ConstantUtils.IS_DELETED_0);
        sysPlatformUserWrapper.eq(SysUserTempalte::getUserName, sysPlatformExpert.getPhonenumber());
        SysPlatformUser sysPlatformUserTmp = sysPlatformUserMapper.selectOne(sysPlatformUserWrapper);
        if (Objects.nonNull(sysPlatformUserTmp) && !sysPlatformUserTmp.getUserId().equals(sysPlatformExpert.getUserId())) {
            throw new SecurityException("手机号已被使用");
        }

        /**
         * 专家修改信息
         */
        sysPlatformUserTmp.setStatus(sysPlatformExpert.getStatus());
        sysPlatformUserTmp.setAvatar(sysPlatformExpert.getAvatar());
        sysPlatformUserTmp.setNickName(sysPlatformExpert.getNickName());
        sysPlatformUserTmp.setPhonenumber(sysPlatformExpert.getPhonenumber());
        sysPlatformUserTmp.setSex(sysPlatformExpert.getSex());
        sysPlatformUserTmp.setUserName(sysPlatformExpert.getPhonenumber());
        sysPlatformUserTmp.setEmail(sysPlatformExpert.getEmail());
        sysPlatformUserTmp.setUpdateById(SecurityUtils.getUserId());
        sysPlatformUserTmp.setUpdateTime(DateUtils.getNowDate());
        sysPlatformUserMapper.updateById(sysPlatformUserTmp);

        /**
         * 修改专家附属信息
         */
        return sysPlatformExpertMapper.updateById(sysPlatformExpert);
    }

    /**
     * 逻辑删除专家附属信息
     *
     * @param ids 需要删除的专家附属信息主键
     * @return 结果
     */
    @Override
    public int logicalDeleteSysPlatformExpertByIds(Long[] ids, Long userId) {
        sysPlatformUserMapper.deleteUserById(userId);

        SysPlatformExpert sysPlatformExpert = new SysPlatformExpert();
        sysPlatformExpert.setUpdateById(SecurityUtils.getUserId());
        sysPlatformExpert.setUpdateBy(SecurityUtils.getUsername());
        sysPlatformExpert.setUpdateTime(new Date());
        sysPlatformExpert.setIsDeleted(ConstantUtils.IS_DELETED_1);
        return sysPlatformExpertMapper.logicalDeleteSysPlatformExpertByIds(ids, sysPlatformExpert);
    }

    /**
     * 批量删除专家附属信息
     *
     * @param ids 需要删除的专家附属信息主键
     * @return 结果
     */
    @Override
    public int deleteSysPlatformExpertByIds(Long[] ids) {
        return sysPlatformExpertMapper.deleteSysPlatformExpertByIds(ids);
    }

    /**
     * 删除专家附属信息信息
     *
     * @param id 专家附属信息主键
     * @return 结果
     */
    @Override
    public int deleteSysPlatformExpertById(Long id) {
        return sysPlatformExpertMapper.deleteById(id);
    }

    /**
     * 专家平台分页
     */
    @Override
    public IPage<VoteExpertWorkingPlatformVo> expertPage(VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto) {
        // 分页参数
        long pageNum = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L);
        long pageSize = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L);
        List<VoteExpertWorkingPlatformVo> voteExpertWorkingPlatformVos = remoteExpertWorkingPlatformService.expertPlatformPage(voteExpertWorkingPlatformDto.getJudgesId()).getData();
        if (!CollectionUtils.isEmpty(voteExpertWorkingPlatformVos)) {
            Page<VoteExpertWorkingPlatformVo> page = new Page<>(pageNum, pageSize);
            page.setRecords(voteExpertWorkingPlatformVos);
            page.setTotal(voteExpertWorkingPlatformVos.size());
            return page;
        }
        throw new NullPointerException("该专家暂未分配评选任务");
    }

    /**
     * 专家评选作品分页
     */
    @Override
    public IPage<VoteExpertSubmissionVo> submissionList(VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto) {
        // 分页参数
        long pageNum = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L);
        long pageSize = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L);
        List<VoteExpertSubmissionVo> submissionVos = remoteExpertWorkingPlatformService.expertPlatformDetail(voteExpertWorkingPlatformDto.getEventId()
                , voteExpertWorkingPlatformDto.getWorkSettingsId()
                , voteExpertWorkingPlatformDto.getRoundId()
                , voteExpertWorkingPlatformDto.getStatus()).getData();
        Page<VoteExpertSubmissionVo> page = new Page<>(pageNum, pageSize);
        if (!CollectionUtils.isEmpty(submissionVos)) {
            page.setRecords(submissionVos);
            page.setTotal(submissionVos.size());
            return page;
        } else {
            page.setRecords(Collections.emptyList());
            page.setTotal(0L);
        }
        return page;
    }

    @Override
    public VoteExpertSubmissionCountVo submissionCount(VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto) {
        return remoteExpertWorkingPlatformService.submissionCount(voteExpertWorkingPlatformDto.getEventId()
                , voteExpertWorkingPlatformDto.getWorkSettingsId()
                , voteExpertWorkingPlatformDto.getRoundId()).getData();
    }

    @Override
    public List<VoteScoringItem> item(Long ruleId) {
        return remoteExpertWorkingPlatformService.getItem(ruleId).getData();
    }

    @Override
    public VoteEvents eventDetails(Long eventId) {
        return remoteExpertWorkingPlatformService.getEventDetails(eventId).getData();
    }

    @Override
    public VoteSubmission submissionDetails(VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto) {
        return remoteExpertWorkingPlatformService.submissionDetails(voteExpertWorkingPlatformDto.getEventId(),
                voteExpertWorkingPlatformDto.getWorkSettingsId(),
                voteExpertWorkingPlatformDto.getRoundId(),
                voteExpertWorkingPlatformDto.getSubmissionId()).getData();

    }

    @Override
    public int commitGrade(VoteExpertWorkingPlatformDto voteExpertWorkingPlatformDto) {
        try {
            String encode = dataEncoder.encode(voteExpertWorkingPlatformDto);
            return remoteExpertWorkingPlatformService.expertScoring(encode).getData();
        } catch (JsonProcessingException e) {
            throw new RuntimeException("不能提交空评分");
        }
    }
}
