package com.testor.module.safeCheck.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.common.util.CheckResultStatusEnum;
import com.testor.common.util.CheckTaskStatusEnum;
import com.testor.module.safe.model.vo.TSafeHazardOptionVO;
import com.testor.module.safe.service.TSafeHazardOptionService;
import com.testor.module.safeCheck.dao.TSafeHazardCheckResultDetailDao;
import com.testor.module.safeCheck.model.domain.TSafeHazardCheckResult;
import com.testor.module.safeCheck.model.domain.TSafeHazardCheckResultDetail;
import com.testor.module.safeCheck.model.domain.TSafeHazardCheckTask;
import com.testor.module.safeCheck.model.dto.TSafeHazardCheckResultDetailParam;
import com.testor.module.safeCheck.model.vo.SafeHazardCheckResultDetailCountVO;
import com.testor.module.safeCheck.model.vo.SafeHazardCheckResultDetailVO;
import com.testor.module.safeCheck.service.TSafeHazardCheckResultDetailService;
import com.testor.module.safeCheck.service.TSafeHazardCheckResultService;
import com.testor.module.safeCheck.service.TSafeHazardCheckTaskService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 巡检结果明细(关联标准)Service业务层处理
 * 
 * @author testor-framework
 * @date 2022-08-04 11:07:56
 */
@Slf4j
@Service
public class TSafeHazardCheckResultDetailServiceImpl extends SuperServiceImpl<TSafeHazardCheckResultDetailDao, TSafeHazardCheckResultDetail> implements TSafeHazardCheckResultDetailService
{
    @Autowired(required = false)
    private TSafeHazardCheckResultDetailDao tSafeHazardCheckResultDetailDao;

    @Autowired
    private TSafeHazardOptionService tSafeHazardOptionService;

    @Autowired
    private TSafeHazardCheckResultService tSafeHazardCheckResultService;

    @Autowired
    private TSafeHazardCheckTaskService tSafeHazardCheckTaskService;

    public Boolean createResultDetail(String resultId, String standardId){
        if(StrUtil.isBlank(resultId) || StrUtil.isBlank(standardId)) {
            log.error("创建巡检结果明细 参数缺失 resultId:{}, standardId:{}", resultId, standardId);
            return false;
        }

        //巡查标准细则
        List<TSafeHazardOptionVO> byParentIdList = tSafeHazardOptionService.getRulesList(standardId);
        if(byParentIdList == null || byParentIdList.size() == 0) {
            log.error("{} 未设置排查项", standardId);
            return false;
        }

        List<TSafeHazardCheckResultDetail> addList = new ArrayList<>();
        TSafeHazardCheckResultDetail checkResultDetail;
        for(TSafeHazardOptionVO option : byParentIdList) {

            checkResultDetail = new TSafeHazardCheckResultDetail();
            checkResultDetail.setResultId(resultId);
            checkResultDetail.setOptionId(option.getId());
            checkResultDetail.setOptionParentId(option.getParentId());
            addList.add(checkResultDetail);
        }

        return saveBatch(addList, addList.size());
    }

    public List<SafeHazardCheckResultDetailVO> listByResult(String resultId){
        return tSafeHazardCheckResultDetailDao.listByResult(resultId);
    }

    public List<SafeHazardCheckResultDetailCountVO> countByResult(String resultId){
        return tSafeHazardCheckResultDetailDao.countByResult(resultId);
    }

    public List<TSafeHazardCheckResultDetail> listAllEntity(TSafeHazardCheckResultDetailParam param){
        QueryWrapper<TSafeHazardCheckResultDetail> queryWrapper=this.createQuery(param);
        List<TSafeHazardCheckResultDetail> resultList=list(queryWrapper);
        return resultList;
    }

