package com.testor.ddd.safetyControl.infrastructure.repository.lecls.service;

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.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.testor.ddd.safetyControl.domain.lecls.entity.TSafeRiskLeclsRelationRepo;
import com.testor.ddd.safetyControl.infrastructure.repository.lecls.dao.TSafeRiskLeclsRelationDao;
import com.testor.ddd.safetyControl.infrastructure.repository.lecls.entity.TSafeRiskLeclsRelationDO;
import com.testor.ddd.safetyControl.interfaces.model.dto.lecls.RiskLeclsValDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.lecls.TSafeRiskLeclsRelationDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.lecls.TSafeRiskLeclsRelationDTOParam;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 危险源Service业务层处理
 * 
 * @author testor-framework
 * @date 2022-07-11 10:00:17
 */
@Service
public class TSafeRiskLeclsRelationServiceImpl extends SuperServiceImpl<TSafeRiskLeclsRelationDao, TSafeRiskLeclsRelationDO>
        implements TSafeRiskLeclsRelationRepo
{
    @Autowired(required = false)
    private TSafeRiskLeclsRelationDao tSafeRiskLeclsRelationDao;

    public TSafeRiskLeclsRelationDTO insert(TSafeRiskLeclsRelationDTO riskLeclsRelationDTO){
        TSafeRiskLeclsRelationDO data = BeanHelper.beanToBean(riskLeclsRelationDTO, TSafeRiskLeclsRelationDO.class);
        int result = tSafeRiskLeclsRelationDao.insert(data);
        if(result < 1) {
            return null;
        }
        riskLeclsRelationDTO = BeanHelper.beanToBean(data, TSafeRiskLeclsRelationDTO.class);
        return riskLeclsRelationDTO;
    }

    public TSafeRiskLeclsRelationDTO updateById(TSafeRiskLeclsRelationDTO riskLeclsRelationDTO){
        TSafeRiskLeclsRelationDO data = BeanHelper.beanToBean(riskLeclsRelationDTO, TSafeRiskLeclsRelationDO.class);
        int result = tSafeRiskLeclsRelationDao.updateById(data);
        if(result < 1) {
            return null;
        }
        riskLeclsRelationDTO = BeanHelper.beanToBean(data, TSafeRiskLeclsRelationDTO.class);
        return riskLeclsRelationDTO;
    }
    
    public TSafeRiskLeclsRelationDTO findById(String id){
        if(StrUtil.isBlank(id)) {
            return null;
        }
        TSafeRiskLeclsRelationDO riskLeclsRelationDo = tSafeRiskLeclsRelationDao.selectById(id);
        TSafeRiskLeclsRelationDTO riskLeclsRelationDTO = BeanHelper.beanToBean(riskLeclsRelationDo, TSafeRiskLeclsRelationDTO.class);
        return riskLeclsRelationDTO;
    }

    public boolean deleteById(String id){
        UpdateWrapper<TSafeRiskLeclsRelationDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(TSafeRiskLeclsRelationDO::getStatus, BizConstants.STATUS_DELETE)
                .ne(TSafeRiskLeclsRelationDO::getStatus, BizConstants.STATUS_DELETE)
                .eq(TSafeRiskLeclsRelationDO::getId,id);
        return update(updateWrapper);
    }

    /* Private Methods */
    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TSafeRiskLeclsRelationDO> createQuery(TSafeRiskLeclsRelationDTOParam queryParam){
        QueryWrapper<TSafeRiskLeclsRelationDO> queryWrapper=new QueryWrapper<>();
        if(ObjectHelper.isNotEmpty(queryParam.getType())){
            queryWrapper.eq(TSafeRiskLeclsRelationDO.TYPE,queryParam.getType());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getValueType())){
            queryWrapper.eq(TSafeRiskLeclsRelationDO.VALUE_TYPE,queryParam.getValueType());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getMaxValue())){
            queryWrapper.eq(TSafeRiskLeclsRelationDO.MAX_VALUE,queryParam.getMaxValue());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getMinValue())){
            queryWrapper.eq(TSafeRiskLeclsRelationDO.MIN_VALUE,queryParam.getMinValue());
        }
        if(ObjectHelper.isNotEmpty(queryParam.getValue())){
            queryWrapper.eq(TSafeRiskLeclsRelationDO.VALUE,queryParam.getValue());
        }
        if(StringHelper.isNotEmpty(queryParam.getRealLevel())){
            queryWrapper.eq(TSafeRiskLeclsRelationDO.REAL_LEVEL,queryParam.getRealLevel());
        }
        if(StringHelper.isNotEmpty(queryParam.getIsIncludeMax())){
            queryWrapper.eq(TSafeRiskLeclsRelationDO.IS_INCLUDE_MAX,queryParam.getIsIncludeMax());
        }
        if(StringHelper.isNotEmpty(queryParam.getIsIncludeMin())){
            queryWrapper.eq(TSafeRiskLeclsRelationDO.IS_INCLUDE_MIN,queryParam.getIsIncludeMin());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TSafeRiskLeclsRelationDO.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TSafeRiskLeclsRelationDO.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())){
            if(StringHelper.isNotEmpty(queryParam.getOrderType())
                    &&BizConstants.ASC.equals(queryParam.getOrderType())){
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            }else{
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        }else{
            queryWrapper.orderByDesc(TSafeRiskLeclsRelationDO.UPDATE_DATE);
        }
        return queryWrapper;
    }

    public boolean saveBatch(List<TSafeRiskLeclsRelationDTO> riskLeclsRelationDTOList){
        List<TSafeRiskLeclsRelationDO> riskLeclsRelationDOList = BeanHelper.listToList(riskLeclsRelationDTOList, TSafeRiskLeclsRelationDO.class);
        return saveBatch(riskLeclsRelationDOList);
    }

    public List<TSafeRiskLeclsRelationDTO> saveOrUpdateBatch(List<TSafeRiskLeclsRelationDTO> riskLeclsRelationDTOList){
        List<TSafeRiskLeclsRelationDO> riskLeclsRelationDOList = BeanHelper.listToList(riskLeclsRelationDTOList, TSafeRiskLeclsRelationDO.class);
        boolean result = saveOrUpdateBatch(riskLeclsRelationDOList);
        riskLeclsRelationDTOList = BeanHelper.listToList(riskLeclsRelationDOList, TSafeRiskLeclsRelationDTO.class);
        if(result) {
            return riskLeclsRelationDTOList;
        }
        return null;
    }

    public boolean deleteRelationByType(Integer type){
        if(type == null) {
            return false;
        }
        UpdateWrapper<TSafeRiskLeclsRelationDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(TSafeRiskLeclsRelationDO::getStatus, BizConstants.STATUS_DELETE)
                .ne(TSafeRiskLeclsRelationDO::getStatus, BizConstants.STATUS_DELETE)
                .eq(TSafeRiskLeclsRelationDO::getType,type);
        return update(updateWrapper);
    }

    /**
     * 根据 lec/ls 计算 现实风险等级
     * @param leclsValDTO
     */
    public TSafeRiskLeclsRelationDTO findLevelByLecls(RiskLeclsValDTO leclsValDTO) throws BusinessException {
        int valueType = leclsValDTO.getValueType();
        int type = leclsValDTO.getType();
        float value = leclsValDTO.getValue();

        LambdaQueryWrapper<TSafeRiskLeclsRelationDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSafeRiskLeclsRelationDO::getStatus, BizConstants.STATUS_ENABLE)
                .eq(TSafeRiskLeclsRelationDO::getType, type)
                .eq(TSafeRiskLeclsRelationDO::getValueType, valueType);

        List<TSafeRiskLeclsRelationDO> relationDOList;
        TSafeRiskLeclsRelationDO riskLeclsRelationDO;
        TSafeRiskLeclsRelationDTO riskLeclsRelationDTO;
        if(valueType == 2) {// 固定值
            queryWrapper.eq(TSafeRiskLeclsRelationDO::getValue, value);
            relationDOList = tSafeRiskLeclsRelationDao.selectList(queryWrapper);
            if(relationDOList == null || relationDOList.size() != 1 ) {
                throw new BusinessException("lec/ls值超出设置范围，请先确认功能配置模块--lec/ls值设置范围");
            }
            riskLeclsRelationDO = relationDOList.get(0);
            riskLeclsRelationDTO = BeanHelper.beanToBean(riskLeclsRelationDO, TSafeRiskLeclsRelationDTO.class);
           return riskLeclsRelationDTO;
        }

        // 范围值 逻辑
        relationDOList = tSafeRiskLeclsRelationDao.selectList(queryWrapper);
        if(relationDOList == null || relationDOList.size() == 0 ) {
            throw new BusinessException("lec/ls值超出设置范围，请先确认功能配置模块--lec/ls值设置范围");
        }

        try{
            ExpressRunner runner = new ExpressRunner();
            for(TSafeRiskLeclsRelationDO relationDO : relationDOList) {
                String formulaStr = relationDO.getFormulaStr();
                if(StrUtil.isBlank(formulaStr)) {
                    throw new BusinessException("lec/ls 配置信息错误，请先确认功能配置模块--lec/ls配置信息");
                }
                DefaultContext<String, Object> context = new DefaultContext<>();
                context.put("param", value);
                boolean boo = (boolean) runner.execute(formulaStr, context, null, true, false);
                if(boo) {
                    riskLeclsRelationDTO = BeanHelper.beanToBean(relationDO, TSafeRiskLeclsRelationDTO.class);
                    return riskLeclsRelationDTO;
                }
            }

            throw new BusinessException("lec/ls值超出设置范围，请先确认功能配置模块--lec/ls值设置范围");

        } catch(BusinessException e){
           throw e;
        } catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

