package com.lantone.daqe.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.lantone.common.enums.IsDeleteEnum;
import com.lantone.common.exception.Asserts;
import com.lantone.common.util.BeanUtil;
import com.lantone.common.util.DateUtil;
import com.lantone.common.util.ListUtil;
import com.lantone.common.util.SysUserUtils;
import com.lantone.daqe.dto.GetRegularPageDTO;
import com.lantone.daqe.entity.ColumnResult;
import com.lantone.daqe.entity.ColumnVerify;
import com.lantone.daqe.entity.RegularInfo;
import com.lantone.daqe.entity.RegularMapping;
import com.lantone.daqe.entity.RegularResult;
import com.lantone.daqe.enums.ColumnVerifyTypeEnum;
import com.lantone.daqe.facade.base.ColumnResultFacade;
import com.lantone.daqe.facade.base.ColumnVerifyFacade;
import com.lantone.daqe.facade.base.RegularInfoFacade;
import com.lantone.daqe.facade.base.RegularMappingFacade;
import com.lantone.daqe.facade.base.RegularResultFacade;
import com.lantone.daqe.vo.AddRegularVO;
import com.lantone.daqe.vo.DelRegularByIdVO;
import com.lantone.daqe.vo.GetRegularPageVO;
import com.lantone.daqe.vo.UpRegularByIdVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 正则式维护-业务处理类
 * @author: songxl
 * @time: 2022/3/4 10:39
 */
@Component
public class RegularManagementFacade {

    @Autowired
    private RegularInfoFacade regularInfoFacade;

    @Autowired
    private RegularResultFacade regularResultFacade;

    @Autowired
    private RegularMappingFacade regularMappingFacade;

    @Autowired
    private ColumnVerifyFacade columnVerifyFacade;

    @Autowired
    private ColumnResultFacade columnResultFacade;

    /**
     * 获取正则式维护分页列表
     *
     * @param getRegularPageVO
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.lantone.daqe.dto.GetRegularPageDTO>
     */
    public IPage<GetRegularPageDTO> getRegularPage(GetRegularPageVO getRegularPageVO) {
        QueryWrapper<RegularInfo> wrapper = new QueryWrapper();
        wrapper.like("name", getRegularPageVO.getName());
        regularInfoFacade.list(wrapper);
        return regularInfoFacade.getBaseMapper().getRegularPage(getRegularPageVO);
    }

    /**
     * 新增正则式 业务处理
     *
     * @param addRegularVO
     * @return 是否新增成功
     */
    public Boolean addRegular(AddRegularVO addRegularVO) {
        RegularInfo regularInfo = new RegularInfo();
        BeanUtils.copyProperties(addRegularVO, regularInfo);
        if (regularInfoFacade.isExist(regularInfo)) {
            Asserts.fail("该正则式已存在！");
        }
        regularInfo.setCreator(SysUserUtils.getCurrentPrinciple() == null ? "0" : SysUserUtils.getCurrentPrinciple());
        regularInfo.setGmtCreate(DateUtil.now());
        return regularInfoFacade.save(regularInfo);
    }

    /**
     * 通过id修改正则式
     *
     * @param upRegularByIdVO
     * @return 是否修改成功
     */
    public Boolean upRegularById(UpRegularByIdVO upRegularByIdVO) {
        if (regularInfoFacade.getById(upRegularByIdVO.getId()) == null) {
            Asserts.fail("该正则式不存在！");
        }
        //修改正则式
        RegularInfo regularInfo = new RegularInfo();
        BeanUtil.copyProperties(upRegularByIdVO, regularInfo);
        regularInfo.setModifier(SysUserUtils.getCurrentPrinciple() == null ? "0" : SysUserUtils.getCurrentPrinciple());
        regularInfo.setGmtModified(DateUtil.now());
        //修改表字段的正则式校验结果表中的正则式
        //先获取正则维护关联表id
        List<Long> regularMappingIdList = getRegularMappingId(upRegularByIdVO.getId());
        if (regularInfoFacade.updateById(regularInfo)) {
            if (ListUtil.isNotEmpty(regularMappingIdList)) {
                return columnVerifyFacade.update(new UpdateWrapper<ColumnVerify>()
                        .in("verify_id", regularMappingIdList)
                        .eq("is_deleted", IsDeleteEnum.N.getKey())
                        .eq("type", ColumnVerifyTypeEnum.REGULAR_TYPE.getKey())
                        .set("verify_val", upRegularByIdVO.getName())
                        .set("modifier", SysUserUtils.getCurrentPrinciple() == null ? "0" : SysUserUtils.getCurrentPrinciple())
                        .set("gmt_modified", DateUtil.now()));
            }
            return true;
        }
        return false;
    }

