package com.ruoyi.kaohe.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.kaohe.mapper.KhEmployeeMapper;
import com.ruoyi.kaohe.domain.KhEmployee;
import com.ruoyi.kaohe.service.IKhEmployeeService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 职工信息Service业务层处理
 *
 * @author hs
 * @date 2025-06-17
 */
@Service
public class KhEmployeeServiceImpl implements IKhEmployeeService {
    @Resource
    private KhEmployeeMapper khEmployeeMapper;
    @Resource
    private SysDeptMapper deptMapper;
    @Autowired
    private ISysUserService userService;

    private static final Logger log = LoggerFactory.getLogger(KhEmployeeServiceImpl.class);

    /**
     * 查询职工信息
     *
     * @param id 职工信息主键
     * @return 职工信息
     */
    @Override
    public KhEmployee selectKhEmployeeById(Long id) {
        return khEmployeeMapper.selectKhEmployeeById(id);
    }

    /**
     * 查询职工信息列表
     *
     * @param khEmployee 职工信息
     * @return 职工信息
     */
    @Override
    public List<KhEmployee> selectKhEmployeeList(KhEmployee khEmployee) {
        return khEmployeeMapper.selectKhEmployeeList(khEmployee);
    }

    /**
     * 新增职工信息
     *
     * @param khEmployee 职工信息
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertKhEmployee(KhEmployee khEmployee) {
        khEmployee.setCreateTime(DateUtils.getNowDate());
        // 验证是否存在这个职工   工号唯一性
        KhEmployee param = new KhEmployee();
        param.setWordId(khEmployee.getWordId());
        List<KhEmployee> e = khEmployeeMapper.selectKhEmployeeList(param);
        if (StringUtils.isNull(e) || e.size() == 0) {
            int r = khEmployeeMapper.insertKhEmployee(khEmployee);
            ///生成对应的用户账号，工号为账号
            SysUser user= new SysUser();
            user.setUserName(khEmployee.getWordId());
            if (userService.checkUserNameUnique(user))
            {
                user.setCreateBy(getUsername());
                user.setNickName(khEmployee.getEmpName());
                user.setPassword(SecurityUtils.encryptPassword("111111"));
                user.setDeptId(khEmployee.getDeptId());
                Long[] roleIds = {102L};  //固定的职工账号角色id
                user.setRoleIds(roleIds);
                userService.insertUser(user);
            }
            return r>0 ? AjaxResult.success() : AjaxResult.error();
        }else{
            return AjaxResult.error("工号已存在！");
        }

    }

    /**
     * 修改职工信息
     *
     * @param khEmployee 职工信息
     * @return 结果
     */
    @Override
    public AjaxResult updateKhEmployee(KhEmployee khEmployee) {
        //如果修改了工号，验证工号不能已存在其他职工上面
        KhEmployee param = new KhEmployee();
        param.setWordId(khEmployee.getWordId());
        List<KhEmployee> e = khEmployeeMapper.selectKhEmployeeList(param);
        if (e!=null&& e.size() == 1) {
            if(!e.get(0).getId().equals(khEmployee.getId())){
                return AjaxResult.error("修改失败，工号已存在！");
            }else{//没有修改员工工号  则直接修改
                return khEmployeeMapper.updateKhEmployee(khEmployee)>0 ? AjaxResult.success() : AjaxResult.error();
            }
        }else{ //给当前员工，修改了一个新的工号
            khEmployee.setUpdateTime(DateUtils.getNowDate());
            int r =khEmployeeMapper.updateKhEmployee(khEmployee);
            ///生成对应的用户账号，工号为账号
            SysUser user= new SysUser();
            user.setUserName(khEmployee.getWordId());
            if (userService.checkUserNameUnique(user))
            {
                user.setCreateBy(getUsername());
                user.setNickName(khEmployee.getEmpName());
                user.setPassword(SecurityUtils.encryptPassword("111111"));
                user.setDeptId(khEmployee.getDeptId());
                Long[] roleIds = {102L};  //固定的职工账号角色id
                user.setRoleIds(roleIds);
                userService.insertUser(user);
            }
            return r>0 ? AjaxResult.success() : AjaxResult.error();
        }
    }

    @Override
    public AjaxResult updateKhEmployeeDocs(KhEmployee khEmployee) {
        return khEmployeeMapper.updateKhEmployee(khEmployee)>0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 批量删除职工信息
     *
     * @param ids 需要删除的职工信息主键
     * @return 结果
     */
    @Override
    public int deleteKhEmployeeByIds(Long[] ids) {
        return khEmployeeMapper.deleteKhEmployeeByIds(ids);
    }

    /**
     * 删除职工信息信息
     *
     * @param id 职工信息主键
     * @return 结果
     */
    @Override
    public int deleteKhEmployeeById(Long id) {
        return khEmployeeMapper.deleteKhEmployeeById(id);
    }

    @Override
    @Transactional
    public String importEmp(List<KhEmployee> empList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(empList) || empList.size() == 0) {
            throw new ServiceException("导入职工数据不能为空！");
        }
        List<KhEmployee>   userEmp = new ArrayList<KhEmployee>();//存放需要生成用户的
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (KhEmployee employee : empList) {
            try {
                if(StringUtils.isEmpty(employee.getSex())){
                    employee.setSex("2");
                }
                //根据deptId查询deptName
                SysDept sysDept = deptMapper.selectDeptById(employee.getDeptId());
                employee.setDeptName(sysDept.getDeptName());
                // 验证是否存在这个职工   工号唯一性
                KhEmployee param = new KhEmployee();
                param.setWordId(employee.getWordId());
                List<KhEmployee> e = khEmployeeMapper.selectKhEmployeeList(param);
                if (StringUtils.isNull(e) || e.size() == 0) {
                    employee.setCreateBy(getUsername());
                    khEmployeeMapper.insertKhEmployee(employee);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、工号 " + employee.getWordId() + " 导入成功");
                    ///生成对应的用户账号，工号为账号
                    SysUser user= new SysUser();
                    user.setUserName(employee.getWordId());
                    if (userService.checkUserNameUnique(user))
                    {
                        user.setCreateBy(getUsername());
                        user.setNickName(employee.getEmpName());
                        user.setPassword(SecurityUtils.encryptPassword("111111"));
                        user.setDeptId(employee.getDeptId());
                        Long[] roleIds = {102L};  //固定的评分账号角色id
                        user.setRoleIds(roleIds);
                        userService.insertUser(user);
                    }
                } else if (updateSupport) {
                    employee.setId(e.get(0).getId());
                    khEmployeeMapper.updateKhEmployee(employee);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、工号 " + employee.getWordId() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、工号 " + employee.getWordId() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、工号 " + employee.getWordId() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