//    public BaseResponseList<TSafeRiskLeclsRelationDTO> listPage(TSafeRiskLeclsRelationDTOParam param){
//        Long page =
//                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
//        Long limit =
//                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
//        Page<TSafeRiskLeclsRelationDTO> resultPage = new Page<>(page, limit);
//        IPage<TSafeRiskLeclsRelationDTO> iPage = tSafeRiskLeclsRelationDao.listPage(resultPage, param);
//
//        BaseResponseList<TSafeRiskLeclsRelationDTO> baseResponseList=new BaseResponseList<>();
//        baseResponseList.setData(iPage.getRecords());
//        baseResponseList.setTotal(iPage.getTotal());
//        return baseResponseList;
//    }

    public List<TSafeRiskLeclsRelationDTO> listAllEntity(TSafeRiskLeclsRelationDTOParam param){
//        QueryWrapper<TSafeRiskLeclsRelationDO> queryWrapper=this.createQuery(param);
//        List<TSafeRiskLeclsRelationDO> resultList=list(queryWrapper);
//        List<TSafeRiskLeclsRelationDTO> resultDTOList= BeanHelper.listToList(resultList, TSafeRiskLeclsRelationDTO.class);
//        return resultDTOList;
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TSafeRiskLeclsRelationDTO> resultPage = new Page<>(page, limit);
        IPage<TSafeRiskLeclsRelationDTO> iPage = tSafeRiskLeclsRelationDao.listPage(resultPage, param);

//        BaseResponseList<TSafeRiskLeclsRelationDTO> baseResponseList=new BaseResponseList<>();
//        baseResponseList.setData(iPage.getRecords());
//        baseResponseList.setTotal(iPage.getTotal());
        return iPage.getRecords();
    }

}

