package com.goafanti.Interview.service.impl;

import com.goafanti.Interview.bo.OutPublicAidUid;
import com.goafanti.Interview.bo.UpdateUserBo;
import com.goafanti.Interview.bo.selectByUidAidBo;
import com.goafanti.Interview.service.UserArchivesInterviewService;
import com.goafanti.common.dao.*;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.BeanUtilsExt;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.customer.bo.MyUserDetailsBo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户档案面谈表(UserArchivesInterview)表服务实现类
 *
 * @author makejava
 * @since 2025-04-10 17:09:23
 */
@Service("userArchivesInterviewService")
public class UserArchivesInterviewServiceImpl extends BaseMybatisDao<UserArchivesInterviewMapper> implements UserArchivesInterviewService {
    @Resource
    private UserArchivesInterviewMapper userArchivesInterviewMapper;
    @Resource
    private UserArchivesMapper userArchivesMapper;
    @Resource
    private PublicReleaseMapper publicReleaseMapper;
    @Resource
    private UserFirstInterviewMapper userFirstInterviewMapper;
    @Resource
    private UserDataLogMapper userDataLogMapper;


    @Override
    public Pagination<UserArchivesInterview> list(UserArchivesInterview userArchivesInterview, Integer pageNo, Integer pageSize) {
        userArchivesInterview.setAid(TokenManager.getAdminId());
        Map<String, Object> params = BeanUtilsExt.pushMap(userArchivesInterview);
        return (Pagination<UserArchivesInterview>) findPage("findUserArchivesInterviewList",
                "findUserArchivesInterviewCount", params, pageNo, pageSize);
    }



    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public UserArchivesInterview queryById(Integer id) {
        return this.userArchivesInterviewMapper.selectById(id);
    }


    /**
     * 新增数据
     *
     * @param userArchivesInterview 实例对象
     * @return 实例对象
     */
    @Override
    public UserArchivesInterview insert(UserArchivesInterview userArchivesInterview) {
        this.userArchivesInterviewMapper.insert(userArchivesInterview);
        return userArchivesInterview;
    }

