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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.module.contractor.common.model.constant.ContractorProcessStatus;
import com.testor.module.contractor.ledger.model.domain.TContractorProject;
import com.testor.module.contractor.ledger.service.TContractorProjectService;
import com.testor.module.contractor.manage.model.domain.TContractorConditionReview;
import com.testor.module.contractor.manage.model.dto.ContractorConditionReviewDto;
import com.testor.module.contractor.manage.model.dto.TContractorConditionReviewDelParam;
import com.testor.module.contractor.manage.model.dto.TContractorConditionReviewParam;
import com.testor.module.contractor.manage.service.TContractorConditionReviewService;
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.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 com.tongtech.tfw.workflow.apis.definition.controller.ProcessDefinitionController;
import com.tongtech.tfw.workflow.apis.task.controller.WfTaskController;
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 java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 承包商管理-条件审查Controller
 *
 * @author testor-framework
 * @date 2024-11-26 10:39:58
 */
@RestController
@RequestMapping("/contractorManage/conditionReview")
@Api(value = "TContractorConditionReview", tags = "承包商管理-条件审查")
@Slf4j
public class TContractorConditionReviewController extends SuperController
{
    @Autowired
    private TContractorConditionReviewService tContractorConditionReviewService;

	@Autowired
	private NewSysOrgService newSysOrgService;

	@Autowired
	private ProcessDefinitionController processDefinitionController;

	@Autowired
	private WfTaskController wfTaskController;

	@Autowired
	private TContractorProjectService tContractorProjectService;

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

	@ApiOperation(value = "获取 承包商管理-条件审查 ", notes = "Get TContractorConditionReview By Id")
	@GetMapping(value = "/get")
	public BaseResponse<TContractorConditionReview> getById(String id){
		BaseResponse<TContractorConditionReview> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
            TContractorConditionReview data= tContractorConditionReviewService.getById(id);
			if(null !=data){
				if(data.getProjId() != null) {
					List<TContractorProject> contractorProject = tContractorProjectService.list(new LambdaQueryWrapper<TContractorProject>()
							.eq(TContractorProject::getId, data.getProjId()));
					if (contractorProject != null && !contractorProject.isEmpty()) {
						// 使用Stream API提取项目名称并用逗号拼接
						String projectNames = contractorProject.stream()
								.map(TContractorProject::getName) // 假设TContractorProject有getName方法
								.filter(StringUtils::isNotBlank) // 过滤掉空值
								.collect(Collectors.joining(",")); // 用逗号拼接

						// 将拼接后的项目名称设置到DTO中
						data.setTcontractorProjectName(projectNames);
					}
				}
			}

			baseResponse.setData(data);
		}
		return baseResponse;
	}

	@ApiOperation(value = "修改 承包商管理-条件审查 ", notes = "Update TContractorConditionReview By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorConditionReviewParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			boolean result= tContractorConditionReviewService.updateEntity(updateRequest);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

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

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


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

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

	@ApiOperation(value = "获取 承包商管理-条件审查 分页列表", notes = "List TContractorConditionReview with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<ContractorConditionReviewDto>>listEntity(TContractorConditionReviewParam param){
		BaseResponse<BaseResponseList<ContractorConditionReviewDto>>baseResponse=new BaseResponse<>();
		Page<ContractorConditionReviewDto> resultList= tContractorConditionReviewService.pageList(param);
		BaseResponseList<ContractorConditionReviewDto> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理-条件审查 列表", notes = "List TContractorConditionReview all")
	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<TContractorConditionReview>>listAllEntity(TContractorConditionReviewParam param){
		BaseResponse<BaseResponseList<TContractorConditionReview>>baseResponse=new BaseResponse<>();
		// TODO 根据需求修改查询条件及查询参数
		QueryWrapper<TContractorConditionReview> queryWrapper=this.createQuery(param);
		List<TContractorConditionReview> resultList=tContractorConditionReviewService.list(queryWrapper);
		BaseResponseList<TContractorConditionReview> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

    /* Private Methods */
	/**
     * 列表查询条件及查询参数
     */
	private QueryWrapper<TContractorConditionReview> createQuery(TContractorConditionReviewParam queryParam){
		QueryWrapper<TContractorConditionReview> queryWrapper=new QueryWrapper<>();
		UserInfo loginUser = ContextUtils.getLoginUser();
		String orgId = loginUser.getOrgId();
		List<String> idsChildrenById = newSysOrgService.getIdsChildrenById(orgId);
		//查询下级机构id
		queryWrapper.in("org_id", idsChildrenById);
		if(StringHelper.isNotEmpty(queryParam.getContractorId())){
			queryWrapper.eq(TContractorConditionReview.CONTRACTOR_ID,queryParam.getContractorId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProjId())){
			queryWrapper.eq(TContractorConditionReview.PROJ_ID,queryParam.getProjId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessId())){
			queryWrapper.eq(TContractorConditionReview.PROCESS_ID,queryParam.getProcessId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessStatus())){
			queryWrapper.eq(TContractorConditionReview.PROCESS_STATUS,queryParam.getProcessStatus());
		}
		if(StringHelper.isNotEmpty(queryParam.getBizId())){
			queryWrapper.eq(TContractorConditionReview.BIZ_ID,queryParam.getBizId());
		}
		if(StringHelper.isNotEmpty(queryParam.getOrgId())){
			queryWrapper.eq(TContractorConditionReview.ORG_ID,queryParam.getOrgId());
		}
		if (StringHelper.isNotEmpty(queryParam.getStatus())) {
			queryWrapper.eq(TContractorConditionReview.STATUS, queryParam.getStatus());
		} else {
			queryWrapper.ne(TContractorConditionReview.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(TContractorConditionReview.UPDATE_DATE);
		}
		return queryWrapper;
	}
}
