package com.hotwj.platform.resourceManagement.companyChangeHistory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.config.companyDeptConfig.domain.HotCompanyDeptConfig;
import com.hotwj.platform.config.companyDeptConfig.mapper.HotCompanyDeptConfigMapper;
import com.hotwj.platform.resourceManagement.companyChangeHistory.domain.HotCompanyChangeHistory;
import com.hotwj.platform.resourceManagement.companyChangeHistory.domain.bo.HotCompanyChangeHistoryBo;
import com.hotwj.platform.resourceManagement.companyChangeHistory.domain.vo.HotCompanyChangeHistoryVo;
import com.hotwj.platform.resourceManagement.companyChangeHistory.mapper.HotCompanyChangeHistoryMapper;
import com.hotwj.platform.resourceManagement.companyChangeHistory.service.IHotCompanyChangeHistoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 人员变更历史记录 Service
 *
 * @author shihongwei
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotCompanyChangeHistoryServiceImpl implements IHotCompanyChangeHistoryService {

    private final HotCompanyChangeHistoryMapper baseMapper;
    private final HotCompanyDeptConfigMapper deptConfigMapper;

    @Override
    public HotCompanyChangeHistoryVo queryById(Long id) {
        HotCompanyChangeHistoryVo vo = baseMapper.selectVoById(id);
        if (vo != null) {
            fillDeptInfo(java.util.Collections.singletonList(vo));
        }
        return vo;
    }

    @Override
    public TableDataInfo<HotCompanyChangeHistoryVo> queryPageList(HotCompanyChangeHistoryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotCompanyChangeHistory> lqw = buildQueryWrapper(bo);
        Page<HotCompanyChangeHistoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        fillDeptInfo(result.getRecords());
        return TableDataInfo.build(result);
    }

    @Override
    public List<HotCompanyChangeHistoryVo> queryList(HotCompanyChangeHistoryBo bo) {
        LambdaQueryWrapper<HotCompanyChangeHistory> lqw = buildQueryWrapper(bo);
        List<HotCompanyChangeHistoryVo> list = baseMapper.selectVoList(lqw);
        fillDeptInfo(list);
        return list;
    }

    private void fillDeptInfo(List<HotCompanyChangeHistoryVo> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        Set<Long> deptIds = new HashSet<>();
        for (HotCompanyChangeHistoryVo vo : list) {
            if (vo.getBeforeDeptId() != null) {
                deptIds.add(vo.getBeforeDeptId());
            }
            if (vo.getAfterDeptId() != null) {
                deptIds.add(vo.getAfterDeptId());
            }
        }
        Map<Long, String> deptMap = new HashMap<>();
        if (!deptIds.isEmpty()) {
            List<HotCompanyDeptConfig> depts = deptConfigMapper.selectBatchIds(deptIds);
            for (HotCompanyDeptConfig dept : depts) {
                deptMap.put(dept.getId(), dept.getDeptName());
            }
        }
        for (HotCompanyChangeHistoryVo vo : list) {
            String beforeDeptName = deptMap.get(vo.getBeforeDeptId());
            String afterDeptName = deptMap.get(vo.getAfterDeptId());
            vo.setBeforeDeptName(beforeDeptName);
            vo.setAfterDeptName(afterDeptName);

            if ("调岗调部门".equals(vo.getChangeType())) {
                if (StringUtils.isNotBlank(beforeDeptName)) {
                    vo.setBeforeJobName(buildJobNameWithDept(vo.getBeforeJobName(), beforeDeptName));
                }
                if (StringUtils.isNotBlank(afterDeptName)) {
                    vo.setAfterJobName(buildJobNameWithDept(vo.getAfterJobName(), afterDeptName));
                }
            }
        }
    }

    private String buildJobNameWithDept(String jobName, String deptName) {
        String normalizedJobName = StringUtils.isNotBlank(jobName) ? jobName.trim() : "";
        String fullSuffix = "（" + deptName + "）";
        String fullSuffixWithSpace = " （" + deptName + "）";
        String halfSuffix = "(" + deptName + ")";
        String halfSuffixWithSpace = " (" + deptName + ")";
        String slashSuffix = "/" + deptName;
        String slashSuffixWithSpace = " /" + deptName;
        while (normalizedJobName.endsWith(fullSuffix)
                || normalizedJobName.endsWith(fullSuffixWithSpace)
                || normalizedJobName.endsWith(halfSuffix)
                || normalizedJobName.endsWith(halfSuffixWithSpace)
                || normalizedJobName.endsWith(slashSuffix)
                || normalizedJobName.endsWith(slashSuffixWithSpace)) {
            if (normalizedJobName.endsWith(fullSuffix)) {
                normalizedJobName = normalizedJobName.substring(0, normalizedJobName.length() - fullSuffix.length()).trim();
                continue;
            }
            if (normalizedJobName.endsWith(fullSuffixWithSpace)) {
                normalizedJobName = normalizedJobName.substring(0, normalizedJobName.length() - fullSuffixWithSpace.length()).trim();
                continue;
            }
            if (normalizedJobName.endsWith(halfSuffix)) {
                normalizedJobName = normalizedJobName.substring(0, normalizedJobName.length() - halfSuffix.length()).trim();
                continue;
            }
            if (normalizedJobName.endsWith(halfSuffixWithSpace)) {
                normalizedJobName = normalizedJobName.substring(0, normalizedJobName.length() - halfSuffixWithSpace.length()).trim();
                continue;
            }
            if (normalizedJobName.endsWith(slashSuffix)) {
                normalizedJobName = normalizedJobName.substring(0, normalizedJobName.length() - slashSuffix.length()).trim();
                continue;
            }
            normalizedJobName = normalizedJobName.substring(0, normalizedJobName.length() - slashSuffixWithSpace.length()).trim();
        }
        return normalizedJobName;
    }

    private LambdaQueryWrapper<HotCompanyChangeHistory> buildQueryWrapper(HotCompanyChangeHistoryBo bo) {
        LambdaQueryWrapper<HotCompanyChangeHistory> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCompanyId() != null, HotCompanyChangeHistory::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getEmployeeId() != null, HotCompanyChangeHistory::getEmployeeId, bo.getEmployeeId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), HotCompanyChangeHistory::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getPhone()), HotCompanyChangeHistory::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getChangeType()), HotCompanyChangeHistory::getChangeType, bo.getChangeType());
        lqw.orderByDesc(HotCompanyChangeHistory::getChangeTime);
        return lqw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(HotCompanyChangeHistoryBo bo) {
        HotCompanyChangeHistory add = MapstructUtils.convert(bo, HotCompanyChangeHistory.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(HotCompanyChangeHistoryBo bo) {
        HotCompanyChangeHistory update = MapstructUtils.convert(bo, HotCompanyChangeHistory.class);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteByIds(ids) > 0;
    }
}