    /**
     * 修改数据
     *
     * @param userArchivesInterview 实例对象
     * @return 实例对象
     */
    @Override
    public UserArchivesInterview update(UserArchivesInterview userArchivesInterview) {
        this.userArchivesInterviewMapper.update(userArchivesInterview);
        return this.queryById(userArchivesInterview.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.userArchivesInterviewMapper.deleteById(id) > 0;
    }

    @Override
    public Object updateUser(UpdateUserBo in) {
        //第一次面谈时间,暂时设定所有的
        List<MyUserDetailsBo> myUserDetailsBos =publicReleaseMapper.selectByUid(in.getUid());
        if (!myUserDetailsBos.isEmpty()){
            MyUserDetailsBo myUserDetailsBo = myUserDetailsBos.get(0);
            in.setFirstInterviewDate(myUserDetailsBo.getReleaseStart());
        }
        //添加客户档案面谈记录表
        if (in.getType()>0){
            addUserArchivesInterview(in);
        }
        if (in.getType()!=2){
            //读取是否有档案存在
            UserArchives userArchives = userArchivesMapper.queryByUid(in.getUid());
            if (userArchives !=null){
                in.setId(userArchives.getId());
            }
            if (in.getId()!=null){
                addUserDataLog(userArchives,in);
                in.setUpdateTime(new Date());
                userArchivesMapper.update(in);
            }else {
                in.setEarlyCommunication(null);
                in.setInterviewIdeas(null);
                in.setCreateTime(new Date());
                in.setUpdateTime(new Date());
                userArchivesMapper.insert(in);
            }
        }
        return in;
    }

    private void addUserDataLog(UserArchives use, UpdateUserBo in) {
        Admin adminToken = TokenManager.getAdminToken();
        String name= adminToken.getName();
        StringBuilder str=new StringBuilder(name).append("修改了");
        int length = str.length();
        addPramUserDataLog(use, in, str);

        if ((str.length()-length)>4){
            userDataLogMapper.insert(new UserDataLog(use.getUid(),str.toString()));
        }
    }

    private void addPramUserDataLog(UserArchives use, UpdateUserBo in, StringBuilder sb) {
        JudgePram(sb,use.getCompanyCount(),in.getCompanyCount(),"母/子公司数");
        JudgePram(sb,use.getSocialSecurityCount(),in.getSocialSecurityCount(),"社保人数");
        JudgePram(sb,use.getExternalInvestCount(),in.getExternalInvestCount(),"对外投资控股的企业数");
        JudgePram(sb,use.getExternalInvestIndustryName(),in.getExternalInvestIndustryName(),"对外投资控股的行业");
        JudgePram(sb,use.getExternalInvestName(),in.getExternalInvestName(),"对外投资控股的企业");
        JudgePram(sb,use.getFinancialRevenue(),in.getFinancialRevenue(),"财务数据-营收（万元）");
        JudgePram(sb,use.getFinancialTax(),in.getFinancialTax(),"财务数据-税收（万元）");
        JudgePram(sb,use.getFinancialProperty(),in.getFinancialProperty(),"财务数据-资产（万元）");
        JudgePram(sb,use.getFinancialRd(),in.getFinancialRd(),"财务数据-研发费用（万元）");
    }

    private void JudgePram(StringBuilder sb,Object use, Object in, String name) {
        if (use instanceof String){
            if (!Objects.equals(use,in)) {
                sb.append(name).append("[").append(use).append(" => ").append(in).append("];");
            }
        }
        if (use instanceof BigDecimal){
            BigDecimal inDb = BigDecimal.valueOf(Double.parseDouble(in.toString()));
            if (inDb.compareTo((BigDecimal) use)!=0) {
                sb.append(name).append("[").append(use).append(" => ").append(inDb).append("];");
            }

        }

    }


    private void addUserArchivesInterview(UpdateUserBo in) {
        List<selectByUidAidBo> list = userArchivesInterviewMapper.selectByUidAid(in.getUid(), in.getAid());
        UserArchivesInterview userArchivesInterview = new UserArchivesInterview();
        if (list.isEmpty()){
            userArchivesInterview.setCounts(1);
        }else {
            userArchivesInterview = list.get(0);
            userArchivesInterview.setCounts(userArchivesInterview.getCounts() + 1);
        }
        userArchivesInterview.setUid(in.getUid());
        userArchivesInterview.setAid(in.getAid());
        userArchivesInterview.setEarlyCommunication(in.getEarlyCommunication());
        userArchivesInterview.setCustomerDemand(in.getCustomerDemand());
        userArchivesInterview.setInterviewIdeas(in.getInterviewIdeas());
        userArchivesInterview.setInterviewPurpose(in.getInterviewPurpose());
        userArchivesInterview.setInterviewRecommend(in.getInterviewRecommend());
        userArchivesInterview.setInterviewFeedback(in.getInterviewFeedback());
        userArchivesInterview.setFollowUpPlan(in.getFollowUpPlan());
        if(in.getUaiId()!=null){
            userArchivesInterviewMapper.update(userArchivesInterview);
        }else {
            userArchivesInterview.setCreateTime(new Date());
            userArchivesInterview.setPrdid(null);
            userArchivesInterviewMapper.insert(userArchivesInterview);
            in.setUaiId(userArchivesInterview.getId());
        }
    }

    @Override
    public Object pushUserFirstInterview(){
    try {
        // 获取所有公共发布记录
        List<OutPublicAidUid> publicReleases = publicReleaseMapper.selectAllAidUid();

        if (publicReleases == null || publicReleases.isEmpty()) {
            return 1; // 如果没有数据，直接返回
        }

        // 按 aid 分组
        Map<String, List<OutPublicAidUid>> groupedByAid = groupByAid(publicReleases);

        // 按 uid 进一步分组，并计算每个用户的首次发布时间
        List<UserFirstInterview> res = calculateUserFirstInterviews(groupedByAid);

        // 批量插入数据库
        insertInBatches(res, 100);

        return 1;
    } catch (Exception e) {
        // 异常处理
        e.printStackTrace();
        throw new RuntimeException("Error during processing user first interview", e);
    }
}

    @Override
    public Object selectByPrdid(Integer prdid) {
        Map<String ,Object> res = new HashMap<>();
        UserArchivesInterview uai = userArchivesInterviewMapper.selectByPrdid(prdid);
        if (uai!=null){
            res.put("data",uai);
            List<selectByUidAidBo> list = userArchivesInterviewMapper.selectByUidAid(uai.getUid(), uai.getAid());
            res.put("list",list);
        }
        return res;
    }

    private Map<String, List<OutPublicAidUid>> groupByAid(List<OutPublicAidUid> publicReleases) {
    return publicReleases.stream()
            .filter(Objects::nonNull) // 过滤掉空对象
            .collect(Collectors.groupingBy(OutPublicAidUid::getAid));
}

private List<UserFirstInterview> calculateUserFirstInterviews(Map<String, List<OutPublicAidUid>> groupedByAid) {
    long currentTime = System.currentTimeMillis(); // 提前获取当前时间戳
    List<UserFirstInterview> res = new ArrayList<>();

    for (Map.Entry<String, List<OutPublicAidUid>> entry : groupedByAid.entrySet()) {
        String aid = entry.getKey();
        List<OutPublicAidUid> aids = entry.getValue();

        Map<String, List<OutPublicAidUid>> groupedByUid = aids.stream()
                .filter(Objects::nonNull) // 过滤掉空对象
                .collect(Collectors.groupingBy(OutPublicAidUid::getUid));

        for (Map.Entry<String, List<OutPublicAidUid>> uidEntry : groupedByUid.entrySet()) {
            String uid = uidEntry.getKey();
            List<OutPublicAidUid> list = uidEntry.getValue();

            UserFirstInterview in = findEarliestRelease(list, currentTime, aid, uid);
            if (in != null) {
                res.add(in);
            }
        }
    }

    return res;
}

private UserFirstInterview findEarliestRelease(List<OutPublicAidUid> list, long currentTime, String aid, String uid) {
    UserFirstInterview in = null;
    long earliestTime = Long.MAX_VALUE;

    for (OutPublicAidUid e : list) {
        if (e == null || e.getReleaseStart() == null) {
            continue; // 跳过空对象或无效的时间
        }

        long releaseStartTime = e.getReleaseStart().getTime();
        if (releaseStartTime < earliestTime && releaseStartTime < currentTime) {
            earliestTime = releaseStartTime;
            in = new UserFirstInterview();
            in.setFirstTime(e.getReleaseStart());
            in.setUid(uid);
            in.setAid(aid);
        }
    }

    return in;
}

private void insertInBatches(List<UserFirstInterview> res, int batchSize) {
    int total = res.size();
    for (int i = 0; i < total; i += batchSize) {
        int end = Math.min(i + batchSize, total);
        List<UserFirstInterview> batch = res.subList(i, end);
        try {
            userFirstInterviewMapper.insertBatch(batch);
        } catch (Exception e) {
            // 批量插入失败时的处理
            e.printStackTrace();
            throw new RuntimeException("Error inserting batch into database", e);
        }
    }
}

}
