package com.goafanti.permission.service.impl;

import com.goafanti.common.bo.Error;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.roleResources;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.*;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.customer.service.CustomerService;
import com.goafanti.permission.bo.RoleBo;
import com.goafanti.permission.bo.RolePermissionBo;
import com.goafanti.permission.service.NewRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class NewRoleServiceImpl extends BaseMybatisDao<RoleMapper> implements NewRoleService {
	@Autowired
	private RoleMapper				roleMapper;
	@Autowired
	private UserMapper				userMapper;
	@Autowired
	private UserRoleMapper			userRoleMapper;
	@Autowired
	private RolePermissionMapper	rolePermissionMapper;
	@Autowired
	private RoleResourcesMapper		roleResourcesMapper;
	@Autowired
	private UserBusinessMapper		userBusinessMapper;
	@Autowired
	private PatentNewMapper			patentNewMapper;
	@Autowired
	private OrganizationContactBookMapper	organizationContactBookMapper;
	@Autowired
	private TOrderNewMapper	tOrderNewMapper;
	@Autowired
	private TOrderMidMapper	tOrderMidMapper;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private UserTransferLogMapper	userTransferLogMapper;
	@Autowired
	private AdminMapper	adminMapper;
	@Autowired
	private TOrderLogMapper	tOrderLogMapper;
	@Autowired
	private AsyncUtils asyncUtils;
	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private UserLockReleaseMapper userLockReleaseMapper;


	@Override
	public Pagination<RoleBo> findRoles(RoleBo role, Integer pageNo, Integer pageSize) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String,Object> params =disposeParams(role);
		@SuppressWarnings("unchecked")
		Pagination<RoleBo> p=(Pagination<RoleBo>)findPage("selectRoleList","selectRoleCount",params,pageNo,pageSize);
		@SuppressWarnings("unchecked")
		List<RoleBo> list=(List<RoleBo>) p.getList();
		for(RoleBo i:list){
			if(i.getCreateTime()!=null){
				i.setCreateTimez(sdf.format(i.getCreateTime()));
			}

		}
		return p;
	}
	private Map<String,Object> disposeParams(RoleBo role){
		Map<String,Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(role.getRoleName())) params.put("roleName", role.getRoleName());
		return params;

	}




	@Override
	public int insert(List<Role> records) {
		return roleMapper.insertBatch(records);
	}

	@Override
	public int deleteByPrimaryKeys(List<String> records) {
		rolePermissionMapper.deleteByRoleId(records);
		userRoleMapper.deleteByRoleId(records);
		List<String> data= userRoleMapper.findUserIdByRoleIds(records);
		TokenManager.clearUserAuthByUserId(data.toArray(new String[]{}));
		return roleMapper.deleteByPrimaryKeys(records);
	}


	@Override
	public int bindPermission(String rid, String pid) {
		TokenManager.clearUserAuthByUserId((String[]) userRoleMapper.findUserIdByRoleId(rid).toArray());
		return rolePermissionMapper.insert(new RolePermission(rid, pid));
	}

	@Override
	public int bindUser(String rid, String uid) {
		TokenManager.clearUserAuthByUserId(new String[] { uid });
		return userRoleMapper.insert(new UserRole(uid, rid));
	}


	@Override
	public int insert(Role record, List<String> permissions) {
		Date now = new Date();
		if (record.getId() != null) {
			List<RolePermission> rps = new ArrayList<>();
			rolePermissionMapper.deleteByRid(record.getId());
			for (String pid : permissions) {
				rps.add(new RolePermission(record.getId(), pid));
			}
			if (!rps.isEmpty()) {
				rolePermissionMapper.insertBatch(rps);
			}
			List<String> ids = userRoleMapper.findUserIdByRoleId(record.getId());
			TokenManager.clearUserAuthByUserId(ids.toArray(new String[ids.size()]));
		}else {
			record.setId(UUID.randomUUID().toString());
		}
		record.getId();
		record.setCreater("管理员");
		record.setCreateTime(now);
		return roleMapper.insert(record);
	}
	@Override
	public List<RolePermissionBo> selectRolePList(String id) {
		List<RolePermissionBo> list=roleMapper.selectRolePList(id);
		return list;
	}
	@Override
	public int addResources(String rid, String resources) {
		List<String> list = Arrays.asList(resources.split(","));
		RoleResources rr=new RoleResources();
		if (roleResourcesMapper.checkRid(rid)>0) {
			roleResourcesMapper.deleteResources(rid);
		}
		for (String s : list) {
			rr.setId(UUID.randomUUID().toString());
			rr.setRoleId(rid);
			rr.setCreateTime(new Date());
			try {
			    rr.setResources(Integer.parseInt(s));
			} catch (NumberFormatException e) {
			    e.printStackTrace();
			}
			roleResourcesMapper.insert(rr);
		}
		return 1;
	}

	@Override
	public int updateDimission(String aid, String transferId) {
		List<Integer> list=roleResourcesMapper.selectAdminRoleResources(aid);
		if (list.isEmpty()||list.get(0)==null) {
			throw new BusinessException(new Error("","用户角色资源不存在"));
		}
		Date date=new Date();
		Admin admin=adminMapper.selectAllByid(aid);
		Admin tadmin=adminMapper.selectAllByid(transferId);
		for (Integer s : list) {
			if (s==roleResources.YXKH.getCode()) {
				userTransferLogMapper.insertUserLog(aid,transferId,date);
				roleResourcesMapper.updateLockRelease("0",aid,transferId);//将用户锁转给指定人
				userBusinessMapper.updateDimissionTransfer(aid,transferId);
				organizationContactBookMapper.updateDimissionTransfer(aid,transferId);
				//所有客户转交给接受者
				transferUserUpdateExamine(aid,transferId);
				userMapper.updateDimissionTransfer(aid,transferId,date);
			}else if (s==roleResources.QDYW.getCode()) {
				userTransferLogMapper.insertUserLockLog(aid,transferId,date);
				patentNewMapper.updateAdmin(aid,transferId);
				roleResourcesMapper.updateLockRelease("1",aid,transferId);//将业务锁转给指定人
			}else if (s == roleResources.YQDD.getCode()) {
				StringBuffer str=new StringBuffer();
				str.append(admin.getName()).append("离职转交到").append(tadmin.getName());
				tOrderLogMapper.insertOrderLog(aid,TokenManager.getAdminId(),date,str.toString());
				tOrderNewMapper.updateSalesmanId(aid, transferId);
				tOrderMidMapper.updateSalesmanId(aid, transferId);
			}else if (s == roleResources.XMRW.getCode()) {
				// 获取被转角色判断修改对应任务角色
				asyncUtils.pushTechTransfer(admin,tadmin,date);

			}else if (s==roleResources.QDYW.getCode()) {
				roleResourcesMapper.updateDimissionTransfer(s,aid,transferId);
			}
		}
		//判定是否要转交财务统计信息
		transferFinanceCount(aid,transferId);
		return 1;
	}

	private void transferFinanceCount(String aid, String transferId) {
		List<Integer> integerList = adminMapper.selectRoleTypeByid(aid);
		List<Integer> integerList1 = adminMapper.selectRoleTypeByid(transferId);
		boolean flag=asyncFinanceCount(integerList);
		boolean flag2=asyncFinanceCount(integerList1);
		if (flag&&flag2) {
			departmentMapper.updateDepFinance(aid,transferId);
		}
		if (flag){
			asyncUtils.financeCoutSwitch(aid);
		}
		if (flag2){
			asyncUtils.financeCoutSwitch(transferId);
		}
	}

	private boolean asyncFinanceCount(List<Integer> integerList) {
		boolean contains = integerList.contains(Integer.parseInt(AFTConstants.FINANCE));
		if (!contains){
			contains = integerList.contains(Integer.parseInt(AFTConstants.FINANCE_MANAGER));
		}
		return contains;
	}


	/**
	 *
	 * @param aid 离职id
	 * @param transferId 转交id
	 */
	private void transferUserUpdateExamine(String aid, String transferId) {
		List<String> uids=userMapper.selectBelongByaid(aid);
		customerService.transferUser(uids,transferId,null);
	}


	@Override
	public List<RoleResources> ResourcesDetail(String rid) {
		return roleResourcesMapper.selectByRid(rid);
	}

}
