package com.cy.guoyan.admin.module.guoyan.service.stateownedreformlawinfo;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.cy.guoyan.admin.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cy.guoyan.admin.framework.security.core.util.SecurityFrameworkUtils;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.researchtopiccategory.ResearchTopicCategoryDO;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.researchtopicinfo.ResearchTopicInfoDO;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.stateownedreformlawcategory.StateOwnedReformLawCategoryDO;
import com.cy.guoyan.admin.module.guoyan.dal.mysql.stateownedreformlawcategory.StateOwnedReformLawCategoryMapper;
import com.cy.guoyan.admin.module.infra.controller.admin.file.vo.file.FileVO;
import com.cy.guoyan.admin.module.infra.dal.dataobject.file.FileDO;
import com.cy.guoyan.admin.module.infra.dal.mysql.file.FileMapper;
import com.cy.guoyan.admin.module.system.enums.common.JobTypeCodeConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

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

import com.cy.guoyan.admin.module.guoyan.controller.admin.stateownedreformlawinfo.vo.*;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.stateownedreformlawinfo.StateOwnedReformLawInfoDO;
import com.cy.guoyan.admin.framework.common.pojo.PageResult;
import com.cy.guoyan.admin.framework.common.util.object.BeanUtils;
import com.cy.guoyan.admin.module.guoyan.dal.mysql.stateownedreformlawinfo.StateOwnedReformLawInfoMapper;
import static com.cy.guoyan.admin.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cy.guoyan.admin.module.system.enums.ErrorCodeConstants.*;

