package com.testor.module.contractor.manage.controller;

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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.testor.common.util.BeanConverUtil;
import com.testor.module.contractor.manage.model.domain.TContractorDailyPlanInspectResult;
import com.testor.module.contractor.manage.model.domain.TContractorDailyPlanInspectResultHazard;
import com.testor.module.contractor.manage.model.dto.TContractorDailyPlanInspectDTO;
import com.testor.module.contractor.manage.model.dto.TContractorDailyPlanInspectResultDTO;
import com.testor.module.contractor.manage.service.TContractorDailyPlanInspectResultHazardService;
import com.testor.module.contractor.manage.service.TContractorDailyPlanInspectResultService;
import com.tongtech.tfw.backend.common.models.exceptions.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;

import com.testor.module.contractor.manage.model.domain.TContractorDailyPlanInspect;
import com.testor.module.contractor.manage.model.dto.TContractorDailyPlanInspectParam;
import com.testor.module.contractor.manage.model.dto.TContractorDailyPlanInspectDelParam;
import com.testor.module.contractor.manage.service.TContractorDailyPlanInspectService;

/**
 * 日常管理-每日工作计划-检查任务Controller
 *
 * @author testor-framework
 * @date 2024-11-30 15:43:16
 */
@RestController
@RequestMapping("/manage/inspect")
@Api(value = "TContractorDailyPlanInspect", tags = "日常管理-每日工作计划-检查任务")
@Slf4j
public class TContractorDailyPlanInspectController extends SuperController
{
    @Autowired
    private TContractorDailyPlanInspectService tContractorDailyPlanInspectService;

	@Autowired
	private TContractorDailyPlanInspectResultService tContractorDailyPlanInspectResultService;

	@Autowired
	private TContractorDailyPlanInspectResultHazardService tContractorDailyPlanInspectResultHazardService;


