package com.blueland.user.staff;


/**
 * @author 代码自动生成工具
 * @version 1.0
 * @since  
 */
 
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blueland.annotation.ApiVersion;
import com.blueland.constant.RedisConstant;
import cn.hutool.core.util.ObjectUtil;
import com.blueland.annotation.Log;
import com.blueland.bo.*;
import com.blueland.core.util.UserUtils;
import com.blueland.enums.Version;
import com.blueland.model.TUcOrg;
import com.blueland.model.TUcStaff;
import com.blueland.result.R;
import com.blueland.service.ITucOrgService;
import com.blueland.service.ITucStaffService;
import com.blueland.service.SysRedisService;
import com.blueland.vo.StaffPostVO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.druid.util.StringUtils;

import static com.blueland.constant.CommonConstant.*;


@Slf4j
@RestController
@RequestMapping(value = "/staff")
public class StaffRest {
	@Autowired
	private ITucStaffService tucStaffService;
	@Autowired
	private ITucOrgService tucOrgService;

	@Autowired
	private SysRedisService sysRedisService;

	/** 
	 * 搜索对象 
	 **/
	@RequestMapping(value = "",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Page<TucStaffEntity>> list(TucStaffEntity tucStaffEntity) {
		Page<TucStaffEntity> page = this.tucStaffService.findPage(tucStaffEntity);
		return R.ok(page);
	}

	
	/** 
	 * 查看对象
	 **/
	@RequestMapping(value = "/{staffId}",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<TUcStaff> view(@PathVariable String staffId)  {
		TUcStaff tucStaffEntity  = tucStaffService.getById(staffId);
		return R.ok(tucStaffEntity);
	}


	/** 
	 * 查看对象（支持多条件查询）
	 **/
	@RequestMapping(value = "get",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<TUcStaff> get(TucStaffEntity model)  {
		TUcStaff tucStaffEntity  = tucStaffService.get(model);
		return R.ok(tucStaffEntity);
	}
	
	
	/** 
	 * 新增对象
	 **/
	@Log(busiType = "新增员工", opType = SAVE, type = "web")
	@RequestMapping(value = "",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<TucStaffEntity> save(@RequestBody TucStaffEntity model)  {
		if (ObjectUtil.isEmpty(model.getDeptId())) {
			throw new RuntimeException("部门ID不能为空");
		}
		List<TUcStaff> addList = tucStaffService.handleStaff(model);
		if (ObjectUtil.isNotEmpty(addList)) {
			tucStaffService.saveBatch(addList);
			// 更新缓存
			sysRedisService.flushStaff(addList);
		}
        return R.ok(model);
	}
	
	/** 
	 * 批量新增对象
	 **/
	@Log(busiType = "批量新增员工", opType = SAVE, type = "web")
	@RequestMapping(value = "/batchSaveUser",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Boolean> batchSave(@RequestBody List<TucStaffEntity> model)  {
		for (TucStaffEntity staffEntity : model) {
			if (ObjectUtil.isEmpty(staffEntity.getDeptId())) {
				throw new RuntimeException("部门ID不能为空");
			}
			List<TUcStaff> addList = tucStaffService.handleStaff(staffEntity);
			if (ObjectUtil.isNotEmpty(addList)) {
				tucStaffService.saveBatch(addList);
				// 更新缓存
				sysRedisService.flushStaff(addList);
			}
        }
        return R.ok();
	}
	
	/**
	 * 更新对象
	 * @return 
	 **/
	@ApiVersion(groups = Version.SIX)
	@ApiOperation("更新员工")
	@Log(busiType = "更新员工", opType = UPDATE, type = "web")
	@RequestMapping(value = "",method = RequestMethod.PUT,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<TucStaffEntity> update(@RequestBody TucStaffEntity model)  {
		TUcStaff old = tucStaffService.getById(model.getStaffId());
		if (ObjectUtil.isEmpty(old)) {
			throw new RuntimeException("员工信息错误");
		}
		if (!Objects.equals(old.getDeptId(), model.getDeptId())) {
			List<TUcStaff> addList = tucStaffService.handleStaff(model);
			if (ObjectUtil.isNotEmpty(addList)) {
				for (TUcStaff staff : addList) {
					if (tucStaffService.countStaff(staff.getStaffId(), staff.getAppId()) > 0) {
						// 更新
						tucStaffService.updateById(staff);
					} else {
						// 新增
						tucStaffService.save(staff);
					}
				}
				// 更新缓存
				sysRedisService.flushStaff(addList);
			}
		} else {
			TUcStaff staff = BeanUtil.copyProperties(model, TUcStaff.class);
			tucStaffService.updateById(staff);
			// 更新缓存
			sysRedisService.saveOrUpdateStaff(model);
		}
        return R.ok(model);
	}
	
	/**
	 * 删除对象
	 * @return 
	 **/
	@ApiOperation("删除员工")
	@ApiVersion(groups = Version.SIX)
	@Log(busiType = "删除员工", opType = DELETE, type = "web")
	@RequestMapping(value = "/{staffId}",method = RequestMethod.DELETE,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Boolean> delete(@PathVariable String staffId) {
        if (ObjectUtil.isEmpty(staffId)) {
            throw new RuntimeException("员工id不能为空");
        }
		TUcStaff tucStaffEntity = tucStaffService.getById(staffId);
		sysRedisService.removeStaff(tucStaffEntity.getAppId(), tucStaffEntity.getStaffPostCode());
		tucStaffService.removeById(staffId);
		return R.ok();
	}
	
	/**
	 *  批量删除对象
	 * @return 
	 **/
	@Log(busiType = "批量删除员工", opType = DELETE, type = "web")
	@RequestMapping(value = "deleteBatch",method = RequestMethod.DELETE,produces = "application/json;charset=UTF-8")
	@ResponseBody
	@CrossOrigin
	public R<Boolean> deleteBatch(String[] ids) {
		if (ObjectUtil.isEmpty(ids)) {
			throw new RuntimeException("id不能为空");
		}
		for (int i = 0; i < ids.length; i++) {
			TUcStaff tucStaffEntity = tucStaffService.getById(ids[i]);
		    try {
				sysRedisService.removeStaff(tucStaffEntity.getAppId(), tucStaffEntity.getStaffPostCode());
            } catch (Exception e){
                log.info("删除redis数据失败->参数:"+ids[i]+"，位置: StaffRest.deleteBatch");
            }
		}
		tucStaffService.removeByIds(Arrays.asList(ids));
		return R.ok();
	}

	/**
	 * 组织下的所有用户-内部抵用
	 **/
	@RequestMapping(value = "/subStaffs", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Page<TucStaffEntity> subStaffs(TucStaffEntity staff) {
		if (StringUtils.isEmpty(staff.getStaffType())) {
			throw new RuntimeException("非法参数");
		}
		boolean flag = false;
		if(ObjectUtil.isNotEmpty(staff.getOrgId())) {
			//查询是否是顶级组织，如果是，用mysql函数递归肯定会丢失数据，所以这里就需要直接查询全部
			//获取组织顶级节点
			List<Org> topOrgList = tucOrgService.getTopOrg(staff.getStaffType());
			for(Org org : topOrgList) {
				if(staff.getOrgId().equals(org.getOrgId())) {
					flag = true;
					break;
				}
			}
			if(flag) {//这里为什么不用sub_staff_type，因为暂时没有维护好这个字段，所以用org_sub_type字段
				TUcOrg org = tucOrgService.getById(staff.getOrgId());
				if("GYGS".equals(org.getOrgSubType())) {
					staff.setStaffType("GYGS");
					Page<TucStaffEntity> pageInfo = tucStaffService.getStaffInfoByOrgTop(staff);
					return pageInfo;
				}
			}
		}
		
		Page<TucStaffEntity> pageInfo = this.tucStaffService.getSubStaffs(staff);
		return pageInfo;
		
	}
	
	/**
	 * 根据用户staffId获取用户
	 **/
	@RequestMapping(value = "/ivuser/{staffId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public R<TucStaffEntity> getByStaffId(@PathVariable String staffId,
			@RequestHeader(value = "iv-user", required = false) String ivUser) {
		String params = "";
		if (!StringUtils.isEmpty(ivUser)) {
			params = ivUser;
		} else if (!StringUtils.isEmpty(staffId)) {
			params = staffId;
		}
		TucStaffEntity tucStaffEntity = tucStaffService.getStaffByStaffId(params);
		return R.ok(tucStaffEntity);
	}
	
	
	/** 
	 * 获取树
	 **/
	@RequestMapping(value = "/getDevDept",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public List<Map<String,Object>> getDevDept(@RequestParam Map<String,Object> map)  {
		List<Map<String,Object>> orgList = new ArrayList<Map<String,Object>>(); 
		Map<String,Object> topOrg = new HashMap<String, Object>();
		//获取顶级组
		List<String> orgIds = new ArrayList<String>();
		if(map.containsKey("orgId")&& !"".equals(map.get("orgId"))){
//			orgIds.add(map.get("orgId").toString());
			String[] tempOrgArray = map.get("orgId").toString().split(",");
			for (String tempOrgId: tempOrgArray) {
				orgIds.add(tempOrgId);
			}
			for (String orgId : orgIds) {
				topOrg = new HashMap<String, Object>();
				Org org = tucOrgService.findOrgById(orgId);
				topOrg.put("id", org.getOrgId());
				topOrg.put("name", org.getOrgName());
				topOrg.put("orgId", org.getOrgParentId()); 
				topOrg.put("companyName", org.getCompanyName());
//				topOrg.put("open", true);
				//查询二级节点
				List<Map<String,Object>> children = new ArrayList<Map<String,Object>>();
				List<Map<String,Object>> childrentemp = new ArrayList<Map<String,Object>>();
				Map<String,Object> orgMaptemp = Maps.newHashMap();
				orgMaptemp.put("id", "1");
				childrentemp.add(orgMaptemp);
				
				Org orgEntity = new Org();
				orgEntity.setOrgParentId(orgId);
				orgEntity.setOrgStatus("QY");
				orgEntity.setSortColumns("org_sort");;
				List<Org> secondOrgList = tucOrgService.findList(orgEntity);
				
			
				for (Org orgEntry : secondOrgList) {
					List<Map<String,Object>> temp = Lists.newArrayList();
					Org entity = new Org();
					entity.setOrgParentId(orgEntry.getOrgId());
					entity.setOrgStatus("QY");
					entity.setSortColumns("org_sort");
					List<Org> orgcs = tucOrgService.findList(entity);
					for (Org orgcscs : orgcs) {
						Map<String,Object> orgMaps = Maps.newHashMap();
						orgMaps.put("id", orgcscs.getOrgId());
						orgMaps.put("name", orgcscs.getOrgName());
						orgMaps.put("orgId", orgcscs.getOrgParentId());
						orgMaps.put("companyName", orgcscs.getCompanyName());
						orgMaps.put("children", Lists.newArrayList());
						temp.add(orgMaps);
					}
					Map<String,Object> orgMap = Maps.newHashMap();
					orgMap.put("id", orgEntry.getOrgId());
					orgMap.put("name", orgEntry.getOrgName());
					orgMap.put("orgId", orgEntry.getOrgParentId()); 
					orgMap.put("companyName", orgEntry.getCompanyName());
					orgMap.put("children", temp);

					children.add(orgMap);
				}
				topOrg.put("children", children);
				orgList.add(topOrg);
			}
		}else{ 
			orgIds.add("402880e447e99cf10147e9a03b320003");
			for (String orgId : orgIds) {
				Org org = tucOrgService.findOrgById(orgId);
				topOrg.put("id", org.getOrgId());
				topOrg.put("name", org.getOrgName());
				topOrg.put("orgId", org.getOrgParentId()); 
				topOrg.put("companyName", org.getCompanyName());
//				topOrg.put("open", true);
				//查询二级节点
				List<Map<String,Object>> children = new ArrayList<Map<String,Object>>();
				List<Map<String,Object>> childrentemp = new ArrayList<Map<String,Object>>();
				Map<String,Object> orgMaptemp = Maps.newHashMap();
				orgMaptemp.put("id", "1");
				childrentemp.add(orgMaptemp);
				Org orgEntity = new Org();
				orgEntity.setOrgParentId(orgId);
				orgEntity.setOrgStatus("QY");
				orgEntity.setSortColumns("org_sort");
				List<Org> secondOrgList = tucOrgService.findList(orgEntity);
				
			
				for (Org orgEntry : secondOrgList) {

					List<Map<String,Object>> temp = Lists.newArrayList();
					Org entity = new Org();
					entity.setOrgParentId(orgEntry.getOrgId());
					entity.setOrgStatus("QY");
					entity.setSortColumns("org_sort");
					List<Org> orgcs = tucOrgService.findList(entity);
					for (Org orgcscs : orgcs) {
						Map<String,Object> orgMaps = Maps.newHashMap();
						orgMaps.put("id", orgcscs.getOrgId());
						orgMaps.put("name", orgcscs.getOrgName());
						orgMaps.put("orgId", orgcscs.getOrgParentId());
						orgMaps.put("companyName", orgcscs.getCompanyName());
						orgMaps.put("children", Lists.newArrayList());
						temp.add(orgMaps);
					}
					
					Map<String,Object> orgMap = Maps.newHashMap();
					orgMap.put("id", orgEntry.getOrgId());
					orgMap.put("name", orgEntry.getOrgName());
					orgMap.put("orgId", orgEntry.getOrgParentId()); 
					orgMap.put("companyName", orgEntry.getCompanyName());
					orgMap.put("children", temp);

					children.add(orgMap);
				}
				topOrg.put("children", children);
				orgList.add(topOrg);
			}
		}
				
		return orgList;
	}
	
	
	/**
	 * 功能描述:查询不分页
	 * @param
	 * @return
	 */
	@RequestMapping(value = "findList",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public List<TucStaffEntity> findList(TucStaffEntity tucStaffEntity) {
		String appId = UserUtils.getTenantId();
		tucStaffEntity.setAppId(appId);
		List<TucStaffEntity> list = tucStaffService.findList(tucStaffEntity);
		return list;
	}
	
	/**
	 * 功能描述:查询不分页
	 * @param
	 * @return
	 */
	@RequestMapping(value = "findListByName",method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public List<TucStaffEntity> findListByName(TucStaffEntity tucStaffEntity) {
		if (ObjectUtil.isEmpty(tucStaffEntity.getAppId())) {
			tucStaffEntity.setAppId(UserUtils.getTenantId());
		}
		List<TucStaffEntity> list = tucStaffService.findListByName(tucStaffEntity);
		return list;
	}
	
	/**
	 * 功能描述:查询不分页
	 * @param
	 * @return
	 */
	@RequestMapping(value = "enablePassport",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public R<Boolean> enablePassport(@RequestParam (required=true) String staffId, @RequestParam (required=true) String enableStatus) {
		tucStaffService.enablePassport(staffId, enableStatus);
		return R.ok();
	}

	// 6.0.0多租户多岗位

	@ApiOperation(value = "查询岗位信息集合")
	@ApiVersion(groups = Version.SIX)
	@GetMapping("/findStaffPostList")
	public List<StaffPostVO> findStaffPostList() {
		return tucStaffService.findStaffPostList();
	}

	
}



