package com.kcim.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
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.PageUtils;
import com.kcim.common.constants.NumberConstant;
import com.kcim.dao.mapper.HospitalMapper;
import com.kcim.dao.model.Hospital;
import com.kcim.dao.model.dto.HospitalDto;
import com.kcim.dao.model.dto.HospitalSaveDto;
import com.kcim.vo.CommonVO;
import com.kcim.vo.HospitalAllVO;
import com.kcim.vo.HospitalVO;
import com.kcim.service.HospitalService;
import com.kcim.common.util.BeanUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;


/**
 * @author 11290
 */
@Service("hosptailService")
public class HospitalServiceImpl extends ServiceImpl<HospitalMapper, Hospital> implements HospitalService {

    /**
     * 分页查询所有的医院信息
     *
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public PageUtils queryList(Integer current, Integer pageSize, Long hospId, String name) {
        Page<Hospital> hosptailPage = new Page<>(current, pageSize);
        Page<Hospital> pages = this.page(hosptailPage, new QueryWrapper<Hospital>().lambda()
                .like(!StringUtils.isEmpty(name), Hospital::getName, name).orderByDesc(Hospital::getCreateTime));
        List<Hospital> records = pages.getRecords();
        List<HospitalVO> hospitalVOList = BeanUtil.convertList(records, HospitalVO.class);

        hospitalVOList.forEach(i -> {
            if (NumberConstant.ZERO.equals(i.getIsHospital())) {
                i.setParentId(null);
                i.setParentName(null);
            }
            String format = DateUtil.format(DateUtil.date(i.getCreateTime()), "yyyy-MM-dd HH:mm:ss");
            i.setCreateDateTime(format);

        });

        PageUtils pageUtils = new PageUtils(pages);
        pageUtils.setList(hospitalVOList);
        return pageUtils;
    }

    /**
     * 添加医院信息
     *
     * @param hospitalSaveDto
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveHosptail(HospitalSaveDto hospitalSaveDto) {
        String sign = hospitalSaveDto.getSign();
        //  检验此时保存的是医院还是院区
        checkParam(hospitalSaveDto, sign);
        Hospital hospital = BeanUtil.convertObj(hospitalSaveDto, Hospital.class);
        hospital.setCreateTime(System.currentTimeMillis());
        baseMapper.insert(hospital);
    }

    // 校验参数
    private void checkParam(HospitalSaveDto hospitalSaveDto, String sign) {
        Integer isHospital = hospitalSaveDto.getIsHospital();
        // 新增医院
        if (isHospital == 0) {
            if (StringUtils.isEmpty(sign)) {
                throw new CostException(500, "新增医院请选择医院标识");
            }
            Hospital bySign = this.getBySignHospital(sign);
            if (Objects.nonNull(bySign)) {
                throw new CostException(500, "当前医院标识已存在，请重新生成");
            }
        } else {
            Long parentId = hospitalSaveDto.getParentId();
            // 校验参数
            if (parentId == 0) {
                throw new CostException(500, "新增院区请选择医院");
            }else {
                Hospital hospital = baseMapper.selectById(parentId);
                if (Objects.isNull(hospital)){
                    throw new CostException(500, "选择的住院不存在");
                }else {
                    hospitalSaveDto.setParentName(hospital.getName());
                }
            }
        }
    }

    public Hospital getBySignHospital(String hospSign) {
        Hospital one = this.getOne(
                new LambdaQueryWrapper<Hospital>()
                        .select(Hospital::getId, Hospital::getName)
                        .eq(Hospital::getIsHospital, 0)
                        .eq(Hospital::getSign, hospSign)
                        .last("limit 1")
        );
        return one;
    }

    /**
     * 修改医院信息
     *
     * @param hospitalDto
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateByHosptail(HospitalDto hospitalDto) {
        Hospital hospital = baseMapper.selectOne(new QueryWrapper<Hospital>().lambda().
                eq(!StringUtils.isEmpty(hospitalDto.getId()), Hospital::getId, hospitalDto.getId()));
        if (Objects.isNull(hospital)) {
            throw new CostException("不存在相关医院信息");
        }
        if (NumberConstant.ONE.equals(hospitalDto.getIsHospital())){
            // 此时修改的是院区  需要传递parent_Id 和 parent__name
            if (hospitalDto.getParentId()<=0 || StringUtils.isEmpty(hospitalDto.getParentName())){
                throw new CostException(500,"修改院区的时候需要传递医院的Id和医院名称");
            }
        }
        Hospital hospitalRequest = BeanUtil.convertObj(hospitalDto, Hospital.class);
        baseMapper.updateById(hospitalRequest);
//        hospitalRequest.setId(null);
//        hospitalRequest.setCreateTime(System.currentTimeMillis());
//        hospitalRequest.setSign(hospital.getSign());
//        baseMapper.insert(hospitalRequest);
        // 修改和这个医院相关联的用户的数据
    }

    /**
     * 获取所有的医院信息
     *
     * @return
     */
    @Override
    public List<HospitalAllVO> getAll() {
        List<Hospital> hospitals = baseMapper.selectList(new QueryWrapper<Hospital>().lambda()
                .eq(Hospital::getIsHospital, NumberConstant.ZERO));
        List<HospitalAllVO> hospitalAllVOList = BeanUtil.convertList(hospitals, HospitalAllVO.class);
        return hospitalAllVOList;
    }


