package org.dromara.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
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.dromara.common.satoken.utils.LoginHelper;
import org.dromara.project.domain.BusWorkWage;
import org.dromara.project.domain.enums.BusWageMeasureUnitEnum;
import org.dromara.project.domain.dto.workwage.BusWorkWageCreateReq;
import org.dromara.project.domain.dto.workwage.BusWorkWageQueryReq;
import org.dromara.project.domain.dto.workwage.BusWorkWageUpdateReq;
import org.dromara.project.domain.vo.workwage.BusWorkWageVo;
import org.dromara.project.mapper.BusWorkWageMapper;
import org.dromara.project.service.IBusProjectService;
import org.dromara.project.service.IBusWorkWageService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 工种薪水Service业务层处理
 *
 * @author lcj
 * @date 2025-03-26
 */
@Service
public class BusWorkWageServiceImpl extends ServiceImpl<BusWorkWageMapper, BusWorkWage>
    implements IBusWorkWageService {

    @Resource
    private IBusProjectService projectService;

    /**
     * 查询工种薪水
     *
     * @param id 主键
     * @return 工种薪水
     */
    @Override
    public BusWorkWageVo queryById(Long id) {
        BusWorkWage workWage = this.getById(id);
        if (workWage == null) {
            throw new ServiceException("工种薪水信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(workWage);
    }

    /**
     * 分页查询工种薪水列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 工种薪水分页列表
     */
    @Override
    public TableDataInfo<BusWorkWageVo> queryPageList(BusWorkWageQueryReq req, PageQuery pageQuery) {
        Page<BusWorkWage> result = this.page(pageQuery.build(), buildQueryWrapper(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的工种薪水列表
     *
     * @param req 查询条件
     * @return 工种薪水列表
     */
    @Override
    public List<BusWorkWageVo> queryList(BusWorkWageQueryReq req) {
        LambdaQueryWrapper<BusWorkWage> lqw = buildQueryWrapper(req);
        return this.list(lqw).stream().map(this::getVo).toList();
    }

    /**
     * 新增工种薪水
     *
     * @param req 工种薪水
     * @return 新增工种薪水id
     */
    @Override
    public Long insertByBo(BusWorkWageCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusWorkWage workWage = new BusWorkWage();
        BeanUtils.copyProperties(req, workWage);
        // 数据校验
        validEntityBeforeSave(workWage, true);
        // 判断是否存在
        Long count = this.lambdaQuery()
            .eq(BusWorkWage::getProjectId, workWage.getProjectId())
            .eq(BusWorkWage::getWorkType, workWage.getWorkType())
            .eq(BusWorkWage::getWageCalculationType, workWage.getWageCalculationType())
            .count();
        if (count > 0) {
            throw new ServiceException("该项目已存在该工种薪水信息", HttpStatus.CONFLICT);
        }
        // 填充默认值
        String wageCalculationType = req.getWageCalculationType();
        switch (wageCalculationType) {
            case "1":
                workWage.setWageMeasureUnit(BusWageMeasureUnitEnum.TIME.getValue());
                break;
            case "2":
                workWage.setWageMeasureUnit(BusWageMeasureUnitEnum.PIECE.getValue());
                break;
            default:
                throw new ServiceException("工资计算方式错误", HttpStatus.BAD_REQUEST);
        }
        // 操作数据库
        boolean save = this.save(workWage);
        if (!save) {
            throw new ServiceException("新增工种薪水失败，数据库异常", HttpStatus.ERROR);
        }
        return workWage.getId();
    }

    /**
     * 修改工种薪水
     *
     * @param req 工种薪水
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BusWorkWageUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusWorkWage workWage = new BusWorkWage();
        BeanUtils.copyProperties(req, workWage);
        // 数据校验
        validEntityBeforeSave(workWage, false);
        // 判断是否存在
        BusWorkWage oldWorkWage = this.getById(workWage.getId());
        if (oldWorkWage == null) {
            throw new ServiceException("修改工种薪水失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(workWage);
    }

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

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

    /**
     * 获取工种薪水视图对象
     *
     * @param workWage 工种薪水对象
     * @return 工种薪水视图对象
     */
    @Override
    public BusWorkWageVo getVo(BusWorkWage workWage) {
        // 对象转封装类
        BusWorkWageVo workWageVo = new BusWorkWageVo();
        if (workWage == null) {
            return workWageVo;
        }
        BeanUtils.copyProperties(workWage, workWageVo);
        return workWageVo;
    }

    /**
     * 获取工种薪水查询条件封装
     *
     * @param req 查询条件
     * @return 查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusWorkWage> buildQueryWrapper(BusWorkWageQueryReq req) {
        LambdaQueryWrapper<BusWorkWage> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        Long id = req.getId();
        Long projectId = req.getProjectId();
        String workType = req.getWorkType();
        String isSpecialType = req.getIsSpecialType();
        String wageCalculationType = req.getWageCalculationType();
        Long wage = req.getWage();
        String wageMeasureUnit = req.getWageMeasureUnit();
        String remark = req.getRemark();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(remark), BusWorkWage::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusWorkWage::getId, id);
        lqw.eq(ObjectUtils.isNotEmpty(projectId), BusWorkWage::getProjectId, projectId);
        lqw.eq(StringUtils.isNotBlank(workType), BusWorkWage::getWorkType, workType);
        lqw.eq(StringUtils.isNotBlank(isSpecialType), BusWorkWage::getIsSpecialType, isSpecialType);
        lqw.eq(StringUtils.isNotBlank(wageCalculationType), BusWorkWage::getWageCalculationType, wageCalculationType);
        lqw.eq(ObjectUtils.isNotEmpty(wage), BusWorkWage::getWage, wage);
        lqw.eq(StringUtils.isNotBlank(wageMeasureUnit), BusWorkWage::getWageMeasureUnit, wageMeasureUnit);
        return lqw;
    }

    /**
     * 获取工种薪水分页对象视图
     *
     * @param workWagePage 工种薪水分页对象
     * @return 工种薪水分页对象视图
     */
    @Override
    public Page<BusWorkWageVo> getVoPage(Page<BusWorkWage> workWagePage) {
        List<BusWorkWage> workWageList = workWagePage.getRecords();
        Page<BusWorkWageVo> workWageVoPage = new Page<>(
            workWagePage.getCurrent(),
            workWagePage.getSize(),
            workWagePage.getTotal()
        );
        if (CollUtil.isEmpty(workWageList)) {
            return workWageVoPage;
        }
        List<BusWorkWageVo> workWageVoList = workWageList.stream().map(this::getVo).toList();
        workWageVoPage.setRecords(workWageVoList);
        return workWageVoPage;
    }
}
