package com.kcim.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcim.common.exception.CostException;
import com.kcim.common.util.BeanUtil;
import com.kcim.common.util.PageUtils;
import com.kcim.common.util.Result;
import com.kcim.common.util.UserContext;
import com.kcim.common.constants.NumberConstant;
import com.kcim.dao.mapper.DepartmentMapper;
import com.kcim.dao.model.Department;
import com.kcim.dao.model.Hospital;
import com.kcim.dao.model.dto.DepartmentRequest;
import com.kcim.dao.model.dto.SysDepartment;
import com.kcim.service.CenterService;
import com.kcim.vo.DepartmentVO;
import com.kcim.service.DepartmentService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

@Slf4j
@Service("departmentService")
@AllArgsConstructor
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    private HospitalServiceImpl hospitalService;

    private CenterService centerService;
    /**
     * 分页查询科室信息
     *
     * @param current
     * @param pageSize
     * @param hospId
     * @param name
     * @return
     */
    @Override
    public PageUtils queryList(Integer current, Integer pageSize, Long hospId, String name) {
        Page<Department> departPage = new Page<>(current, pageSize);
        Page<Department> pages = this.page(departPage, new QueryWrapper<Department>().lambda()
                .eq(!StringUtils.isEmpty(hospId), Department::getHospId, hospId)
                .like(!StringUtils.isEmpty(name), Department::getDepartmentName, name).orderByDesc(Department::getCreateTime));
        List<Department> records = pages.getRecords();
        List<DepartmentVO> departmentVOList = BeanUtil.convertList(records, DepartmentVO.class);
        Hospital hospital = hospitalService.getOne(new QueryWrapper<Hospital>().lambda().eq(Hospital::getId, hospId));

        departmentVOList.forEach(i->{
            if (Objects.nonNull(hospital)){
                i.setHospName(hospital.getName());
            }
            i.setCreateDateTime(DateUtil.format(DateUtil.date(i.getCreateTime()),"yyyy-MM-dd HH:mm:ss"));
        });
        PageUtils pageUtils = new PageUtils(pages);
        pageUtils.setList(departmentVOList);
        return pageUtils;
    }

    /**
     * 根据指定条件查询科室的相关信息
     * @param id
     * @param departmentName
     * @param departmentCode
     * @param hospId
     * @return
     */
    @Override
    public List<Department> getByDepartment(Integer id,String departmentName,String departmentCode,Long hospId) {
//        LambdaQueryWrapper<Department> wrapper = new QueryWrapper<Department>().lambda()
//                .eq(!StringUtils.isEmpty(id), Department::getId, id)
//                .like(!StringUtils.isEmpty(departmentName), Department::getDepartmentName, departmentName)
//                .eq(!StringUtils.isEmpty(departmentCode), Department::getDepartmentCode, departmentCode)
//                .eq(!StringUtils.isEmpty(hospId), Department::getHospId, hospId)
//                .orderByDesc(Department::getCreateTime);
//        List<Department> departmentList = baseMapper.selectList(wrapper);
        List<SysDepartment> departmentFilter = centerService.getDepartmentFilter(null);
        List<Department> departmentList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(departmentFilter)){
            for (SysDepartment sysDepartment : departmentFilter) {
                Department depart = new Department();
                depart.setId(Long.valueOf(sysDepartment.getId()));
                depart.setDepartmentCode(sysDepartment.getCode());
                depart.setDepartmentName(sysDepartment.getName());
                departmentList.add(depart);
            }
        }
        return departmentList;
    }

    /**
     * 保存科室信息
     * TODO 检验科室信息是否存在
     * @param departmentRequest
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void addDepartment(DepartmentRequest departmentRequest) {
        Long hospId = UserContext.getHospId();
        // 查询所有的科室信息
        List<Department> departmentList = baseMapper.selectList(new QueryWrapper<Department>().lambda().eq(Department::getHospId, hospId));
        Map<String, List<Department>> map =
                departmentList.stream().collect(Collectors.groupingBy(Department::getDepartmentCode));
        if (!CollectionUtils.isEmpty(map.get(departmentRequest.getDepartmentCode()))){
            throw new CostException(500,"科室代码"+departmentRequest.getDepartmentCode()+"已存在");
        }
        departmentRequest.setHospId(hospId);
        Department department = BeanUtil.convertObj(departmentRequest, Department.class);
        department.setId(null);
        department.setCreateTime(System.currentTimeMillis());
        baseMapper.insert(department);
        int a=10/0;
    }

    /**
     * 修改科室信息
     *
     * @param departmentRequest
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateByDepartment(DepartmentRequest departmentRequest) {
        Long hospId = UserContext.getHospId();
        Long id = departmentRequest.getId();
        Department department = baseMapper.selectById(id);
        if (Objects.isNull(department)){
            throw new CostException("未找到相关科室信息");
        }
        baseMapper.deleteById(id);
        // 查询所有的科室信息
        List<Department> departmentList = baseMapper.selectList(new QueryWrapper<Department>().lambda().eq(Department::getHospId, hospId));
        Map<String, List<Department>> map =
                departmentList.stream().collect(Collectors.groupingBy(Department::getDepartmentCode));
        if (!CollectionUtils.isEmpty(map.get(departmentRequest.getDepartmentCode()))){
            throw new CostException(500,"科室代码"+departmentRequest.getDepartmentCode()+"已存在");
        }
        // 新增操作
        Department departmentResponse = BeanUtil.convertObj(departmentRequest, Department.class);
        departmentResponse.setId(null);
        departmentResponse.setCreateTime(System.currentTimeMillis());
        departmentResponse.setHospId(hospId);
        baseMapper.insert(departmentResponse);
    }

    /**
     * 导入科室信息
     *
     * @param list
     * @param hospId
     * @return
     */
    @Override
    public Result importDepartment(List<List<Object>> list, Long hospId) {
        for (int i = list.size() - 1; i >= 0; i--) {
            if (i == NumberConstant.ZERO || i == NumberConstant.ONE || i == NumberConstant.TWO || i == NumberConstant.THREE) {
                list.remove(list.get(i));
            }
        }
        log.info("读取的数据为：{}", list);
        List<Department> departmentList = new ArrayList<>();
        List<String> errRowNums = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            List<Object> data = list.get(i);
            log.info("得到用户输入的数据为：{}", data);
            Department department = new Department();
            department.setHospId(hospId);
            department.setCreateTime(System.currentTimeMillis());
            int size = data.size();
            if (size != 5) {
                // 补充读取的null问题
                if (size == 4) {
                    data.add(StrUtil.EMPTY);
                }
                for (int j = 0; j < 3; j++) {
                    if (Objects.isNull(data.get(j))) {
                        data.set(j, StrUtil.EMPTY);
                    }
                }
            }
            for (int j = 0; j < 3; j++) {
                String str = String.valueOf(data.get(j));
                log.info("得到的字符串{}", str);
                if (StrUtil.isBlank(str)) {
                    errRowNums.add("" + (i + 3));
                }

                if (j == 0) {
                    //  Excel里面输入医院名称  根据医院名称解析
                    Hospital hospital = hospitalService.getByName(str);
                    department.setHospId(hospital.getId());
                } else if (j == 1) {
                    department.setDepartmentName(str);
                } else {
                    department.setDepartmentCode(str);
                }
            }
            departmentList.add(department);
        }
        if (CollUtil.isNotEmpty(errRowNums)) {
            String collect = errRowNums.stream().collect(Collectors.joining(StrUtil.COMMA));
            throw new CostException(500, "第" + collect + "行数据异常");
        }
        // 校验输入的Department是否存在  输入的科室里面筛选出已经存在的科室信息
        List<Department> realDepartments = new ArrayList<>();
        departmentList.forEach(i -> {
            Department one = getOne(
                    new QueryWrapper<Department>().lambda()
                            .eq(Department::getDepartmentCode, i.getDepartmentCode())
                            .eq(Department::getHospId, i.getHospId())
            );
            if (Objects.nonNull(one)) {
                realDepartments.add(one);
            }
        });
        departmentList = departmentList.stream().filter(i -> !realDepartments.stream().map(Department::getDepartmentCode).collect(Collectors.toList()).contains(i.getDepartmentCode())).collect(Collectors.toList());
        this.saveBatch(departmentList);
        if (CollectionUtils.isEmpty(realDepartments)){
            return Result.build(200,"数据导入成功",null);
        }else {
            return Result.build(200, "有" + realDepartments.size() + "条数据已存在，未被导入", null);
        }
    }

    /**
     * 批量删除科室信息
     *
     * @param idList 科室Id集合
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deleteByIds(List<Integer> idList) {
        this.removeByIds(idList);
    }

    @Override
    public List<Department> getDepartments() {
        List<SysDepartment> departmentFilter = centerService.getDepartmentFilter(null);
        List<Department> departmentList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(departmentFilter)){
            for (SysDepartment sysDepartment : departmentFilter) {
                Department depart = new Department();
                depart.setId(Long.valueOf(sysDepartment.getId()));
                depart.setDepartmentCode(sysDepartment.getCode());
                depart.setDepartmentName(sysDepartment.getName());
                departmentList.add(depart);
            }
        }
        return departmentList;
    }
}