    /* Generated Method*/
	@ApiOperation(value = "新增 日常管理-每日工作计划-检查任务", notes = "Add TContractorDailyPlanInspect")
	@PostMapping(value = "/add")
	public BaseResponse<TContractorDailyPlanInspect>addEntity(@RequestBody TContractorDailyPlanInspectDTO addRequest) {
		BaseResponse<TContractorDailyPlanInspect> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			int count = tContractorDailyPlanInspectService.count(new LambdaQueryWrapper<TContractorDailyPlanInspect>()
					.eq(TContractorDailyPlanInspect::getPlanId, addRequest.getPlanId())
					.eq(TContractorDailyPlanInspect::getInspectTypeId, addRequest.getInspectTypeId()));
			if(count > 0){
				throw new ServiceException("该检查类型已存在");
			}
			String id = IdHelper.getId32bit();
            TContractorDailyPlanInspect data=BeanHelper.beanToBean(addRequest,  TContractorDailyPlanInspect.class);
			data.setId(id);
			boolean result= tContractorDailyPlanInspectService.save(data);
			//检查结果
			List<TContractorDailyPlanInspectResult> tContractorDailyPlanInspectResults = addRequest.getTContractorDailyPlanInspectResults();
			if(tContractorDailyPlanInspectResults != null && !tContractorDailyPlanInspectResults.isEmpty()){
				for(TContractorDailyPlanInspectResult tContractorDailyPlanInspectResult : tContractorDailyPlanInspectResults){
					tContractorDailyPlanInspectResult.setId(IdHelper.getId32bit());
					tContractorDailyPlanInspectResult.setInspectId(id);
					TContractorDailyPlanInspectResult dailyPlanInspectResult = BeanConverUtil.conver(tContractorDailyPlanInspectResult, TContractorDailyPlanInspectResult.class);
					String dailyPlanInspectResultId = IdHelper.getId32bit();
					tContractorDailyPlanInspectResultService.save(dailyPlanInspectResult);
					if(tContractorDailyPlanInspectResult.getHazardIds() != null && !tContractorDailyPlanInspectResult.getHazardIds().isEmpty()) {
						//检查任务隐患
						for (String hazardId : tContractorDailyPlanInspectResult.getHazardIds()) {
							TContractorDailyPlanInspectResultHazard tContractorDailyPlanInspectResultHazard = new TContractorDailyPlanInspectResultHazard();
							tContractorDailyPlanInspectResultHazard.setInspectId(id);
							tContractorDailyPlanInspectResultHazard.setInspectResultId(dailyPlanInspectResultId);
							tContractorDailyPlanInspectResultHazard.setPlanId(addRequest.getPlanId());
							tContractorDailyPlanInspectResultHazard.setHazardId(hazardId);
							tContractorDailyPlanInspectResultHazardService.save(tContractorDailyPlanInspectResultHazard);
						}
					}
				}
			}
			if(result){
                TContractorDailyPlanInspect newEntity = new TContractorDailyPlanInspect();
				newEntity.setId(id);
				baseResponse.setData(newEntity);
			}
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 日常管理-每日工作计划-检查任务 ", notes = "Get TContractorDailyPlanInspect By Id")
	@GetMapping(value = "/get")
	public BaseResponse<TContractorDailyPlanInspectDTO> getById(String id){
		BaseResponse<TContractorDailyPlanInspectDTO> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
            TContractorDailyPlanInspect data= tContractorDailyPlanInspectService.getById(id);
            if(data==null){
            	 data=new TContractorDailyPlanInspect();
			}
			TContractorDailyPlanInspectDTO tContractorDailyPlanInspectDTO = BeanHelper.beanToBean(data, TContractorDailyPlanInspectDTO.class);
			List<String> hazardIdsByInspectId = tContractorDailyPlanInspectResultHazardService.getHazardIdsByInspectId(id);
			tContractorDailyPlanInspectDTO.setHazardIds(hazardIdsByInspectId);
			List<TContractorDailyPlanInspectResult> tContractorDailyPlanInspectResults = tContractorDailyPlanInspectResultService.list(new LambdaQueryWrapper<>(new TContractorDailyPlanInspectResult().setInspectId(id)));
			if (tContractorDailyPlanInspectResults != null && !tContractorDailyPlanInspectResults.isEmpty()) {
				for (TContractorDailyPlanInspectResult tContractorDailyPlanInspectResult : tContractorDailyPlanInspectResults) {
					List<String> hazardIdsByInspectResultId = tContractorDailyPlanInspectResultHazardService.getHazardIdsByInspectResultId(tContractorDailyPlanInspectResult.getId());
					tContractorDailyPlanInspectResult.setHazardIds(hazardIdsByInspectResultId);
				}
			}
			tContractorDailyPlanInspectDTO.setTContractorDailyPlanInspectResults(tContractorDailyPlanInspectResults);
			baseResponse.setData(tContractorDailyPlanInspectDTO);
		}
		return baseResponse;
	}