    /**
     * 通过id删除正则式
     *
     * @param delRegularByIdVO
     * @return 是否删除成功
     */
    public Boolean delRegularById(DelRegularByIdVO delRegularByIdVO) {
        Boolean flag = false;
        for (Long id : delRegularByIdVO.getIds()) {
            flag = delRegularById(id, delRegularByIdVO.getHospitalId());
        }
        return flag;
    }

    /**
     * 通过id删除正则式
     *
     * @param id
     * @param hospitalId
     * @Return java.lang.Boolean
     */
    private Boolean delRegularById(Long id, Long hospitalId) {

        if (regularInfoFacade.getById(id) == null) {
            Asserts.fail("该正则式不存在！");
        }
        if (regularInfoFacade.removeById(id)) {
            //先获取正则维护关联表id
            List<Long> regularMappingIdList = getRegularMappingId(id);
            //删除表字段的实际值与正则式关联关系
            if (regularMappingFacade.remove(new UpdateWrapper<RegularMapping>()
                    .eq("regular_id", id)
                    .eq("is_deleted", IsDeleteEnum.N.getKey()))) {
                if (columnVerifyFacade.remove(new UpdateWrapper<ColumnVerify>()
                        .in("verify_id", regularMappingIdList)
                        .eq("type", ColumnVerifyTypeEnum.REGULAR_TYPE.getKey())
                        .eq("is_deleted", IsDeleteEnum.N.getKey()))) {
                    //拿到正则结果表中关联数据的id
                    List<RegularResult> regularResults = regularResultFacade.getBaseMapper().selectList(new QueryWrapper<RegularResult>()
                            .eq("regular_id", id)
                            .eq("is_deleted", IsDeleteEnum.N.getKey())
                    );
                    List<Long> regularResultId = new ArrayList<>();
                    regularResults.stream().forEach(regularResult->{
                        regularResultId.add(regularResult.getId());
                    });
                    //            删除表字段的正则式校验结果表中的正则式
                    if (regularResultFacade.remove(new UpdateWrapper<RegularResult>()
                            .eq(hospitalId != null, "hospital_id", hospitalId)
                            .eq("regular_id", id)
                            .eq("is_deleted", IsDeleteEnum.N.getKey()))) {
                        //删除总结果表信息
                        return columnResultFacade.remove(new UpdateWrapper<ColumnResult>()
                                .eq(hospitalId != null, "hospital_id", hospitalId)
                                .eq("is_deleted", IsDeleteEnum.N.getKey())
                                .in(ListUtil.isNotEmpty(regularResultId),"result_id",regularResultId)
                        );
                    }
                }
            }


        }
        return false;
    }

    /**
     * 根据正则id获取正则维护表id集合
     *
     * @param id
     * @return: 正则维护表id集合
     */
    public List<Long> getRegularMappingId(Long id) {
        List<Long> regularMappingIdList = new ArrayList<>();
        List<RegularMapping> regularMappingList = regularMappingFacade.getBaseMapper().selectList(new QueryWrapper<RegularMapping>()
                .eq("regular_id", id)
                .eq("is_deleted", IsDeleteEnum.N.getKey())
        );
        if (ListUtil.isNotEmpty(regularMappingList)) {
            for (RegularMapping regularMapping : regularMappingList) {
                regularMappingIdList.add(regularMapping.getId());
            }
        }
        return regularMappingIdList;
    }

    /**
     * 判断该正则式是否关联
     *
     * @param upRegularByIdVO
     * @Return java.lang.Boolean
     */
    public Boolean isRelation(UpRegularByIdVO upRegularByIdVO) {
        int count = regularMappingFacade.count(new QueryWrapper<RegularMapping>()
                .eq("is_deleted", IsDeleteEnum.N.getKey())
                .eq("regular_id", upRegularByIdVO.getId()));
        if (count > 0) {
            return true;
        }
        return false;
    }
}