package com.rongwei.sfcommon.sys.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rongwe.scentity.vo.DepartmentAndPersonnelReq;
import com.rongwe.scentity.vo.DepartmentVo;
import com.rongwe.scentity.vo.PersonnelVo;
import com.rongwei.rwadmincommon.system.domain.SysOrganizationDo;
import com.rongwei.rwadmincommon.system.domain.SysUserDo;
import com.rongwei.rwadmincommon.system.domain.SysUserOrgDo;
import com.rongwei.rwadmincommon.system.domain.SysUserRoleDo;
import com.rongwei.rwadmincommon.system.service.SysOrganizationService;
import com.rongwei.rwadmincommon.system.service.SysUserOrgService;
import com.rongwei.rwadmincommon.system.service.SysUserRoleService;
import com.rongwei.rwadmincommon.system.service.SysUserService;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.sfcommon.sys.dao.DepartmentAndPersonnelDao;
import com.rongwei.sfcommon.sys.service.DepartmentAndPersonnelService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Service
@Log4j2
public class DepartmentAndPersonnelServiceImpl implements DepartmentAndPersonnelService {
    @Autowired
    private SysOrganizationService sysOrganizationService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserOrgService sysUserOrgService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Resource
    private DepartmentAndPersonnelDao departmentAndPersonnelDao;

