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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.common.constant.StatusEnum;
import com.testor.common.util.BeanConverUtil;
import com.testor.module.contractor.common.model.constant.ContractorProcessStatus;
import com.testor.module.contractor.ledger.dao.TContractorLedgerDao;
import com.testor.module.contractor.ledger.model.domain.TContractorProject;
import com.testor.module.contractor.ledger.model.dto.TContractorLedgerDto;
import com.testor.module.contractor.ledger.service.TContractorLedgerService;
import com.testor.module.contractor.ledger.service.TContractorProjectService;
import com.testor.module.contractor.manage.model.domain.TContractorSafetyBrief;
import com.testor.module.contractor.manage.model.domain.TContractorSafetyBriefDetail;
import com.testor.module.contractor.manage.model.dto.*;
import com.testor.module.contractor.manage.service.TContractorSafetyBriefDetailService;
import com.testor.module.contractor.manage.service.TContractorSafetyBriefService;
import com.testor.module.sys.service.NewSysOrgService;
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.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 承包商管理-安全交底Controller
 *
 * @author testor-framework
 * @date 2024-11-28 11:51:46
 */
@RestController
@RequestMapping("/contractorManage/safetyBrief")
@Api(value = "TContractorSafetyBrief", tags = "承包商管理-安全交底")
@Slf4j
public class TContractorSafetyBriefController extends SuperController
{
    @Autowired
    private TContractorSafetyBriefService tContractorSafetyBriefService;

	@Autowired
	private TContractorSafetyBriefDetailService tContractorSafetyBriefDetailService;

	@Autowired
	private NewSysOrgService newSysOrgService;

	@Autowired
	private TContractorLedgerService tContractorLedgerService;
	@Autowired
	private TContractorProjectService tContractorProjectService;

	@Resource
	private TContractorLedgerDao contractorLedgerDao;

    /* Generated Method*/
	@ApiOperation(value = "新增 承包商管理-安全交底", notes = "Add TContractorSafetyBrief")
	@PostMapping(value = "/add")
	public BaseResponse<TContractorSafetyBrief>addEntity(@RequestBody TContractorSafetyBrief addRequest) {
		BaseResponse<TContractorSafetyBrief> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
			String id = IdHelper.getId32bit();
            TContractorSafetyBrief data=BeanHelper.beanToBean(addRequest,  TContractorSafetyBrief.class);
			data.setId(id);
			boolean result= tContractorSafetyBriefService.save(data);
			if(result){
                TContractorSafetyBrief newEntity = new TContractorSafetyBrief();
				newEntity.setId(id);
				baseResponse.setData(newEntity);
			}
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理-安全交底 ", notes = "Get TContractorSafetyBrief By Id")
	@GetMapping(value = "/get")
	public BaseResponse<ContractorSafetyBriefDto> getById(String id){
		BaseResponse<ContractorSafetyBriefDto> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
			ContractorSafetyBriefDto dto = tContractorSafetyBriefService.getEntityById(id);
            baseResponse.setData(dto);
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理-安全交底 ", notes = "Get TContractorSafetyBrief By Id")
	@GetMapping(value = "/getByIds")
	public BaseResponse<ContractorSafetyBriefDto> getByIds(@RequestParam String projId,@RequestParam String contractorId,@RequestParam String bizId){
		BaseResponse<ContractorSafetyBriefDto> baseResponse=new BaseResponse<>();
		TContractorSafetyBrief data =
				tContractorSafetyBriefService.getOne(new QueryWrapper<TContractorSafetyBrief>().eq("proj_id", projId).eq("contractor_id", contractorId).eq("biz_id", bizId).ne("status", StatusEnum.DELETE.getCode()).last("limit 1"),false);
		if(data != null) {
			ContractorSafetyBriefDto dto= BeanConverUtil.conver(data, ContractorSafetyBriefDto.class);
			List<TContractorSafetyBriefDetail> detailList =
					tContractorSafetyBriefDetailService.list(new QueryWrapper<TContractorSafetyBriefDetail>().eq(TContractorSafetyBriefDetail.BRIEF_ID, data.getId()).orderByAsc(TContractorSafetyBriefDetail.TREE_SORT));
			dto.setBriefDetailList(detailList);
			baseResponse.setData(dto);
		}
		return baseResponse;
	}

	@ApiOperation(value = "修改 承包商管理-安全交底 ", notes = "Update TContractorSafetyBrief By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorSafetyBriefParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			boolean result= tContractorSafetyBriefService.updateEntity(updateRequest);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "推送", notes = "推送任务")
	@PostMapping(value = "/push")
	@Transactional(rollbackFor = Exception.class)
	public BaseResponse<BizGeneralResponse> pushProcess(@RequestBody TContractorSafetyBriefParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// 调用tContractorConditionReviewService的updateEntity方法，推送安全交底任务进入待提交状态
			updateRequest.setProcessStatus(ContractorProcessStatus.PENDING_SUBMISSION.getValue());
			tContractorSafetyBriefService.updateEntity(updateRequest);
		}
		return baseResponse;
	}

	@ApiOperation(value = "提交", notes = "启动流程")
	@PostMapping(value = "/submit")
	@Transactional(rollbackFor = Exception.class)
	public BaseResponse<BizGeneralResponse> startProcess(@RequestBody TContractorSafetyBriefParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// 调用tContractorConditionReviewService的startProcess方法，启动流程
			tContractorSafetyBriefService.startProcess(updateRequest);
		}
		return baseResponse;
	}

	@ApiOperation(value = "完成流程", notes = "启动流程")
	@PostMapping(value = "/completeProcess")
	@Transactional(rollbackFor = Exception.class)
	public BaseResponse<BizGeneralResponse> completeProcess(@RequestBody TContractorSafetyBriefParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// 调用tContractorConditionReviewService的completeProcess方法,完成流程
			tContractorSafetyBriefService.completeProcess(updateRequest);
		}
		return baseResponse;
	}

