package com.diagbot.facade;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.diagbot.dto.QcCasesEntrySimpleDTO;
import com.diagbot.dto.QcTypeDTO;
import com.diagbot.dto.QcTypePageDTO;
import com.diagbot.entity.CommonParam;
import com.diagbot.entity.QcType;
import com.diagbot.entity.QcTypeCasesEntry;
import com.diagbot.enums.InsertOrUpdateEnum;
import com.diagbot.enums.IsDeleteEnum;
import com.diagbot.exception.CommonErrorCode;
import com.diagbot.exception.CommonException;
import com.diagbot.service.impl.QcTypeCasesEntryServiceImpl;
import com.diagbot.service.impl.QcTypeServiceImpl;
import com.diagbot.util.BeanUtil;
import com.diagbot.util.DateUtil;
import com.diagbot.util.EntityUtil;
import com.diagbot.util.ListUtil;
import com.diagbot.util.SysUserUtils;
import com.diagbot.vo.DeleteQcTypeVO;
import com.diagbot.vo.QcEntryHospitalVO;
import com.diagbot.vo.QcTypeCasesEntryVO;
import com.diagbot.vo.QcTypeIndexVO;
import com.diagbot.vo.QcTypePageVO;
import com.diagbot.vo.QcTypeSaveVO;
import com.diagbot.vo.QcTypeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author:zhoutg
 * @time: 2018/11/23 11:37
 */
@Component
public class QcTypeFacade extends QcTypeServiceImpl {


    @Autowired
    @Qualifier("qcTypeCasesEntryServiceImpl")
    QcTypeCasesEntryServiceImpl qcTypeCasesEntryService;
    @Autowired
    QcCasesEntryFacade qcCasesEntryFacade;

    /**
     * 保存
     *
     * @param qcTypeSaveVO
     */
    public void saveOrUpdate(QcTypeSaveVO qcTypeSaveVO) {
        CommonParam param = initCommonParam();
        qcTypeSaveVO.setHospitalId(Long.valueOf(SysUserUtils.getCurrentHospitalID()));
        // 保存主表
        saveQcType(qcTypeSaveVO, param);
        // 保存质控类型和质控条目映射关系
        saveQcTypeCasesEntry(qcTypeSaveVO, param);
    }

    /**
     * 初始化参数
     *
     * @return
     */
    public CommonParam initCommonParam() {
        CommonParam param = new CommonParam();
        String person = SysUserUtils.getCurrentPrincipleID();
        param.setNow(DateUtil.now());
        param.setPerson(person);
        param.setInsertOrUpdate(InsertOrUpdateEnum.Insert.getKey());
        return param;
    }

    /**
     * 保存映射关系
     *
     * @param qcTypeSaveVO
     * @param param
     */
    public void saveQcTypeCasesEntry(QcTypeSaveVO qcTypeSaveVO, CommonParam param) {
        Date now = param.getNow();
        String person = param.getPerson();
        // 先删除原明细(物理删除)
        qcTypeCasesEntryService.remove(new QueryWrapper<QcTypeCasesEntry>()
                .eq("type_id", qcTypeSaveVO.getId())
        );
        // 再插入新明细
        List<QcTypeCasesEntryVO> qcTypeCasesEntryVOList = qcTypeSaveVO.getQcTypeCasesEntryVOList();
        if (ListUtil.isNotEmpty(qcTypeCasesEntryVOList)) {
            List<QcTypeCasesEntry> saveQcTypeCasesEntry = new ArrayList<>();
            for (QcTypeCasesEntryVO mapping : qcTypeCasesEntryVOList) {
                QcTypeCasesEntry bean = new QcTypeCasesEntry();
                bean.setCaseEntryId(mapping.getCaseEntryId());
                bean.setCreator(person);
                bean.setGmtCreate(now);
                bean.setModifier(person);
                bean.setGmtModified(now);
                bean.setTypeId(qcTypeSaveVO.getId());
                saveQcTypeCasesEntry.add(bean);
            }
            qcTypeCasesEntryService.saveBatch(saveQcTypeCasesEntry);
        }
    }