    /**
     * 通过医院标识获取院区列表
     *
     * @param sign
     * @return
     */
    @Override
    public List<CommonVO> getHospArea(String sign) {
        Hospital one = this.getBySign(sign);
        // 获取下面所有院区
        List<Hospital> list = this.list(
                new LambdaQueryWrapper<Hospital>()
                        .select(Hospital::getId)
                        .eq(Hospital::getIsHospital, 1)
                        .eq(Hospital::getParentId, one.getId())
        );
        // 如果不存在院区
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        return BeanUtil.convertList(list, CommonVO.class);
    }

    /**
     * 通过医院sign获取医院信息
     *
     * @param hospSign 医院唯一标识
     * @return
     */
    @Override
    public Hospital getBySign(String hospSign) {
        Hospital one = this.getOne(
                new LambdaQueryWrapper<Hospital>()
                        .select(Hospital::getId, Hospital::getName)
//                        .eq(Hospital::getIsHospital, 0)
                        .eq(Hospital::getSign, hospSign)
                        .last("limit 1")
        );
        if (Objects.isNull(one)) {
            throw new CostException("当前医院不存在");
        }
        return one;
    }

    @Override
    public Hospital getByName(String str) {
        Hospital one = this.getOne(
                new LambdaQueryWrapper<Hospital>()
//                        .select(Hospital::getId, Hospital::getName)
                        .eq(Hospital::getName, str)
                        .last("limit 1")
        );
        if (Objects.isNull(one)) {
            throw new CostException("当前医院名称为：" + str + "不存在");
        }
        return one;
    }

    /**
     * 批量珊瑚医院的数据
     *
     * @param idList 医院的Id集合
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deleteByIds(List<Integer> idList) {
        this.removeByIds(idList);
    }

    //    /**
//     * 校验是否是本院下人员,并且返回对应的院区id
//     *
//     * @param hospId
//     * @param str
//     * @return
//     */
//    @Override
//    public Integer getByNameAndCheck(Long hospId, String str) {
//        // 得到这个hospId 相关的所有医院或院区id
//        Hospital byId = this.getById(hospId);
//        if (Objects.isNull(byId)) {
//            throw new CostException(500, "当前医院不存在");
//        }
//        Integer isHospital = byId.getIsHospital();
//        List<Integer>
//        // 是医院
//        if (isHospital == 0) {
//
//        }
//    }
}