package com.ruoyi.pay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.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 com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.pay.domain.bo.PayEmployeeInfoBo;
import com.ruoyi.pay.domain.vo.PayEmployeeInfoVo;
import com.ruoyi.pay.domain.PayEmployeeInfo;
import com.ruoyi.pay.mapper.PayEmployeeInfoMapper;
import com.ruoyi.pay.service.IPayEmployeeInfoService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 员工信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-12
 */
@RequiredArgsConstructor
@Service
public class PayEmployeeInfoServiceImpl implements IPayEmployeeInfoService {

    private final PayEmployeeInfoMapper baseMapper;
    private final ISysUserService userService;
    private final ISysRoleService roleService;

    /**
     * 查询员工信息
     */
    @Override
    public PayEmployeeInfoVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询员工信息列表
     */
    @Override
    public TableDataInfo<PayEmployeeInfoVo> queryPageList(PayEmployeeInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayEmployeeInfo> lqw = buildQueryWrapper(bo);
        Page<PayEmployeeInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询员工信息列表
     */
    @Override
    public List<PayEmployeeInfoVo> queryList(PayEmployeeInfoBo bo) {
        LambdaQueryWrapper<PayEmployeeInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayEmployeeInfo> buildQueryWrapper(PayEmployeeInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PayEmployeeInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTenantId() != null, PayEmployeeInfo::getTenantId, bo.getTenantId());
        lqw.eq(bo.getUserId() != null, PayEmployeeInfo::getUserId, bo.getUserId());
        lqw.eq(bo.getDeptId() != null, PayEmployeeInfo::getDeptId, bo.getDeptId());
        lqw.like(StringUtils.isNotBlank(bo.getDeptName()), PayEmployeeInfo::getDeptName, bo.getDeptName());
        lqw.like(StringUtils.isNotBlank(bo.getName()), PayEmployeeInfo::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), PayEmployeeInfo::getSex, bo.getSex());
        lqw.eq(bo.getAge() != null, PayEmployeeInfo::getAge, bo.getAge());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), PayEmployeeInfo::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getIdcard()), PayEmployeeInfo::getIdcard, bo.getIdcard());
        lqw.eq(StringUtils.isNotBlank(bo.getBankCardNumber()), PayEmployeeInfo::getBankCardNumber, bo.getBankCardNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getOpeningBank()), PayEmployeeInfo::getOpeningBank, bo.getOpeningBank());
        lqw.eq(bo.getBasicSalary() != null, PayEmployeeInfo::getBasicSalary, bo.getBasicSalary());
        lqw.eq(bo.getDaySalary() != null, PayEmployeeInfo::getDaySalary, bo.getDaySalary());
        lqw.eq(bo.getHourSalary() != null, PayEmployeeInfo::getHourSalary, bo.getHourSalary());
        lqw.eq(StringUtils.isNotBlank(bo.getRestType()), PayEmployeeInfo::getRestType, bo.getRestType());
        lqw.eq(bo.getHoursPerDay() != null, PayEmployeeInfo::getHoursPerDay, bo.getHoursPerDay());
        lqw.eq(StringUtils.isNotBlank(bo.getPayCalcType()), PayEmployeeInfo::getPayCalcType, bo.getPayCalcType());
        lqw.eq(StringUtils.isNotBlank(bo.getEducation()), PayEmployeeInfo::getEducation, bo.getEducation());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), PayEmployeeInfo::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getContact()), PayEmployeeInfo::getContact, bo.getContact());
        lqw.eq(StringUtils.isNotBlank(bo.getContactPhone()), PayEmployeeInfo::getContactPhone, bo.getContactPhone());
        lqw.eq(bo.getZhijian() != null, PayEmployeeInfo::getZhijian, bo.getZhijian());
        lqw.eq(bo.getYewu() != null, PayEmployeeInfo::getYewu, bo.getYewu());
        lqw.eq(bo.getHtstime() != null, PayEmployeeInfo::getHtstime, bo.getHtstime());
        lqw.eq(bo.getHtetime() != null, PayEmployeeInfo::getHtetime, bo.getHtetime());
        lqw.eq(bo.getDeleted() != null, PayEmployeeInfo::getDeleted, bo.getDeleted());
        return lqw;
    }

    /**
     * 新增员工信息  默认手机号为用户名、密码
     */
    @Override
    @Transactional
    public Boolean insertByBo(PayEmployeeInfoBo bo) {
        //  新增一个系统员工
        SysUser sysUser = new SysUser();
        sysUser.setNickName(bo.getName());
        sysUser.setUserName(bo.getPhone());
        sysUser.setPassword(bo.getPhone());
        sysUser.setDeptId(bo.getDeptId());
        sysUser.setSex(bo.getSex());
        sysUser.setPhonenumber(bo.getPhone());
        sysUser.setCreateBy(LoginHelper.getUsername());
        sysUser.setTenantId(bo.getTenantId());
        /*sysUser.setRoleIds();
        sysUser.setPostIds();*/
        //查询角色，如果有普通员工角色则添加这个角色到用户
        SysRole role = new SysRole();
        role.setTenantId(bo.getTenantId());
        List<SysRole> sysRoles = roleService.selectRoleList(role);
        if(sysRoles!=null&&sysRoles.size()>0){
            Long[] roleids = new Long[1];
            for(SysRole sysRole :sysRoles){
                if(sysRole.getRoleKey().equals("yg")){
                    roleids[0]=sysRole.getRoleId();
                    sysUser.setRoleIds(roleids);
                    break;
                }
            }
        }
        int id = userService.insertUser(sysUser);

        // 关联用户ID
        bo.setUserId(sysUser.getUserId());

        PayEmployeeInfo add = BeanUtil.toBean(bo, PayEmployeeInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改员工信息
     */
    @Override
    public Boolean updateByBo(PayEmployeeInfoBo bo) {
        PayEmployeeInfo update = BeanUtil.toBean(bo, PayEmployeeInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PayEmployeeInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除员工信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int updateSgrEmployeeHour(String oldHour, String newHour,Long tenantId) {
        return  baseMapper.updateSgrEmployeeHour(oldHour,newHour,tenantId);
    }

    @Override
    public List<PayEmployeeInfoVo> getSalesmanList(PayEmployeeInfoBo bo) {
        return baseMapper.getSalesmanList(bo.getTenantId());
    }
}