/**
 * 国企改革法规信息 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class StateOwnedReformLawInfoServiceImpl implements StateOwnedReformLawInfoService {

    @Resource
    private StateOwnedReformLawInfoMapper stateOwnedReformLawInfoMapper;

    @Resource
    private StateOwnedReformLawCategoryMapper stateOwnedReformLawCategoryMapper;

    @Resource
    private FileMapper fileMapper;


    @Override
    public Long createStateOwnedReformLawInfo(StateOwnedReformLawInfoSaveReqVO createReqVO) {
        String nickname = String.valueOf(SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));
        StateOwnedReformLawInfoDO data = BeanUtils.toBean(createReqVO, StateOwnedReformLawInfoDO.class);

        data.setCreatorName(nickname);
        DefaultIdentifierGenerator generator = new DefaultIdentifierGenerator();
        data.setId(generator.nextId(null));
        data.setAuditStatus("未审核");
        data.setStatus("正常");
        if (createReqVO.getPublishDate() != null) {
            String year = createReqVO.getPublishDate().substring(0, 4);
            data.setPublishYear(Integer.parseInt(year));
        }
        if (StringUtils.isNotBlank(createReqVO.getImage())) {
            createReqVO.setImageDate(extractDate(createReqVO.getImage()));
        }

        stateOwnedReformLawInfoMapper.insert(data);
        if (createReqVO.getFileList() != null) {
            createReqVO.getFileList().forEach(file -> {
                file.setJobTypeCode(JobTypeCodeConstants.STATE_OWNED_REFORM_LAW_INFO);
                file.setBusinessId(String.valueOf(data.getId()));
                List<FileDO> fileDOList =BeanUtils.toBean(createReqVO.getFileList(), FileDO.class);
                fileMapper.updateBatch(fileDOList);
            });
        }

        if (StringUtils.isNotBlank(createReqVO.getTopicCategoryCode())) {
            String topicCategoryCodeStr = createReqVO.getTopicCategoryCode();
            List<String> codeList = Arrays.stream(topicCategoryCodeStr.split("\\."))
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());

            List<StateOwnedReformLawCategoryDO> categoryList =
                    stateOwnedReformLawCategoryMapper.selectList(
                            new LambdaQueryWrapperX<StateOwnedReformLawCategoryDO>()
                                    .in(StateOwnedReformLawCategoryDO::getCategoryCode, codeList));

            categoryList.forEach(item ->
                    item.setInfoCount(
                            Optional.ofNullable(item.getInfoCount()).orElse(0) + 1));
            stateOwnedReformLawCategoryMapper.updateBatch(categoryList);
        }

        return data.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStateOwnedReformLawInfo(StateOwnedReformLawInfoSaveReqVO updateReqVO) {
        String nickname = String.valueOf(
                SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));
        StateOwnedReformLawInfoDO old = stateOwnedReformLawInfoMapper.selectById(updateReqVO.getId());
        if (old == null) {
            throw exception(STATE_OWNED_REFORM_LAW_INFO_NOT_EXISTS);
        }

        // 3. 查询旧附件
        List<FileDO> oldFiles = fileMapper.selectList(new LambdaQueryWrapperX<FileDO>()
                .eq(FileDO::getBusinessId, old.getId())
                .eq(FileDO::getJobTypeCode, JobTypeCodeConstants.STATE_OWNED_REFORM_LAW_INFO));

        // 4. 取新附件（前端应传文件 ID 列表）
        List<Long> newFileIds = Optional.ofNullable(updateReqVO.getFileList())
                .orElse(Collections.emptyList())
                .stream()
                .map(FileVO::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 5. 做 diff
        Set<Long> oldSet = oldFiles.stream()
                .map(FileDO::getId)
                .collect(Collectors.toSet());
        Set<Long> newSet = new HashSet<>(newFileIds);

        // old - new => 需要移除的旧文件
        List<Long> removeIds = oldSet.stream()
                .filter(id -> !newSet.contains(id))
                .collect(Collectors.toList());

        // new - old => 需要新增绑定的文件
        List<Long> addIds = newSet.stream()
                .filter(id -> !oldSet.contains(id))
                .collect(Collectors.toList());

        // 6. 处理删除
        if (!removeIds.isEmpty()) {
            fileMapper.deleteByIds(removeIds);
        }

        if (StringUtils.isNotBlank(updateReqVO.getImage())) {
            updateReqVO.setImageDate(extractDate(updateReqVO.getImage()));
        }

        // 7. 处理新增
        if (!addIds.isEmpty()) {
            List<FileVO> fileList = updateReqVO.getFileList().stream()
                    .filter(fileVO -> fileVO.getId() != null && addIds.contains(fileVO.getId()))
                    .collect(Collectors.toList());

            fileList.forEach(f-> {
                f.setJobTypeCode(JobTypeCodeConstants.STATE_OWNED_REFORM_LAW_INFO);
                f.setBusinessId(String.valueOf(updateReqVO.getId()));
            });

            List<FileDO> addFileList =BeanUtils.toBean(fileList, FileDO.class);
            fileMapper.updateBatch(addFileList);
        }

        StateOwnedReformLawInfoDO updateObj = BeanUtils.toBean(updateReqVO, StateOwnedReformLawInfoDO.class);
        updateObj.setUpdaterName(nickname);
        stateOwnedReformLawInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteStateOwnedReformLawInfo(Long id) {
        // 校验存在
        validateStateOwnedReformLawInfoExists(id);
        // 删除
        stateOwnedReformLawInfoMapper.deleteById(id);
    }

    @Override
        public void deleteStateOwnedReformLawInfoListByIds(List<Long> ids) {
        // 校验存在
        validateStateOwnedReformLawInfoExists(ids);
        // 删除
        stateOwnedReformLawInfoMapper.deleteByIds(ids);
        }

    private void validateStateOwnedReformLawInfoExists(List<Long> ids) {
        List<StateOwnedReformLawInfoDO> list = stateOwnedReformLawInfoMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(STATE_OWNED_REFORM_LAW_INFO_NOT_EXISTS);
        }
    }

    private void validateStateOwnedReformLawInfoExists(Long id) {
        if (stateOwnedReformLawInfoMapper.selectById(id) == null) {
            throw exception(STATE_OWNED_REFORM_LAW_INFO_NOT_EXISTS);
        }
    }

    @Override
    public StateOwnedReformLawInfoRespVO getStateOwnedReformLawInfo(Long id) {
        StateOwnedReformLawInfoDO old = stateOwnedReformLawInfoMapper.selectById(id);
        if (old == null) {
            throw exception(STATE_OWNED_REFORM_LAW_INFO_NOT_EXISTS);
        }
        StateOwnedReformLawInfoRespVO bean = BeanUtils.toBean(old, StateOwnedReformLawInfoRespVO.class);

        List<FileDO> fileList = fileMapper.selectList(new LambdaQueryWrapperX<FileDO>()
                .eq(FileDO::getBusinessId, String.valueOf(id))
                .eq(FileDO::getJobTypeCode, JobTypeCodeConstants.STATE_OWNED_REFORM_LAW_INFO));

        List<FileVO> fileRespVOList =BeanUtils.toBean(fileList, FileVO.class);

        bean.setFileList(fileRespVOList);

        return bean;
    }

    @Override
    public PageResult<StateOwnedReformLawInfoDO> getStateOwnedReformLawInfoPage(StateOwnedReformLawInfoPageReqVO pageReqVO) {
        return stateOwnedReformLawInfoMapper.selectPage(pageReqVO);
    }

    @Override
    public List<StateOwnedReformLawInfoDO> getStateOwnedReformLawInfoList(StateOwnedReformLawInfoPageReqVO pageReqVO) {
        pageReqVO.setPageSize(-1);
        PageResult<StateOwnedReformLawInfoDO> stateOwnedReformLawInfoDOPageResult = stateOwnedReformLawInfoMapper.selectPage(pageReqVO);
        return stateOwnedReformLawInfoDOPageResult.getList();
    }


    @Override
    public void auditStateOwnedReformLawInfo(Long id, String auditStatus) {
        StateOwnedReformLawInfoDO infoDO = stateOwnedReformLawInfoMapper.selectById(id);
        if (infoDO == null) {
            throw exception(STATE_OWNED_REFORM_LAW_INFO_NOT_EXISTS);
        }
        String nickname = String.valueOf(
                SecurityFrameworkUtils.getLoginUser().getInfo().get("nickname"));
        infoDO.setAuditStatus(auditStatus);
        infoDO.setAuditor(nickname);
        infoDO.setAuditTime(LocalDateTime.now());
        stateOwnedReformLawInfoMapper.updateById(infoDO);
    }
    @Override
    public void voidStateOwnedReformLawInfo(Long id, String status) {
        StateOwnedReformLawInfoDO infoDO = stateOwnedReformLawInfoMapper.selectById(id);
        if (infoDO == null) {
            throw exception(STATE_OWNED_REFORM_LAW_INFO_NOT_EXISTS);
        }
        infoDO.setStatus(status);
        stateOwnedReformLawInfoMapper.updateById(infoDO);
    }



    public static String extractDate(String path) {
        // 正则匹配中间的8位数字
        String regex = "/(\\d{8})/";
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
        java.util.regex.Matcher matcher = pattern.matcher(path);

        if (matcher.find()) {
            return matcher.group(1); // 返回匹配到的日期部分
        }

        return null;
    }

}