package com.lz.modules.flow.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.lz.common.utils.NumberUtil;
import com.lz.common.utils.PageUtils;
import com.lz.modules.app.dao.DepartmentsDao;
import com.lz.modules.app.dao.StaffDao;
import com.lz.modules.app.dto.StaffRoleResp;
import com.lz.modules.app.entity.DepartmentsEntity;
import com.lz.modules.app.entity.DepartmentsStaffRelateEntity;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.service.DepartmentsService;
import com.lz.modules.app.service.DepartmentsStaffRelateService;
import com.lz.modules.flow.dao.RecordRoleMapper;
import com.lz.modules.flow.dao.StaffRoleDepartmentMapper;
import com.lz.modules.flow.dao.StaffRoleMapper;
import com.lz.modules.flow.entity.RecordRole;
import com.lz.modules.flow.entity.StaffRole;
import com.lz.modules.flow.entity.StaffRoleDepartment;
import com.lz.modules.flow.service.RecordRoleService;
import com.lz.modules.flow.service.StaffRoleService;
import com.lz.modules.sys.entity.SysMenuEntity;
import com.lz.modules.sys.entity.SysRoleEntity;
import com.lz.modules.sys.service.app.ResultRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 流转关系表 服务类
 * </p>
 *
 * @author quyixiao
 * @since 2020-08-18
 */

@Service
@Slf4j
public class StaffRoleServiceImpl extends ServiceImpl<StaffRoleMapper, StaffRole> implements StaffRoleService {


    @Autowired
    private StaffRoleMapper staffRoleMapper;

    @Autowired
    private StaffDao staffDao;


    @Autowired
    private RecordRoleMapper recordRoleMapper;

    @Autowired
    private StaffRoleDepartmentMapper staffRoleDepartmentMapper;
    @Autowired
    private DepartmentsDao departmentsDao;

    @Autowired
    private ResultRecordService resultRecordService;

    @Autowired
    private  RecordRoleService recordRoleService;

    @Autowired
    private DepartmentsService departmentsService;

    @Autowired
    private DepartmentsStaffRelateService departmentsStaffRelateService;

    @Override
    public StaffRole selectStaffRoleById(Long id) {
        return staffRoleMapper.selectStaffRoleById(id);
    }


    @Override
    public Long insertStaffRole(StaffRole staffRole) {
        return staffRoleMapper.insertStaffRole(staffRole);
    }


    @Override
    public int updateStaffRoleById(StaffRole staffRole) {
        return staffRoleMapper.updateStaffRoleById(staffRole);
    }


    @Override
    public int updateCoverStaffRoleById(StaffRole staffRole) {
        return staffRoleMapper.updateCoverStaffRoleById(staffRole);
    }


    @Override
    public int deleteStaffRoleById(Long id) {
        return staffRoleMapper.deleteStaffRoleById(id);
    }

    @Override
    public StaffRole selectByStaffId(Long staffId) {
        return staffRoleMapper.selectByStaffId(staffId);
    }