    /* Private Methods */
    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TSafeHazardCheckResultDetail> createQuery(TSafeHazardCheckResultDetailParam queryParam){
        QueryWrapper<TSafeHazardCheckResultDetail> queryWrapper=new QueryWrapper<>();
        if(StringHelper.isNotEmpty(queryParam.getResultId())){
            queryWrapper.eq(TSafeHazardCheckResultDetail.RESULT_ID,queryParam.getResultId());
        }
        if(StringHelper.isNotEmpty(queryParam.getResultTypeId())){
            queryWrapper.eq(TSafeHazardCheckResultDetail.RESULT_TYPE_ID,queryParam.getResultTypeId());
        } else if("-1".equals(queryParam.getResultTypeId())){ // 查询所有

        } else {
            queryWrapper.isNull(TSafeHazardCheckResultDetail.RESULT_TYPE_ID);
        }
        if(StringHelper.isNotEmpty(queryParam.getRelationId())){
            queryWrapper.eq(TSafeHazardCheckResultDetail.RELATION_ID,queryParam.getRelationId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TSafeHazardCheckResultDetail.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TSafeHazardCheckResultDetail.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(TSafeHazardCheckResultDetail.UPDATE_DATE);
        }
        return queryWrapper;
    }

    /**
     *  修改巡检结果 值
     *  需要传id\result_type_id两个值
     *  当有 隐患上报时 需要 relationId(隐患id)
     */
    @Transactional
    public BaseResponse updateResultDetail(TSafeHazardCheckResultDetail resultDetail){

        BaseResponse baseResponse = new BaseResponse<>();

        String detailId = resultDetail.getId();
        String resultTypeId = resultDetail.getResultTypeId();

        if(StrUtil.isBlank(detailId)) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("参数缺失");
            return baseResponse;
        }

        if(StrUtil.isBlank(resultTypeId)) {
            baseResponse.setCode(BaseStatusEnum.SUCCESS.code());
            return baseResponse;
        }

        TSafeHazardCheckResultDetail detail = getById(detailId);
        TSafeHazardCheckResult result = tSafeHazardCheckResultService.getById(detail.getResultId());
        TSafeHazardCheckTask task = tSafeHazardCheckTaskService.getById(result.getTaskId());
        if(task.getTaskStatus() == CheckTaskStatusEnum.nostart.getCode().intValue()
            || task.getTaskStatus() == CheckTaskStatusEnum.complete.getCode()) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("当前任务状态不允许修改！");
            return baseResponse;
        }

        if(!StrUtil.isBlank(detail.getRelationId())) {
            baseResponse.setCode(701);
            baseResponse.setMsg("已上报隐患不允许修改！");
            return baseResponse;
        }

        detail.setResultTypeId(resultTypeId);
        if(!StrUtil.isBlank(resultDetail.getRelationId())) {
            detail.setRelationId(resultDetail.getRelationId());
        }

        boolean updateResult = updateById(detail);
        if(!updateResult) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("编辑失败！");
            return baseResponse;
        }

        // 判断更新 巡检结果 的 状态 （通过数量 或是 result_type_id 为null的数量判断）
        TSafeHazardCheckResultDetailParam detailParam = new TSafeHazardCheckResultDetailParam();
        detailParam.setStatus(BizConstants.STATUS_ENABLE);
        detailParam.setResultId(result.getId());
        detailParam.setResultTypeId("-1");
        List<TSafeHazardCheckResultDetail> allNum = listAllEntity(detailParam);
        detailParam.setResultTypeId(null);
        List<TSafeHazardCheckResultDetail> noCheckNum = listAllEntity(detailParam);
        if(noCheckNum == null || noCheckNum.size() == 0) {
            result.setResultStatus(CheckResultStatusEnum.complete.getCode());
        } else if(noCheckNum.size() == allNum.size()){
            result.setResultStatus(CheckResultStatusEnum.nostart.getCode());
        } else {
            result.setResultStatus(CheckResultStatusEnum.running.getCode());
        }
        tSafeHazardCheckResultService.updateById(result);

        baseResponse.setCode(BaseStatusEnum.SUCCESS.code());
        return baseResponse;
    }

    /**
     *  修改巡检结果 值
     *  需要传id\result_type_id两个值
     *  当有 隐患上报时 需要 relationId(隐患id)
     */
    @Transactional
    public BaseResponse updateResultDetailList(List<TSafeHazardCheckResultDetail> resultDetailList){

        BaseResponse baseResponse = new BaseResponse<>();
        if(resultDetailList == null || resultDetailList.size() == 0) {
            baseResponse.setCode(BaseStatusEnum.SUCCESS.code());
            return baseResponse;
        }

        for(TSafeHazardCheckResultDetail detail : resultDetailList) {
            BaseResponse detailResponse = updateResultDetail(detail);
            if(detailResponse.getCode() != BaseStatusEnum.SUCCESS.code()
            && detailResponse.getCode() != 701) { // 701 已上报隐患
               // return detailResponse;
                throw new RuntimeException("编辑失败");
            }
        }

        baseResponse.setCode(BaseStatusEnum.SUCCESS.code());
        return baseResponse;
    }
}