    /**
     * 保存主表
     *
     * @param qcTypeSaveVO
     * @param param
     */
    public void saveQcType(QcTypeSaveVO qcTypeSaveVO, CommonParam param) {
        QcType qcType = new QcType();
        Long id = qcTypeSaveVO.getId();

        // 保存主表
        if (qcTypeSaveVO.getId() != null) {
            qcType = this.getOne(new QueryWrapper<QcType>()
                    .eq("id", id)
                    .eq("hospital_id", qcTypeSaveVO.getHospitalId())
                    .eq("is_deleted", IsDeleteEnum.N.getKey()), false);
            if (qcType == null) { //校验
                throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "当前质控类型不存在【id=" + id + "】");
            }
            param.setInsertOrUpdate(InsertOrUpdateEnum.Update.getKey());
        }
        BeanUtil.copyProperties(qcTypeSaveVO, qcType);
        Integer count = this.count(new QueryWrapper<QcType>()
                .eq("name", qcTypeSaveVO.getName())
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", qcTypeSaveVO.getHospitalId())
                .ne("id", id == null ? -1 : id));
        // 质控类型hospitalId、name唯一
        if (count > 0) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "质控类型已存在");
        }
        if (InsertOrUpdateEnum.Insert.getKey() == param.getInsertOrUpdate()) {
            qcType.setCreator(param.getPerson()); //创建人
            qcType.setGmtCreate(param.getNow());//创建时间
        }
        qcType.setGmtModified(param.getNow());//修改时间
        qcType.setModifier(param.getPerson());//修改人
        this.saveOrUpdate(qcType);
        qcTypeSaveVO.setId(qcType.getId());
    }

    /**
     * 标签列表
     *
     * @param qcTypePageVO
     * @return
     */
    public IPage<QcTypePageDTO> getListFac(QcTypePageVO qcTypePageVO) {
        qcTypePageVO.setHospitalId(Long.valueOf(SysUserUtils.getCurrentHospitalID()));
        IPage<QcTypePageDTO> res = this.getList(qcTypePageVO);
        return res;
    }

    /**
     * 新增时质控条目分组信息
     *
     * @param qcEntryHospitalVO
     * @return
     */
    public Map<String, List<QcCasesEntrySimpleDTO>> getEntryByHospital(@RequestBody QcEntryHospitalVO qcEntryHospitalVO) {
        qcEntryHospitalVO.setHospitalId(Long.valueOf(SysUserUtils.getCurrentHospitalID()));
        List<QcCasesEntrySimpleDTO> qcCasesEntrySimpleDTOList = qcCasesEntryFacade.getEntryByHospital(qcEntryHospitalVO);
        return EntityUtil.makeEntityListMap(qcCasesEntrySimpleDTOList, "modeName");
    }

    /**
     * 检索
     *
     * @param qcTypeIndexVO
     * @return
     */
    public List<QcCasesEntrySimpleDTO> indexFac(QcTypeIndexVO qcTypeIndexVO) {
        qcTypeIndexVO.setHospitalId(Long.valueOf(SysUserUtils.getCurrentHospitalID()));
        List<QcCasesEntrySimpleDTO> res = qcCasesEntryFacade.index(qcTypeIndexVO);
        return res;
    }

    /**
     * 根据参数返回质控类型内容
     *
     * @param qcTypeVO 获取质控类型内容参数
     * @return 标签内容
     */
    public QcTypeDTO getById(QcTypeVO qcTypeVO) {
        QcTypeDTO qcTypeDTO = new QcTypeDTO();
        qcTypeVO.setHospitalId(Long.valueOf(SysUserUtils.getCurrentHospitalID()));
        QcType qcType = this.getOne(new QueryWrapper<QcType>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("hospital_id", qcTypeVO.getHospitalId())
                .eq("id", qcTypeVO.getId()), false
        );
        if (qcType == null) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR,
                    "当前质控类型不存在或已删除【id=" + qcTypeVO.getId() + "】");
        }
        BeanUtil.copyProperties(qcType, qcTypeDTO);
        List<QcCasesEntrySimpleDTO> list = qcTypeCasesEntryService.getByTypeId(qcTypeVO);
        Map<String, List<QcCasesEntrySimpleDTO>> entryMap = EntityUtil.makeEntityListMap(list, "modeName");
        qcTypeDTO.setEntryMap(entryMap);
        return qcTypeDTO;
    }

    /**
     * 根据id删除质控类型
     *
     * @param deleteQcTypeVO
     * @return
     */
    public Boolean deleteByIdsFac(DeleteQcTypeVO deleteQcTypeVO) {
        Date now = DateUtil.now();
        String person = SysUserUtils.getCurrentPrincipleID();
        // 更新主表
        Boolean res =
                this.update(new UpdateWrapper<QcType>()
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("hospital_id", SysUserUtils.getCurrentHospitalID())
                        .in("id", deleteQcTypeVO.getIds())
                        .set("is_deleted", IsDeleteEnum.Y.getKey())
                        .set("gmt_modified", now)
                        .set("modifier", person)
                );

        if (!res){
            throw new CommonException(CommonErrorCode.UPDATE_INFO_FAIL);
        }
        // 删除明细表
        if (ListUtil.isNotEmpty(deleteQcTypeVO.getIds())) {
            qcTypeCasesEntryService.remove(new QueryWrapper<QcTypeCasesEntry>()
                    .in("type_id", deleteQcTypeVO.getIds())
            );
        }
        return true;
    }

}