    @Override
    @Transactional
    public R departmentAndPersonnel(DepartmentAndPersonnelReq req) {
        //部门数据
        List<DepartmentVo> departmentList = req.getDepartmentList();
        log.info("接收到部门数据：{}条", departmentList.size());
        //员工数据
        List<PersonnelVo> personnelList = req.getPersonnelList();
        log.info("接收到员工数据：{}条", personnelList.size());

        List<SysOrganizationDo> insertDepartList = new LinkedList<>();
        List<SysOrganizationDo> updateDepartList = new LinkedList<>();
        List<String> deleteDepartIdList = new LinkedList<>();
        //=======================开始处理部门数据======================
        if (ObjectUtil.isNotEmpty(departmentList)) {
            //查询本系统中已有的部门信息
            List<SysOrganizationDo> sysOrganizationDoList = sysOrganizationService.list();
            //遍历入参部门 判断新增、修改、删除

            for (DepartmentVo departmentVo : departmentList) {
                //筛选部门ID
                SysOrganizationDo sysOrganizationDo = sysOrganizationDoList.stream().filter(item -> item.getId().equals(departmentVo.getDepartmentid())).findFirst().orElse(null);
                //如果不存在 并且没有被冻结使用，则新增
                if (ObjectUtil.isEmpty(sysOrganizationDo) && departmentVo.getCanceled() != 1) {
                    SysOrganizationDo insertSysOrganization = new SysOrganizationDo();
                    insertSysOrganization.setId(departmentVo.getDepartmentid());
                    insertSysOrganization.setCode(departmentVo.getDepartmentcode());
                    insertSysOrganization.setFullname(departmentVo.getDepartmentname());
                    insertSysOrganization.setShortname(departmentVo.getDepartmentname());
                    if (ObjectUtil.isNotEmpty(departmentVo.getSupdepid())) {
                        insertSysOrganization.setPid(departmentVo.getSupdepid());
                    } else {
                        insertSysOrganization.setPid("-1");
                    }
                    //TODO:补充平台构造部门字段
                    insertSysOrganization.setIsleaf("n");
                    //如果名字中带有“有限公司”
                    if (departmentVo.getDepartmentname().contains("有限公司")) {
                        insertSysOrganization.setOrgtype("Branch-Office");
                    }
                    insertSysOrganization.setEnabled("y");

                    insertDepartList.add(insertSysOrganization);
                } else {
                    //冻结，则删除
                    if (departmentVo.getCanceled() == 1) {
                        deleteDepartIdList.add(departmentVo.getDepartmentid());
                    } else {
                        sysOrganizationDo.setCode(departmentVo.getDepartmentcode());
                        sysOrganizationDo.setPid(departmentVo.getSupdepid());
                        sysOrganizationDo.setFullname(departmentVo.getDepartmentname());
                        sysOrganizationDo.setShortname(departmentVo.getDepartmentname());
                        if (ObjectUtil.isNotEmpty(departmentVo.getSupdepid())) {
                            sysOrganizationDo.setPid(departmentVo.getSupdepid());
                        } else {
                            sysOrganizationDo.setPid("-1");
                        }
                        //TODO:补充平台构造部门字段
                        sysOrganizationDo.setIsleaf("n");
                        //如果名字中带有“有限公司”
                        if (departmentVo.getDepartmentname().contains("有限公司")) {
                            sysOrganizationDo.setOrgtype("Branch-Office");
                        }
                        sysOrganizationDo.setEnabled("y");

                        updateDepartList.add(sysOrganizationDo);
                    }
                }
            }

        }
        //=======================开始处理员工数据======================
        List<SysUserDo> insertUserList = new LinkedList<>();
        List<SysUserDo> updateUserList = new LinkedList<>();
        List<String> deleteUserIdList = new LinkedList<>();
        //员工-部门关系
        List<String> deleteUserOrgByUserIdList = new LinkedList<>();//根据用户ID批量删除
        List<SysUserOrgDo> insertUserOrgList = new LinkedList<>();
        //员工-角色关系(新增的员工，给予一个默认的角色)
        List<SysUserRoleDo> insertUserRoleList = new LinkedList<>();
        if (ObjectUtil.isNotEmpty(personnelList)) {
            //查询本系统中已有的员工数据
            List<SysUserDo> sysUserDoList = sysUserService.list();
            for (PersonnelVo personnelVo : personnelList) {
                SysUserDo sysUserDo = sysUserDoList.stream().filter(item -> item.getAccount().equals(personnelVo.getWorkcode())).findFirst().orElse(null);
                //不存在 并且在职，则新增
                if (ObjectUtil.isEmpty(sysUserDo) && personnelVo.getStatus() == 1) {
                    SysUserDo insertUser = new SysUserDo();
                    insertUser.setId(SecurityUtil.getUUID());
                    insertUser.setAccount(personnelVo.getWorkcode());
                    insertUser.setName(personnelVo.getLastname());
                    //TODO:待完善平台用户其他字段
                    insertUser.setCode(personnelVo.getWorkcode());
                    insertUser.setPassword(SecurityUtil.getSaltMd5AndSha("000000", insertUser.getId()));//新增用户初始化密码为“000000”
                    insertUserList.add(insertUser);

                    SysUserOrgDo insertUserOrg = new SysUserOrgDo();
                    insertUserOrg.setId(SecurityUtil.getUUID());
                    insertUserOrg.setUserid(insertUser.getId());
                    insertUserOrg.setOrgid(personnelVo.getDepartmentid());
                    insertUserOrgList.add(insertUserOrg);

                    //新增用户给予默认角色
                    SysUserRoleDo insertUserRole = new SysUserRoleDo();
                    insertUserRole.setId(SecurityUtil.getUUID());
                    insertUserRole.setUserid(insertUser.getId());
                    insertUserRole.setRoleid("58fb8df3bebb48d58e8a2be261c32774");//普通员工 角色
                    insertUserRoleList.add(insertUserRole);
                } else {
                    //不是在职，则删除
                    if (personnelVo.getStatus() != 1) {
                        deleteUserIdList.add(sysUserDo.getId());
                        deleteUserOrgByUserIdList.add(sysUserDo.getId());
                    } else {
                        sysUserDo.setAccount(personnelVo.getWorkcode());
                        sysUserDo.setName(personnelVo.getLastname());
                        sysUserDo.setCode(personnelVo.getWorkcode());
                        updateUserList.add(sysUserDo);

                        deleteUserOrgByUserIdList.add(personnelVo.getWorkcode());

                        SysUserOrgDo insertUserOrg = new SysUserOrgDo();
                        insertUserOrg.setId(SecurityUtil.getUUID());
                        insertUserOrg.setUserid(personnelVo.getWorkcode());
                        insertUserOrg.setOrgid(personnelVo.getDepartmentid());
                        insertUserOrgList.add(insertUserOrg);
                    }
                }
            }

        }
        //批量导入/修改部门
        if (ObjectUtil.isNotEmpty(deleteDepartIdList)) {
//            sysOrganizationService.removeByIds(deleteDepartIdList);
            departmentAndPersonnelDao.deleteOrgByIds(deleteDepartIdList);
        }

        if (ObjectUtil.isNotEmpty(updateDepartList)) {
            sysOrganizationService.updateBatchById(updateDepartList);
        }
        if (ObjectUtil.isNotEmpty(insertDepartList)) {
            sysOrganizationService.saveBatch(insertDepartList);
        }

        //批量导入/修改用户
        if (ObjectUtil.isNotEmpty(deleteUserIdList)) {
            sysUserService.removeByIds(deleteUserIdList);
//            departmentAndPersonnelDao.deleteUserById(deleteUserIdList);
        }
        if (ObjectUtil.isNotEmpty(updateUserList)) {
            sysUserService.updateBatchById(updateUserList);
        }
        if (ObjectUtil.isNotEmpty(insertUserList)) {
            sysUserService.saveBatch(insertUserList);
        }

        //批量导入/修改 用户-部门
        if (ObjectUtil.isNotEmpty(deleteUserOrgByUserIdList)) {
            sysUserOrgService.remove(new QueryWrapper<SysUserOrgDo>().lambda().in(SysUserOrgDo::getUserid, deleteUserOrgByUserIdList));
        }
        if (ObjectUtil.isNotEmpty(insertUserOrgList)) {
            sysUserOrgService.saveBatch(insertUserOrgList);
        }

        //初始化批量导入/修改 用户-角色
        if (ObjectUtil.isNotEmpty(insertUserRoleList)) {
            sysUserRoleService.saveBatch(insertUserRoleList);
        }

        String res = "成功，部门新增" + insertDepartList.size() + "个，更新" + updateDepartList.size() + "个，删除" + deleteDepartIdList.size() + "个，员工新增" + insertUserList.size() + "个，更新" + updateUserList.size() + "个，删除" + deleteUserIdList.size() + "个";
        return R.ok(res);
    }
}
