package com.lz.modules.sys.service.app.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.common.utils.DateUtils;
import com.lz.common.utils.ISelect;
import com.lz.common.utils.PageUtils;
import com.lz.common.utils.StringUtil;
import com.lz.modules.app.dao.DepartmentsDao;
import com.lz.modules.app.dao.DepartmentsStaffRelateDao;
import com.lz.modules.app.dto.EmployeesDto;
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.req.ResultRecordReq;
import com.lz.modules.app.resp.ResultRecordResp;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.sys.dao.app.ResultRecordMapper;
import com.lz.modules.sys.entity.app.ResultRecord;
import com.lz.modules.sys.service.app.ResultRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业绩记录表 服务类
 * </p>
 *
 * @author quyixiao
 * @since 2020-08-10
 */

@Service
@Slf4j
public class ResultRecordServiceImpl extends ServiceImpl<ResultRecordMapper, ResultRecord> implements ResultRecordService {


    @Autowired
    private ResultRecordMapper resultRecordMapper;


    private static EmployeesDto employeesDto;

    @Autowired
    private DepartmentsDao departmentsDao;

    @Autowired
    private DepartmentsStaffRelateDao departmentsStaffRelateDao;

    @Autowired
    private StaffService staffService;




    @Override
    public ResultRecord selectResultRecordById(Long id) {
        return resultRecordMapper.selectResultRecordById(id);
    }


    @Override
    public Long insertResultRecord(ResultRecord resultRecord) {
        return resultRecordMapper.insertResultRecord(resultRecord);
    }


    @Override
    public int updateResultRecordById(ResultRecord resultRecord) {
        return resultRecordMapper.updateResultRecordById(resultRecord);
    }


    @Override
    public int updateCoverResultRecordById(ResultRecord resultRecord) {
        return resultRecordMapper.updateCoverResultRecordById(resultRecord);
    }


    @Override
    public int deleteResultRecordById(Long id) {
        return resultRecordMapper.deleteResultRecordById(id);
    }


    @Override
    public PageUtils queryPage(ResultRecordReq params) {
        List<Long> departmentStaffIds = new ArrayList<>();
        List<Long> staffIds = new ArrayList<>();
        List<String> departmentIds = new ArrayList<>();
        List<DepartmentsEntity> tDepartments = departmentsDao.selectAll();
        if (StringUtil.isNotBlank(params.getDepartment1()) || StringUtil.isNotBlank(params.getDepartment2())
                || StringUtil.isNotBlank(params.getDepartment3())) {
            Map<String,List<DepartmentsEntity>> departmentMap = null;
            if(employeesDto == null || employeesDto.getExpire() < new Date().getTime()){
                departmentMap = getStringListMap(tDepartments);
                Date expire = DateUtils.addMinute(new Date(),30);
                EmployeesDto newDto = new EmployeesDto(expire.getTime(),departmentMap);
                employeesDto = newDto;
                log.info("使用新数据");
            }else{
                log.info("使用缓存");
                departmentMap = employeesDto.getCacheMap();
            }
            if (StringUtil.isNotBlank(params.getDepartment3())) {
                getChildIds(departmentIds, params.getDepartment3(), departmentMap);
            } else if (StringUtil.isNotBlank(params.getDepartment2())) {
                getChildIds(departmentIds, params.getDepartment2(), departmentMap);
            } else if (StringUtil.isNotBlank(params.getDepartment1())) {
                getChildIds(departmentIds, params.getDepartment1(), departmentMap);
            }
        }

        if (departmentIds != null && departmentIds.size() > 0) {
            List<DepartmentsStaffRelateEntity> departmentsStaffRelateEntities = departmentsStaffRelateDao.selectByDepartmentIds(departmentIds);
            if(CollectionUtils.isNotEmpty(departmentsStaffRelateEntities)){
                Set<Long> setStaffId = departmentsStaffRelateEntities.stream().map(p->p.getStaffId()).collect(Collectors.toSet());
                departmentStaffIds = new ArrayList<>(setStaffId);
            }
        }

        if(StringUtil.isNotBlank(params.getName())){
            List<StaffEntity> staffEntities = staffService.selectByName(params.getName());
            if(CollectionUtils.isNotEmpty(staffEntities)){
                staffIds = staffEntities.stream().map(p->p.getId()).collect(Collectors.toList());
            }
        }

        params.setDepartmentStaffIds(departmentStaffIds);
        params.setStaffIds(staffIds);

        PageUtils pageUtils = PageUtils.startPage(params.getPage(), params.getLimit() ).doSelect(
                page -> resultRecordMapper.selectByCondition(page, params)
        );

        List<ResultRecord> resultRecords = pageUtils.getList();
        List<ResultRecordResp> list = new ArrayList<>();

        Set<Long> viewStaffIdSet = resultRecords.stream().map(p->p.getStaffId()).collect(Collectors.toSet());
        List<Long> viewStaffId = new ArrayList<>(viewStaffIdSet);

        List<StaffEntity> staffEntities = staffService.selectByIds(viewStaffId);
        List<DepartmentsStaffRelateEntity> staffRelateEntities = departmentsStaffRelateDao.selectByStaffIds(viewStaffId);

        Map<Long ,StaffEntity> staffEntityMap = staffEntities.stream().collect(Collectors.toMap(StaffEntity::getId, p -> p));
        Map<String, DepartmentsEntity> departmentsEntityMap = tDepartments.stream().collect(Collectors.toMap(p -> p.getDepartmentId(), p -> p));

        Map<Long, DepartmentsStaffRelateEntity> staffRelateEntityMap = staffRelateEntities.stream().collect(Collectors.toMap(p -> p.getStaffId(), p -> p));

        for (ResultRecord resultRecord : resultRecords) {
            ResultRecordResp resp = new ResultRecordResp();
            BeanUtils.copyProperties(resultRecord, resp);
            resp.setStaffName(staffEntityMap.get(resp.getStaffId()) != null ? staffEntityMap.get(resp.getStaffId()).getName() : "");
            DepartmentsStaffRelateEntity relate = staffRelateEntityMap.get(resp.getStaffId());
            resp.setDepartmentName(relate != null && departmentsEntityMap.get(relate.getDepartmentId()) != null ?
                    departmentsEntityMap.get(relate.getDepartmentId()).getDepartmentName() : "");
            list.add(resp);
        }
        pageUtils.setList(list);
        return pageUtils;
    }

    private Map<String, List<DepartmentsEntity>> getStringListMap(List<DepartmentsEntity> tDepartments) {
        Map<String, List<DepartmentsEntity>>  departmentMap = new HashMap<>();
        for(DepartmentsEntity department : tDepartments) {
            List<DepartmentsEntity> list = new ArrayList<>();
            for(DepartmentsEntity child : tDepartments) {
                if(child.getDepartmentParentId().equals(department.getDepartmentId())){
                    list.add(child);
                }
            }
            departmentMap.put(department.getDepartmentId(), list);
        }
        return departmentMap;
    }

    public void getChildIds(List<String> childDepartIds ,String parentId,Map<String,List<DepartmentsEntity>> departmentMap ){
        childDepartIds.add(parentId);
        List<DepartmentsEntity > tDepartments = departmentMap.get(parentId);
        if(CollectionUtils.isNotEmpty(tDepartments)){
            for(DepartmentsEntity tDepartment:tDepartments){
                getChildIds(childDepartIds,tDepartment.getDepartmentId(),departmentMap);
            }
        }
    }


    @Override
    public void deleteBatchIds(List<Long> asList) {

    }


}
