package com.dayou.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dayou.common.BaseEntity;
import com.dayou.dto.SimpleDepartmentModel;
import com.dayou.entity.Department;
import com.dayou.entity.Post;
import com.dayou.entity.User;
import com.dayou.mapper.DepartmentMapper;
import com.dayou.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayou.service.IPostService;
import com.dayou.service.IUserService;
import com.dayou.vo.DepartmentStatVO;
import com.dayou.vo.DepartmentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.web.multipart.MultipartFile;
import java.util.List;
import java.util.ArrayList;
import org.springframework.transaction.annotation.Transactional;
import com.dayou.enums.BatchTaskTypeEnum;

/**
 * <p>
 * 机构 服务实现类
 * </p>
 *
 * @author wucl
 * @since 2022-11-29
 */
@DS("mbs")
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

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

    static{
            departmentExcelTitles.add("部门名称");
            departmentExcelTitles.add("联系电话");
    }

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private IPostService postService;

    @Autowired
    private IUserService userService;


    @Override
    @SuppressWarnings("unchecked")
    public Page<DepartmentVO> selectPage(Page page,Department department){
        return departmentMapper.getPage(page,department);
    }


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

    @Override
    public Boolean add(Department department){
        return  this.save(department);
    }

    @Override
    public Boolean update(Department department){
        return  this.update(new LambdaUpdateWrapper<Department>().set(Department::getName,department.getName())
                .set(Department::getParentId,department.getParentId())
                        .set(Department::getLeaderId,department.getLeaderId())
                        .set(Department::getIfAllot,department.getIfAllot())
                .set(Department::getPhone,department.getPhone()).eq(BaseEntity::getId,department.getId()));
    }

    @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 < departmentExcelTitles.size(); i++) {
            cell = row.createCell(i);
            cell.setCellStyle(style);
            cell.setCellValue(departmentExcelTitles.get(i));
        }
    }

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

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

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


    @Override
    public Page<DepartmentVO> xPage(SimpleDepartmentModel department, Page page) {
        Page<DepartmentVO> result = departmentMapper.xPage(department,page);
        return result;
    }

    @Override
    public DepartmentStatVO stat() {
        LambdaQueryWrapper<Department> departmentLambdaQueryWrapper = new LambdaQueryWrapper<Department>()
                .eq(Department::getDeleted, false);

        int orgNum = this.count(departmentLambdaQueryWrapper);
        LambdaQueryWrapper<Post> postLambdaQueryWrapper = new LambdaQueryWrapper<Post>()
                .eq(Post::getDeleted, false);

        int postNum = postService.count(postLambdaQueryWrapper);
        LambdaQueryWrapper<User> staffLambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getDeleted, false);

        int staffNum = userService.count(staffLambdaQueryWrapper);
        return DepartmentStatVO.builder()
                .orgNum(orgNum)
                .postNum(postNum)
                .staffNum(staffNum)
                .build();
    }

    /**
     * 根据业务code获取接单部门
     * @param businessCode 业务code
     * @return List<Department>
     */
    @Override
    public List<Department> getAllotDepartmentByBusiness(String businessCode) {
        return departmentMapper.getAllotDepartmentByBusiness(businessCode);
    }

}