    @Override
    public List<StaffRole> selectByRole(String departmentLevel) {
        return staffRoleMapper.selectByRole(departmentLevel);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {


        PageUtils pageUtils = PageUtils.startPage(
                NumberUtil.objToIntDefault(params.get("page"), 1),
                NumberUtil.objToIntDefault(params.get("limit"), 10)).doSelect(
                page -> staffRoleMapper.selectByCondition(page, params)
		);
		List<StaffRole> staffRoles = pageUtils.getList();
		List<StaffRoleResp> list = new ArrayList<>();
		Map<Long, RecordRole> map = Maps.newHashMap();
		for (StaffRole staffRole : staffRoles) {
			StaffRoleResp resp = new StaffRoleResp();
			BeanUtils.copyProperties(staffRole, resp);
			StaffEntity staffEntity = staffDao.selectStaffById(resp.getStaffId());
			if (staffEntity != null) {
				resp.setStaffName(staffEntity.getName());
			}

			Map<String, Integer> types = JSONObject.parseObject(resp.getTypeRoleIds(), Map.class);
			Long type1 = NumberUtil.objToLongDefault(types.get("type1"),0l);
			Long type2 = NumberUtil.objToLongDefault(types.get("type2"),0l);
			RecordRole recordRoleType1 = map.get(type1);
			if (recordRoleType1 == null) {
				recordRoleType1 = recordRoleMapper.selectById(type1);
			}
			RecordRole recordRoleType2 = map.get(type2);
			if (recordRoleType2 == null) {
				recordRoleType2 = recordRoleMapper.selectById(type2);
			}
			if (recordRoleType1 != null) {
				map.put(recordRoleType1.getId(), recordRoleType1);
				resp.setTargetRole(recordRoleType1.getName());
			}
			if (recordRoleType2 != null) {
				map.put(recordRoleType2.getId(), recordRoleType2);
				resp.setResultRole(recordRoleType2.getName());
			}
			list.add(resp);
		}
        pageUtils.setList(list);
        return pageUtils;
    }

    @Override
    public void deleteBatchIds(List<Long> asList) {
        for (Long a : asList) {
            staffRoleMapper.deleteStaffRoleById(a);
        }
    }


    @Override
    public SysRoleEntity getRole(Long id) {
        StaffRole staffRole = staffRoleMapper.selectStaffRoleById(id);
        SysRoleEntity role = new SysRoleEntity();
        List<Long> menuIdList= new ArrayList<>();
        List<Long> menuIdList1= new ArrayList<>();
        if(staffRole!=null){
            List<StaffRoleDepartment> staffRoleDepartments = staffRoleDepartmentMapper.selectStaffRoleDepartmentByStaffRoleId(staffRole.getId());
            List<DepartmentsEntity> departmentsEntities = departmentsDao.selectAll();
            Map<String,List<DepartmentsEntity>> map= resultRecordService.getStringListMap(departmentsEntities);
            role.setRoleId(staffRole.getId());
            role.setRoleName(staffRole.getDepartmentLevel());

            for(StaffRoleDepartment staffRoleDepartment: staffRoleDepartments){
                List<DepartmentsEntity> list = map.get(staffRoleDepartment.getDepartmentId());
                List<String> departments = departmentsService.selectAllChildDepartmentIds(staffRoleDepartment.getDepartmentId());
                List<StaffRoleDepartment> departments1 = staffRoleDepartmentMapper.selectStaffRoleDepartmentByStaffRoleIdDepartments(staffRole.getId(), departments);
                if (list == null || list.size() == 0 || departments1.size() <= 1) {
                    menuIdList.add(NumberUtil.objToLongDefault(staffRoleDepartment.getDepartmentId(), 0l));
                } else {
                    menuIdList1.add(NumberUtil.objToLongDefault(staffRoleDepartment.getDepartmentId(), 0l));
                }
            }
        }
        menuIdList.add(-666666l);
        menuIdList.addAll(menuIdList1);
        role.setMenuIdList(menuIdList);
        return role;
    }

    @Override
    public List<SysMenuEntity> selectMenuList() {
        List<DepartmentsEntity> tDepartments = departmentsDao.selectAll();
        List<DepartmentsEntity> parentDepartments = tDepartments.stream()
                //根据两个属性进行过滤
                .filter(s -> s.getDepartmentParentId().equals("1"))
                .collect(Collectors.toList());
        List<DepartmentsStaffRelateEntity> departmentsStaffRelateEntities = departmentsStaffRelateService.selectAll();
        Map<String,DepartmentsStaffRelateEntity> departmentsStaffRelateEntityMap = new HashMap<>();
        Map<String,DepartmentsStaffRelateEntity> singleDepartmentsStaffRelate = new HashMap<>();
        for(DepartmentsStaffRelateEntity d : departmentsStaffRelateEntities){
            singleDepartmentsStaffRelate.put(d.getDepartmentId(),d);
            if(new Integer(1).equals(d.getIsLeader())){
                departmentsStaffRelateEntityMap.put(d.getDepartmentId(),d);
            }
        }
        List<StaffEntity> staffEntities = staffDao.selectAll();
        Map<Long ,StaffEntity> staffMap = new HashMap<>();
        for(StaffEntity staffEntity : staffEntities){
            staffMap.put(staffEntity.getId(),staffEntity);
        }
        List<SysMenuEntity> list = new ArrayList<>();
        for (DepartmentsEntity d : parentDepartments) {
            String departmentName = d.getDepartmentName() + getSuffix(departmentsStaffRelateEntityMap,staffMap,d.getDepartmentId(),singleDepartmentsStaffRelate);
            SysMenuEntity entity = recordRoleService.buildMenuEntity(NumberUtil.objToLongDefault(d.getDepartmentId(), 0l),departmentName , 0l, "");
            getMenuList(tDepartments, entity, list,departmentsStaffRelateEntityMap,staffMap,singleDepartmentsStaffRelate);
            list.add(entity);
        }
        return list;
    }

    @Override
    public List<StaffRole> selectByGroupId(Long id) {

        return staffRoleMapper.selectByGroupId(id);
    }

    public String getSuffix(Map<String, DepartmentsStaffRelateEntity> departmentsStaffRelateEntityMap, Map<Long, StaffEntity> staffMap, String departmentId,
                            Map<String, DepartmentsStaffRelateEntity> singleDepartmentsStaffRelate) {
        DepartmentsStaffRelateEntity departmentsStaffRelateEntity = departmentsStaffRelateEntityMap.get(departmentId);
        if (departmentsStaffRelateEntity != null) {
            return doGetStaff(departmentsStaffRelateEntity, staffMap);
        } else {
            return doGetStaff(singleDepartmentsStaffRelate.get(departmentId), staffMap);
        }
    }

    public String doGetStaff(DepartmentsStaffRelateEntity departmentsStaffRelateEntity, Map<Long, StaffEntity> staffMap) {
        if (departmentsStaffRelateEntity != null) {
            StaffEntity staffEntity = staffMap.get(departmentsStaffRelateEntity.getStaffId());
            if (staffEntity != null) {
                return " , " + staffEntity.getName();
            }
        }
        return " ";
    }


    public void getMenuList(List<DepartmentsEntity> tDepartments,SysMenuEntity sysMenuEntity,List<SysMenuEntity> list,
                            Map<String,DepartmentsStaffRelateEntity> departmentsStaffRelateEntityMap, Map<Long ,StaffEntity> staffMap,
                            Map<String,DepartmentsStaffRelateEntity> singleDepartmentsStaffRelate) {
        for(DepartmentsEntity child : tDepartments) {
            if(NumberUtil.objToLongDefault(child.getDepartmentParentId(),0l).equals(sysMenuEntity.getMenuId())){
                String departmentName = child.getDepartmentName() + getSuffix(departmentsStaffRelateEntityMap,staffMap,child.getDepartmentId(),singleDepartmentsStaffRelate);
                SysMenuEntity entity =  recordRoleService.buildMenuEntity(NumberUtil.objToLongDefault(child.getDepartmentId(),0l),
                        departmentName,sysMenuEntity.getMenuId(),sysMenuEntity.getName());
                getMenuList(tDepartments,entity,list,departmentsStaffRelateEntityMap,staffMap,singleDepartmentsStaffRelate);
                list.add(entity);
            }
        }
    }

}
