package com.dayou.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.dayou.common.BaseEntity;
import com.dayou.common.SimpleListModel;
import com.dayou.dto.SimplePostModel;
import com.dayou.entity.Department;
import com.dayou.entity.Post;
import com.dayou.entity.UserPost;
import com.dayou.exception.ErrorCode;
import com.dayou.mapper.UserPostMapper;
import com.dayou.service.IDepartmentService;
import com.dayou.service.IPostService;
import com.dayou.service.IUserPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dayou.utils.ExcelUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.transaction.annotation.Transactional;
import com.dayou.enums.BatchTaskTypeEnum;

import static com.dayou.common.Constants.MARKET_DEPARTMENT;
import static com.dayou.common.Constants.MARKET_MANAGER;

/**
 * <p>
 * 用户岗位 服务实现类
 * </p>
 *
 * @author wucl
 * @since 2022-11-29
 */
@Service
public class UserPostServiceImpl extends ServiceImpl<UserPostMapper, UserPost> implements IUserPostService {

    private static final List<String> userPostExcelTitles= new ArrayList();

    @Autowired
    private UserPostMapper userPostMapper;

    @Autowired
    private IPostService postService;

    @Autowired
    private IDepartmentService departmentService;


    @Override
    @SuppressWarnings("unchecked")
    public Page<UserPost> selectPage(Page page,UserPost userPost){
        return this.page(page, new QueryWrapper<UserPost>(userPost));
    }


    @Override
    public UserPost detail(Long id){
        return this.getById(id);
    }

    @Override
    public Boolean add(UserPost userPost){
        return  this.save(userPost);
    }

    @Override
    public Boolean update(UserPost userPost){
        return  this.updateById(userPost);
    }

    @Override
    public Boolean delete(Long id){
        //逻辑删除
        return this.removeById(id);
    }

    @Override
    public XSSFWorkbook generateImportTemplate(){
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建固定列的表头
        createExcelTitle(wb);
        return wb;
    }

    private void createExcelTitle(XSSFWorkbook wb) {
        Sheet sheet = wb.createSheet("用户岗位导入模板");
        Row row = sheet.createRow(0);
        CellStyle style = wb.createCellStyle();
        Cell cell = null;
        for (int i = 0; i < userPostExcelTitles.size(); i++) {
            cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(userPostExcelTitles.get(i));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importExcel(MultipartFile file){
        ExcelUtil.importExcel(UserPost.class, new ExcelUtil.ImportListener<UserPost>() {
            @Override
            public Boolean handleOneRecord(UserPost userPost) {
                return add(userPost);
            }

            @Override
            public void afterImport(ExcelUtil.BatchImportResult batchImportResult) {

            }
        }, file, BatchTaskTypeEnum.DEFAULT,ExcelUtil.BatchImportStrategy.ROLL_BACK);
    }

    @Override
    public XSSFWorkbook exportExcel(UserPost userPost) {
        XSSFWorkbook wb = ExcelUtil.export(UserPost.class,
        (page, userPostReq) -> selectPage(page,userPostReq),
        userPost);
        return wb;
    }

    @Override
    public List<SimplePostModel> getPostList(Long userId) {
        List<SimplePostModel> list = userPostMapper.getPostList(userId);
        return list;
    }

    @Override
    public void saveOrUpdateById(UserPost userPost) {
        userPostMapper.saveOrUpdateById(userPost);
    }

    @Override
    public Set<Long> getPostUserId(Set<Long> juniorPost) {
        Set<Long> userIds = userPostMapper.getPostUserId(juniorPost);
        return userIds;
    }

    @Override
    public SimplePostModel getMarketPostList(Long userId) {
        SimplePostModel postModel = userPostMapper.getMarketPostList(userId);
        return postModel;
    }

    @Override
    public void checkMultiPostInMarketDepartment(Set<Long> postIds) {
        List<Post> list = postService.list(new LambdaQueryWrapper<Post>().in(BaseEntity::getId, postIds).eq(BaseEntity::getDeleted, Boolean.FALSE));
        Long marketDepId = departmentService.getOne(new LambdaQueryWrapper<Department>().eq(Department::getName, MARKET_DEPARTMENT).eq(BaseEntity::getDeleted, Boolean.FALSE)).getId();
        Post manager = postService.getOne(new LambdaQueryWrapper<Post>().eq(Post::getName, MARKET_MANAGER).eq(BaseEntity::getDeleted, Boolean.FALSE));
        if (manager==null){
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"警告! 系统还未设置市场部经理岗位");
        }
        List<UserPost> managers = this.list(new LambdaQueryWrapper<UserPost>().eq(UserPost::getPostId, manager.getId()).eq(BaseEntity::getDeleted, Boolean.FALSE));
        if (!CollectionUtils.isEmpty(managers) && list.stream().map(BaseEntity::getId).filter(x->x.equals(manager.getId())).collect(Collectors.toSet()).size()!=0){
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"抱歉！市场部经理已存在任职人员，暂不支持设置多个市场部经理人员。");
        }
        List<Post> collect = list.stream().filter(x -> x.getDepartmentId().equals(marketDepId)).collect(Collectors.toList());
        if (collect.size()>1){
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"抱歉！员工在市场部只能担任一个岗位。");
        }
    }

    @Override
    public Long getUniqueHandlerByPostForWorkNode(Long postId) {
        List<UserPost> list = this.list(new LambdaQueryWrapper<UserPost>().select(UserPost::getUserId).eq(UserPost::getPostId, postId)
                .orderByDesc(BaseEntity::getCreated));
        if (CollectionUtil.isNotEmpty(list)){
            return list.get(0).getUserId();
        }
        return null;
    }

}