	@ApiOperation(value = "删除 承包商管理-安全交底 ", notes = "delete TContractorSafetyBrief By Id")
	@PutMapping(value = "/delete")
	public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TContractorSafetyBriefDelParam deleteRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(deleteRequest)&&StringHelper.isNotEmpty(deleteRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorSafetyBrief data= new TContractorSafetyBrief();
			data.setId(deleteRequest.getId());
			data.setStatus(BizConstants.STATUS_DELETE);
			boolean result= tContractorSafetyBriefService.updateById(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "批量删除承包商管理-安全交底", notes = "delete TContractorSafetyBrief by batch Id")
	@PutMapping(value = "/batch_delete")
	public BaseResponse<BizGeneralResponse> deleteEntityBatch(
			@RequestBody TContractorSafetyBriefDelParam deleteRequest) {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
			List<TContractorSafetyBrief> tContractorSafetyBriefList = new ArrayList<>();
            for(String id: deleteRequest.getIds()){
                TContractorSafetyBrief data= new TContractorSafetyBrief();
				data.setId(id);
				data.setStatus(BizConstants.STATUS_DELETE);
                tContractorSafetyBriefList.add(data);
			}
			boolean result = tContractorSafetyBriefService.updateBatchById(tContractorSafetyBriefList);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理-安全交底 分页列表", notes = "List TContractorSafetyBrief with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<ContractorSafetyBriefDto>>listEntity(TContractorSafetyBriefParam param){
		BaseResponse<BaseResponseList<ContractorSafetyBriefDto>>baseResponse=new BaseResponse<>();
		Page<ContractorSafetyBriefDto> resultList= tContractorSafetyBriefService.pageList(param);
		BaseResponseList<ContractorSafetyBriefDto> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理-安全交底 列表", notes = "List TContractorSafetyBrief all")
	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<ContractorSafetyBriefDto>>listAllEntity(TContractorSafetyBriefParam param){
		BaseResponse<BaseResponseList<ContractorSafetyBriefDto>>baseResponse=new BaseResponse<>();
		// TODO 根据需求修改查询条件及查询参数
		QueryWrapper<TContractorSafetyBrief> queryWrapper=this.createQuery(param);
		List<TContractorSafetyBrief> resultList=tContractorSafetyBriefService.list(queryWrapper);
		List<ContractorSafetyBriefDto> dtoList=new ArrayList<>();
		for(TContractorSafetyBrief entity:resultList){
			ContractorSafetyBriefDto dto = BeanHelper.beanToBean(entity, ContractorSafetyBriefDto.class);
			TContractorLedgerDto  ledgerDto = tContractorLedgerService.getLedgerById(entity.getContractorId());
			dto.setContractorLedgerDto(ledgerDto);
			if(ledgerDto != null && ledgerDto.getTContractorInfo() !=  null) {
				dto.setContractorName(ledgerDto.getTContractorInfo().getName());
			}

			TContractorProject project = tContractorProjectService.getById(entity.getProjId());
			if(project != null) {
				dto.setProjectName(project.getName());
			}
			dtoList.add(dto);
		}
		BaseResponseList<ContractorSafetyBriefDto> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(dtoList);
		baseResponseList.setTotal(dtoList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理-安全交底 内容确认合信息", notes = "List TContractorSafetyBrief content confirm info")
    @GetMapping(value = "/getBriefContentConfirmInfo")
    public  BaseResponse<ContractorSafetyBriefContentDto>getBriefContentConfirmInfo(TContractorSafetyBriefDetailParam param){
        BaseResponse<ContractorSafetyBriefContentDto>baseResponse=new BaseResponse<>();
        if(ObjectHelper.isEmpty(param) || StringHelper.isEmpty(param.getBriefId()) || StringHelper.isEmpty(param.getContractorId())
				|| StringHelper.isEmpty(param.getProjId())){
			baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
			baseResponse.setMsg("安全交底id、承包商id、项目id不能为空");
            return baseResponse;
		}
		ContractorSafetyBriefContentDto dto = tContractorSafetyBriefService.getSafetyBriefContent(param);
		baseResponse.setData(dto);
        return baseResponse;
    }


    /* Private Methods */
	/**
     * 列表查询条件及查询参数
     */
	private QueryWrapper<TContractorSafetyBrief> createQuery(TContractorSafetyBriefParam queryParam){
		QueryWrapper<TContractorSafetyBrief> queryWrapper=new QueryWrapper<>();
		UserInfo loginUser = ContextUtils.getLoginUser();
		String orgId = loginUser.getOrgId();
		//List<String> idsChildrenById = newSysOrgService.getIdsChildrenById(orgId);
		List<String> idsChildrenById = new ArrayList<>();
		//idsChildrenById.addAll(Arrays.asList(contractorLedgerDao.orgIdDistinct(orgId).split(",")));
		String orgIdDistinct = contractorLedgerDao.orgIdDistinct(orgId);
		if (orgIdDistinct != null && !orgIdDistinct.trim().isEmpty()) {
			idsChildrenById.addAll(Arrays.asList(orgIdDistinct.split(",")));
		}
		log.info("承包商人员台账列表--ids1------>ids值:{}",idsChildrenById);
		idsChildrenById.addAll(newSysOrgService.getIdsChildrenById(orgId));
		log.info("承包商人员台账列表--ids2------>ids值:{}",idsChildrenById);
		//查询下级机构id
		//queryWrapper.in("org_id", idsChildrenById);
		String inIds = idsChildrenById.stream()
				.map(id -> "'" + id + "'")
				.collect(Collectors.joining(","));

		queryWrapper.apply(
				"string_to_array(org_id, ',') && ARRAY[" + inIds + "]"
		);


		if(StringHelper.isNotEmpty(queryParam.getContractorId())){
			queryWrapper.eq(TContractorSafetyBrief.CONTRACTOR_ID,queryParam.getContractorId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProjId())){
			queryWrapper.eq(TContractorSafetyBrief.PROJ_ID,queryParam.getProjId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessId())){
			queryWrapper.eq(TContractorSafetyBrief.PROCESS_ID,queryParam.getProcessId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessStatus())){
			queryWrapper.eq(TContractorSafetyBrief.PROCESS_STATUS,queryParam.getProcessStatus());
		}
		if(StringHelper.isNotEmpty(queryParam.getBizId())){
			queryWrapper.eq(TContractorSafetyBrief.BIZ_ID,queryParam.getBizId());
		}
		if(StringHelper.isNotEmpty(queryParam.getOrgId())){
			queryWrapper.eq(TContractorSafetyBrief.ORG_ID,queryParam.getOrgId());
		}
		if(ObjectHelper.isNotEmpty(queryParam.getBriefDate())){
			queryWrapper.eq(TContractorSafetyBrief.BRIEF_DATE,queryParam.getBriefDate());
		}
		if(StringHelper.isNotEmpty(queryParam.getBriefLocation())){
			queryWrapper.eq(TContractorSafetyBrief.BRIEF_LOCATION,queryParam.getBriefLocation());
		}
		if(StringHelper.isNotEmpty(queryParam.getBriefBy())){
			queryWrapper.eq(TContractorSafetyBrief.BRIEF_BY,queryParam.getBriefBy());
		}
		if(StringHelper.isNotEmpty(queryParam.getSignature())){
			queryWrapper.eq(TContractorSafetyBrief.SIGNATURE,queryParam.getSignature());
		}
		if(StringHelper.isNotEmpty(queryParam.getSitePhoto())){
			queryWrapper.eq(TContractorSafetyBrief.SITE_PHOTO,queryParam.getSitePhoto());
		}
		if (StringHelper.isNotEmpty(queryParam.getStatus())) {
			queryWrapper.eq(TContractorSafetyBrief.STATUS, queryParam.getStatus());
		} else {
			queryWrapper.ne(TContractorSafetyBrief.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(TContractorSafetyBrief.UPDATE_DATE);
		}
		return queryWrapper;
	}
}