	@ApiOperation(value = "修改 日常管理-每日工作计划-检查任务 ", notes = "Update TContractorDailyPlanInspect By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorDailyPlanInspect updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorDailyPlanInspect data=BeanHelper.beanToBean(updateRequest, TContractorDailyPlanInspect.class);
			boolean result= tContractorDailyPlanInspectService.updateById(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "删除 日常管理-每日工作计划-检查任务 ", notes = "delete TContractorDailyPlanInspect By Id")
	@PutMapping(value = "/delete")
	public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TContractorDailyPlanInspectDelParam deleteRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(deleteRequest)&&StringHelper.isNotEmpty(deleteRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorDailyPlanInspect data= new TContractorDailyPlanInspect();
			data.setId(deleteRequest.getId());
			data.setStatus(BizConstants.STATUS_DELETE);
			boolean result= tContractorDailyPlanInspectService.updateById(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "批量删除日常管理-每日工作计划-检查任务", notes = "delete TContractorDailyPlanInspect by batch Id")
	@PutMapping(value = "/batch_delete")
	public BaseResponse<BizGeneralResponse> deleteEntityBatch(
			@RequestBody TContractorDailyPlanInspectDelParam deleteRequest) {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
			List<TContractorDailyPlanInspect> tContractorDailyPlanInspectList = new ArrayList<>();
            for(String id: deleteRequest.getIds()){
                TContractorDailyPlanInspect data= new TContractorDailyPlanInspect();
				data.setId(id);
				data.setStatus(BizConstants.STATUS_DELETE);
                tContractorDailyPlanInspectList.add(data);
			}
			boolean result = tContractorDailyPlanInspectService.updateBatchById(tContractorDailyPlanInspectList);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 日常管理-每日工作计划-检查任务 分页列表", notes = "List TContractorDailyPlanInspect with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<TContractorDailyPlanInspect>>listEntity(TContractorDailyPlanInspectParam param){
		BaseResponse<BaseResponseList<TContractorDailyPlanInspect>>baseResponse=new BaseResponse<>();
		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<TContractorDailyPlanInspect> resultPage=new Page<>(page,limit);
		// TODO 根据需求修改查询条件及查询参数
		QueryWrapper<TContractorDailyPlanInspect> queryWrapper=this.createQuery(param);
		Page<TContractorDailyPlanInspect> resultList= tContractorDailyPlanInspectService.page(resultPage,queryWrapper);
		BaseResponseList<TContractorDailyPlanInspect> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "获取 日常管理-每日工作计划-检查任务 列表", notes = "List TContractorDailyPlanInspect all")
	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<TContractorDailyPlanInspect>>listAllEntity(TContractorDailyPlanInspectParam param){
		BaseResponse<BaseResponseList<TContractorDailyPlanInspect>>baseResponse=new BaseResponse<>();
		// TODO 根据需求修改查询条件及查询参数
		QueryWrapper<TContractorDailyPlanInspect> queryWrapper=this.createQuery(param);
		List<TContractorDailyPlanInspect> resultList=tContractorDailyPlanInspectService.list(queryWrapper);
		for (TContractorDailyPlanInspect tContractorDailyPlanInspect : resultList) {
			List<String> hazardIdsByInspectId = tContractorDailyPlanInspectResultHazardService.getHazardIdsByInspectId(tContractorDailyPlanInspect.getId());
			tContractorDailyPlanInspect.setHazardIds(hazardIdsByInspectId);
		}
		BaseResponseList<TContractorDailyPlanInspect> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

    /* Private Methods */
	/**
     * 列表查询条件及查询参数
     */
	private QueryWrapper<TContractorDailyPlanInspect> createQuery(TContractorDailyPlanInspectParam queryParam){
		QueryWrapper<TContractorDailyPlanInspect> queryWrapper=new QueryWrapper<>();
		if(StringHelper.isNotEmpty(queryParam.getPlanId())){
			queryWrapper.eq(TContractorDailyPlanInspect.PLAN_ID,queryParam.getPlanId());
		}
		if(StringHelper.isNotEmpty(queryParam.getInspectTypeId())){
			queryWrapper.eq(TContractorDailyPlanInspect.INSPECT_TYPE_ID,queryParam.getInspectTypeId());
		}
		if(StringHelper.isNotEmpty(queryParam.getInspectType())){
			queryWrapper.eq(TContractorDailyPlanInspect.INSPECT_TYPE,queryParam.getInspectType());
		}
		if(StringHelper.isNotEmpty(queryParam.getInspector())){
			queryWrapper.eq(TContractorDailyPlanInspect.INSPECTOR,queryParam.getInspector());
		}
		if(ObjectHelper.isNotEmpty(queryParam.getInspectTime())){
			queryWrapper.eq(TContractorDailyPlanInspect.INSPECT_TIME,queryParam.getInspectTime());
		}
		if (StringHelper.isNotEmpty(queryParam.getStatus())) {
			queryWrapper.eq(TContractorDailyPlanInspect.STATUS, queryParam.getStatus());
		} else {
			queryWrapper.ne(TContractorDailyPlanInspect.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(TContractorDailyPlanInspect.UPDATE_DATE);
		}
		return queryWrapper;
	}
}
