package org.dromara.personnel.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.personnel.domain.enums.BusWageMeasureUnitEnum;
import org.dromara.system.api.RemoteProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.personnel.domain.bo.OpsWorkWageBo;
import org.dromara.personnel.domain.vo.OpsWorkWageVo;
import org.dromara.personnel.domain.OpsWorkWage;
import org.dromara.personnel.mapper.OpsWorkWageMapper;
import org.dromara.personnel.service.IOpsWorkWageService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 工种薪水Service业务层处理
 *
 * @author LionLi
 * @date 2025-09-17
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OpsWorkWageServiceImpl extends ServiceImpl<OpsWorkWageMapper,OpsWorkWage> implements IOpsWorkWageService {

    private final OpsWorkWageMapper baseMapper;

    @Autowired
    private RemoteProjectService remoteProjectService;

    /**
     * 查询工种薪水
     *
     * @param id 主键
     * @return 工种薪水
     */
    @Override
    public OpsWorkWageVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询工种薪水列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 工种薪水分页列表
     */
    @Override
    public TableDataInfo<OpsWorkWageVo> queryPageList(OpsWorkWageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OpsWorkWage> lqw = buildQueryWrapper(bo);
        Page<OpsWorkWageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的工种薪水列表
     *
     * @param bo 查询条件
     * @return 工种薪水列表
     */
    @Override
    public List<OpsWorkWageVo> queryList(OpsWorkWageBo bo) {
        LambdaQueryWrapper<OpsWorkWage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OpsWorkWage> buildQueryWrapper(OpsWorkWageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OpsWorkWage> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(OpsWorkWage::getId);
        lqw.eq(bo.getProjectId() != null, OpsWorkWage::getProjectId, bo.getProjectId());
        lqw.eq(StringUtils.isNotBlank(bo.getWorkType()), OpsWorkWage::getWorkType, bo.getWorkType());
        lqw.eq(StringUtils.isNotBlank(bo.getIsSpecialType()), OpsWorkWage::getIsSpecialType, bo.getIsSpecialType());
        lqw.eq(StringUtils.isNotBlank(bo.getWageCalculationType()), OpsWorkWage::getWageCalculationType, bo.getWageCalculationType());
        lqw.eq(bo.getWage() != null, OpsWorkWage::getWage, bo.getWage());
        lqw.eq(StringUtils.isNotBlank(bo.getWageMeasureUnit()), OpsWorkWage::getWageMeasureUnit, bo.getWageMeasureUnit());
        return lqw;
    }

    /**
     * 新增工种薪水
     *
     * @param bo 工种薪水
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OpsWorkWageBo bo) {
        OpsWorkWage add = MapstructUtils.convert(bo, OpsWorkWage.class);
        validEntityBeforeSave(add,true);
        // 判断是否存在
        Long count = baseMapper.selectCount(new LambdaQueryWrapper<OpsWorkWage>()
            .eq(OpsWorkWage::getProjectId, bo.getProjectId())
            .eq(OpsWorkWage::getWorkType, bo.getWorkType())
            .eq(OpsWorkWage::getWageCalculationType, bo.getWageCalculationType()));
        if (count > 0) {
            throw new ServiceException("该项目已存在该工种薪水信息", HttpStatus.CONFLICT);
        }
        // 填充默认值
        String wageCalculationType = bo.getWageCalculationType();
        switch (wageCalculationType) {
            case "1":
                add.setWageMeasureUnit(BusWageMeasureUnitEnum.TIME.getValue());
                break;
            case "2":
                add.setWageMeasureUnit(BusWageMeasureUnitEnum.PIECE.getValue());
                break;
            default:
                throw new ServiceException("工资计算方式错误", HttpStatus.BAD_REQUEST);
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改工种薪水
     *
     * @param bo 工种薪水
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OpsWorkWageBo bo) {
        OpsWorkWage update = MapstructUtils.convert(bo, OpsWorkWage.class);
        validEntityBeforeSave(update,false);
        // 判断是否存在
        OpsWorkWage oldWorkWage = baseMapper.selectById(update.getId());
        if (oldWorkWage == null) {
            throw new ServiceException("修改工种薪水失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OpsWorkWage entity, Boolean create){
        //TODO 做一些数据校验,如唯一约束
        // 做一些数据校验,如唯一约束
        Long userId = LoginHelper.getUserId();
        Long projectId = entity.getProjectId();
        if (create) {
            if (projectId == null) {
                throw new ServiceException("项目id不能为空", HttpStatus.BAD_REQUEST);
            }
        }
        if (projectId != null && remoteProjectService.getById(projectId) == null) {
            throw new ServiceException("对应项目不存在", HttpStatus.NOT_FOUND);
        }
        remoteProjectService.validAuth(projectId, userId);
    }

    /**
     * 校验并批量删除工种薪水信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            // 获取当前登录用户
            Long userId = LoginHelper.getUserId();
            // 获取待删除数据详情
            List<OpsWorkWage> workWageList = baseMapper.selectByIds(ids);
            if (isValid) {
                // TODO 做一些业务上的校验,判断是否需要校验
                List<Long> projectIdList = workWageList.stream().map(OpsWorkWage::getProjectId).toList();
                remoteProjectService.validAuth(projectIdList, userId);
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
