package com.sqx.modules.intention.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.intention.dao.IntentionDao;
import com.sqx.modules.intention.entity.Intention;
import com.sqx.modules.intention.service.IntentionService;
import com.sqx.modules.resumes.entity.RuleClassify;
import com.sqx.modules.resumes.service.RuleClassifyService;
import com.sqx.modules.resumes.service.RulePostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import weixin.popular.bean.datacube.article.Usershare;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author www.javacoder.top
 * @since 2023-01-13
 */
@Service
public class IntentionServiceImpl extends ServiceImpl<IntentionDao, Intention> implements IntentionService {
    @Autowired
    CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private RuleClassifyService classifyService;

    @Override
    public Result saveUpdate(Intention intention) {
        // 1. 处理默认意向：全局最多3条is_default=1的数据
        boolean isSetDefault = intention.getIsDefault() == 1;
        if (isSetDefault) {
            // 查询当前数据库中is_default=1的总数
            int currentDefaultCount = baseMapper.selectCount(new QueryWrapper<Intention>().eq("is_default", 1));

            // 判断是否需要校验（新增默认 或 修改非默认→默认）
            boolean needCheck = false;
            if (intention.getIntentionId() == null) {
                // 新增操作：设置为默认会使总数+1，需校验
                needCheck = true;
            } else {
                // 修改操作：查询原记录的is_default值
                Intention oldIntention = baseMapper.selectById(intention.getIntentionId());
                if (oldIntention != null && oldIntention.getIsDefault() == 0) {
                    // 原记录不是默认，现在改为默认，总数+1，需校验
                    needCheck = true;
                }
            }

            // 校验：若需要检查且当前总数已≥3，禁止操作
            if (needCheck && currentDefaultCount >= 3) {
                return Result.error("系统最多只能有3条默认求职意向");
            }
        }

        // 2. 校验用户的意向总数限制（原有逻辑：每个用户最多maxCount个意向）
        QueryWrapper<Intention> countWrapper = new QueryWrapper<Intention>()
                .eq("user_id", intention.getUserId())
                .ne(intention.getIntentionId() != null, "intention_id", intention.getIntentionId());
        int userIntentionCount = baseMapper.selectCount(countWrapper);
        int maxUserCount = Integer.parseInt(commonInfoService.findOne(325).getValue()); // 每个用户的最大意向数
        if (userIntentionCount >= maxUserCount) {
            return Result.error("当前用户求职意向最多添加" + maxUserCount + "个");
        }

        // 3. 区分新增/修改操作
        if (intention.getIntentionId() != null) {
            // 修改操作
            return Result.upStatus(baseMapper.updateById(intention));
        } else {
            // 新增操作：补充基础信息
            UserEntity userEntity = userService.getById(intention.getUserId());
            if (userEntity == null) {
                return Result.error("用户不存在");
            }
            intention.setCreateTime(LocalDateTime.now());
            intention.setUserName(userEntity.getUserName());

            // 补充三级分类信息
            RuleClassify ruleClassify = classifyService.getById(intention.getRuleClassifyId());
            if (ruleClassify == null) {
                return Result.error("三级分类不存在");
            }
            RuleClassify twoClassify = classifyService.getOne(new QueryWrapper<RuleClassify>()
                    .eq("rule_classify_id", ruleClassify.getParentId()));
            if (twoClassify == null) {
                return Result.error("二级分类不存在");
            }
            RuleClassify oneClassify = classifyService.getOne(new QueryWrapper<RuleClassify>()
                    .eq("rule_classify_id", twoClassify.getParentId()));
            if (oneClassify == null) {
                return Result.error("一级分类不存在");
            }
            intention.setRuleClassifyId(ruleClassify.getRuleClassifyId());
            intention.setClassifyTwoId(twoClassify.getRuleClassifyId());
            intention.setClassifyOneId(oneClassify.getRuleClassifyId());

            // 执行插入
            return Result.upStatus(baseMapper.insert(intention));
        }
    }

    @Override
    public IPage<Intention> getIntentionList(Integer page, Integer limit, Intention intention) {
        Page<Intention> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.selectPage(pages, new QueryWrapper<>(intention).orderByDesc("create_time"));
    }

    @Override
    public List<Intention> getIntention(Long userId) {
        QueryWrapper<Intention>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("is_default",1);
        return baseMapper.selectList(queryWrapper);
    }
}
