package com.gci.boot.modules.driver.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gci.boot.constant.CommonConstant;
import com.gci.boot.modules.basedata.entity.TbCustomerArchives;
import com.gci.boot.modules.basedata.service.ITbCustomerArchivesService;
import com.gci.boot.modules.driver.entity.TbDriver;
import com.gci.boot.modules.driver.mapper.TbDriverMapper;
import com.gci.boot.modules.driver.service.ITbDriverService;
import com.gci.boot.modules.driver.vo.DriverUserVo;
import com.gci.boot.modules.system.entity.SysDepart;
import com.gci.boot.modules.system.entity.SysRole;
import com.gci.boot.modules.system.entity.SysUser;
import com.gci.boot.modules.system.service.ISysDepartService;
import com.gci.boot.modules.system.service.ISysRoleService;
import com.gci.boot.modules.system.service.ISysUserService;
import com.gci.boot.modules.system.vo.LoginUser;

/**
 * <p>
 *  司机档案 服务实现类
 * </p>
 *
 * @author xushuhan
 * @since 2023-09-04
 */
@Service
public class TbDriverServiceImpl extends ServiceImpl<TbDriverMapper, TbDriver> implements ITbDriverService {
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysRoleService sysRoleService;
	@Autowired
	private ISysDepartService sysDepartService;
    @Autowired
    private ITbCustomerArchivesService tbCustomerArchivesService;
	@Override
	public void updateStatus(TbDriver item) {
		item = getById(item.getId());
		if(CommonConstant.STATUS_1.equals(item.getStatus())) {
			item.setStatus(CommonConstant.STATUS_0);
			updateById(item);
		}else if(CommonConstant.STATUS_0.equals(item.getStatus())) {
			item.setStatus(CommonConstant.STATUS_1);
			updateById(item);
		}

		if(StringUtils.isNotBlank(item.getUserId())){
			SysUser user = sysUserService.getById(item.getUserId());
			if(user != null){
				//根据作废状态和入职状态冻结账号
				if(CommonConstant.STATUS_1.equals(item.getStatus())&&CommonConstant.STATUS_1.equals(item.getEntryStatus())) {
					user.setStatus(1);
				}else {
					user.setStatus(2);
				}
				sysUserService.updateById(user);
			}
		}
		
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void addDriverWithUserBatch(List<DriverUserVo> items){
		for(DriverUserVo v:items){
			addDriverWithUser(v);
		}
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void addDriverWithUser(DriverUserVo item){
		//保存司机信息
		TbDriver tbDriver = new TbDriver();
		BeanUtils.copyProperties(item, tbDriver);
		save(tbDriver);

		if(StringUtils.isNotBlank(item.getUsername())){
			//提取用户信息
			SysUser user = new SysUser();
			BeanUtils.copyProperties(item, user);
			user.setRealname(item.getName());
			//处理司机跟用户性别转换
			if("1".equals(item.getSex())){
				user.setSex(1);
			}else if ("0".equals(item.getSex())){
				user.setSex(2);
			}else{
				user.setSex(0);
			}

			//获取角色
			List<String> roleList = new ArrayList<>();
			SysRole role = sysRoleService.lambdaQuery().eq(SysRole::getRoleCode, "Driver").one();
			if(role != null) {
				roleList.add(role.getId());
			}
			//获取所属客户机构填充
			TbCustomerArchives com = tbCustomerArchivesService.getById(item.getCustomerId());
			if(StringUtils.isBlank(user.getOrgCode())&&com!=null) {
				user.setOrgCode(com.getSysOrgCode());
			}
			//新创建用户根据当前创建人的部门设置部门..新建用户没有orgCode,保存数据时会自动设置为当前创建人的部门
			if(StringUtils.isBlank(user.getOrgCode())){
				LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				user.setOrgCode(sysUser.getOrgCode());
			}
			//获取部门
			List<String> depList = null;
			if(StringUtils.isNotBlank(user.getOrgCode())) {
				List<SysDepart> list = sysDepartService.lambdaQuery().eq(SysDepart::getOrgCode, user.getOrgCode()).list();
				if(list.size()>0){
					depList = list.stream().map(SysDepart::getId).collect(Collectors.toList());
				}
			}
			//根据作废状态和入职状态冻结账号
			if(CommonConstant.STATUS_0.equals(item.getStatus())||CommonConstant.STATUS_0.equals(item.getEntryStatus())) {
				user.setStatus(2);
			}else {
				user.setStatus(1);
			}
			//保存用户信息
			sysUserService.addUserEncryptPassword(user, roleList,  depList);
			tbDriver.setUserId(user.getId());
			updateById(tbDriver);
		}
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void editDriverWithUser(DriverUserVo item){
		//保存司机信息
		TbDriver tbDriver = new TbDriver();
		BeanUtils.copyProperties(item, tbDriver);
		updateById(tbDriver);
		if(StringUtils.isNotBlank(item.getUsername())){
			SysUser user;
			if(tbDriver.getUserId() != null){
				user = sysUserService.getById(tbDriver.getUserId());
				if(user != null){
					user.setRealname(item.getName());
					user.setPhone(item.getPhone());
					user.setTelephone(item.getTelephone());
					user.setBirthday(item.getBirthday());
					user.setWorkNo(item.getWorkNo());
					if(StringUtils.isNotBlank(item.getPassword())){
						user.setPassword(item.getPassword());
					}else {
						user.setPassword(null);
					}
				}
			}else{
				//提取用户信息
				user = new SysUser();
				BeanUtils.copyProperties(item, user);
				user.setRealname(item.getName());
			}

			//获取角色
			List<String> roleList = new ArrayList<>();
			SysRole role = sysRoleService.lambdaQuery().eq(SysRole::getRoleCode, "Driver").one();
			if(role != null) {
				roleList.add(role.getId());
			}
			//获取所属客户机构填充
			TbCustomerArchives com = tbCustomerArchivesService.getById(item.getCustomerId());
			if(StringUtils.isBlank(user.getOrgCode())&&com!=null) {
				user.setOrgCode(com.getSysOrgCode());
			}
			//获取部门
			List<String> depList = null;
			if(StringUtils.isNotBlank(user.getOrgCode())) {
				List<SysDepart> list = sysDepartService.lambdaQuery().eq(SysDepart::getOrgCode, user.getOrgCode()).list();
				if(list.size()>0){
					depList = list.stream().map(SysDepart::getId).collect(Collectors.toList());
				}
			}
			//根据作废状态和入职状态冻结账号
			if(CommonConstant.STATUS_0.equals(item.getStatus())||CommonConstant.STATUS_0.equals(item.getEntryStatus())) {
				user.setStatus(2);
			}else {
				user.setStatus(1);
			}
			//保存用户信息
			if(user.getId() == null){
				sysUserService.addUserEncryptPassword(user, roleList,  depList);
				tbDriver.setUserId(user.getId());
				updateById(tbDriver);
			}else{
				sysUserService.editUserEncryptPassword(user, roleList, depList);
			}
		}
	}

	@Transactional
	@Override
	public void delete(String id){
		TbDriver d = getById(id);
		if(d != null){
			removeById(d.getId());
			sysUserService.delete(d.getUserId());
		}
	}

	@Override
	public IPage<DriverUserVo> pageWithUserInfo(IPage page, Wrapper wrapper){
		IPage<DriverUserVo> p = baseMapper.pageWithUserInfo(page, wrapper);

		if(p.getRecords().size()>0){
			List<String> userIdList = p.getRecords().stream().map(DriverUserVo::getUserId).collect(Collectors.toList());
			Map<String, String> userRoleIds = sysUserService.getUserRoleIds(userIdList);
			p.getRecords().forEach(d->{
				if(StringUtils.isBlank(d.getUserId())){
					return;
				}
				d.setRoleIds(userRoleIds.get(d.getUserId()));
			});
		}
		return p;
	}


}
