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

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.testor.common.util.BeanConverUtil;
import com.testor.module.contractor.common.model.constant.ContractorProcessStatus;
import com.testor.module.contractor.common.service.TContractorLedgerProjectService;
import com.testor.module.contractor.enums.GeneralFlagEnum;
import com.testor.module.contractor.ledger.model.domain.TContractorInfo;
import com.testor.module.contractor.ledger.model.domain.TContractorLedger;
import com.testor.module.contractor.ledger.model.domain.TContractorProject;
import com.testor.module.contractor.ledger.model.dto.TContractorLedgerDto;
import com.testor.module.contractor.ledger.model.dto.TContractorProjectParam;
import com.testor.module.contractor.ledger.service.TContractorLedgerService;
import com.testor.module.contractor.ledger.service.TContractorProjectService;
import com.testor.module.contractor.manage.model.domain.TContractorAllow;
import com.testor.module.contractor.manage.model.dto.ContractorInfoDTO;
import com.testor.module.contractor.manage.model.dto.TContractorBasicInfoDto;
import com.testor.module.contractor.manage.service.TContractorAllowService;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.workflow.apis.definition.controller.ProcessDefinitionController;
import com.tongtech.tfw.workflow.apis.definition.model.dto.ProcessDefStartParam;
import com.tongtech.tfw.workflow.apis.task.controller.WfTaskController;
import com.tongtech.tfw.workflow.apis.task.model.dto.CompleteTask;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
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.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.exceptions.ApiException;
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.TContractorBasicInfo;
import com.testor.module.contractor.manage.model.dto.TContractorBasicInfoParam;
import com.testor.module.contractor.manage.model.dto.TContractorBasicInfoDelParam;
import com.testor.module.contractor.manage.service.TContractorBasicInfoService;

/**
 * 基本管理Controller
 *
 * @author testor-framework
 * @date 2024-11-22 21:03:04
 */
@RestController
@RequestMapping("/manage/basicInfo")
@Api(value = "TContractorBasicInfo", tags = "基本管理")
@Slf4j
public class TContractorBasicInfoController extends SuperController
{
    @Autowired
    private TContractorBasicInfoService tContractorBasicInfoService;

	@Autowired
	private TContractorLedgerService tContractorLedgerService;

	@Autowired
	private TContractorProjectService tContractorProjectService;

	@Autowired
	private TContractorLedgerProjectService tContractorLedgerProjectService;

    /* Generated Method*/
	@ApiOperation(value = "新增 基本管理", notes = "Add TContractorBasicInfo")
	@PostMapping(value = "/add")
	public BaseResponse<TContractorBasicInfo>addEntity(@RequestBody TContractorBasicInfoParam addRequest) {
		BaseResponse<TContractorBasicInfo> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isEmpty(addRequest)){
			return baseResponse;
		}
		// 判断承包商是否在黑名单中，在黑名单中不能新增
		TContractorLedgerDto ledgerDto =  tContractorLedgerService.getLedgerById(addRequest.getContractorId());
		if(ledgerDto != null){
			TContractorInfo contractorInfo = ledgerDto.getTContractorInfo();
			if(GeneralFlagEnum.YES.getCode().equals(contractorInfo.getIsBlacklist())){
				baseResponse.setCode(500);
				baseResponse.setMsg("该供应商已被列入黑名单，不能新增基本信息");
				return baseResponse;
			}
		}
		// TODO 按需求添加数据去重，特殊值设定，业务异常
		TContractorBasicInfo result= tContractorBasicInfoService.addEntity(addRequest);
		if(result != null){
			baseResponse.setData(result);
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 基本管理 ", notes = "Get TContractorBasicInfo By Id")
	@GetMapping(value = "/get")
	public BaseResponse<TContractorBasicInfoDto> getById(@RequestParam String id){
		BaseResponse<TContractorBasicInfoDto> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
			TContractorBasicInfo result= tContractorBasicInfoService.getById(id);
			if (result != null){
				TContractorBasicInfoDto  tContractorBasicInfoDto= BeanConverUtil.conver(result,
						TContractorBasicInfoDto.class);
				String contractorId = result.getContractorId();
				// 根据contractorId获取TContractorLedgerDto对象
				TContractorLedgerDto tContractorLedgerDto= tContractorLedgerService.getLedgerById(contractorId);
				// 根据result.getId()获取projIdsByBizId列表
				List<String> projIdsByBizId = tContractorLedgerProjectService.getProjIdsByBizId(result.getId());
				// 创建TContractorProjectParam对象
				TContractorProjectParam tContractorProjectParam = new TContractorProjectParam();
				// 设置TContractorProjectParam对象的ids属性为projIdsByBizId
				tContractorProjectParam.setIds(projIdsByBizId);
				// 设置TContractorProjectParam对象的typeQuery属性为"1"
				tContractorProjectParam.setTypeQuery("1");
				// 根据TContractorProjectParam对象获取TContractorProject列表
				List<TContractorProject> tContractorProjects = tContractorProjectService.listAllEntity(tContractorProjectParam);
				// 将TContractorProject列表设置到TContractorLedgerDto对象的TContractorProjects属性中
				tContractorLedgerDto.setTContractorProjects(tContractorProjects);

				tContractorBasicInfoDto.setContractorLedgerDto(tContractorLedgerDto);
				// 将TContractorLedgerDto对象设置到baseResponse的data属性中
				baseResponse.setData(tContractorBasicInfoDto);
			}

		}
		return baseResponse;
	}

	@ApiOperation(value = "修改 基本管理 ", notes = "Update TContractorBasicInfo By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorBasicInfoParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
			TContractorBasicInfo result= tContractorBasicInfoService.updateEntity(updateRequest);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "提交", notes = "启动流程")
	@PostMapping(value = "/submit")
	public BaseResponse<BizGeneralResponse> submit(@RequestBody TContractorBasicInfoParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			tContractorBasicInfoService.submit(updateRequest);
		}
		return baseResponse;
	}

	@ApiOperation(value = "完成流程", notes = "完成流程 通过/驳回")
	@PostMapping(value = "/completeProcess")
	public BaseResponse<BizGeneralResponse> completeProcess(@RequestBody TContractorBasicInfoParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			tContractorBasicInfoService.completeProcess(updateRequest);
		}
		return baseResponse;
	}



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

	@ApiOperation(value = "批量删除基本管理", notes = "delete TContractorBasicInfo by batch Id")
	@PutMapping(value = "/batch_delete")
	public BaseResponse<BizGeneralResponse> deleteEntityBatch(
			@RequestBody TContractorBasicInfoDelParam deleteRequest) {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
			List<TContractorBasicInfo> tContractorBasicInfoList = new ArrayList<>();
            for(String id: deleteRequest.getIds()){
                TContractorBasicInfo data= new TContractorBasicInfo();
				data.setId(id);
				data.setStatus(BizConstants.STATUS_DELETE);
                tContractorBasicInfoList.add(data);
			}
			boolean result = tContractorBasicInfoService.updateBatchById(tContractorBasicInfoList);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 基本管理 分页列表", notes = "List TContractorBasicInfo with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<ContractorInfoDTO>>listEntity(TContractorBasicInfoParam param){
		BaseResponse<BaseResponseList<ContractorInfoDTO>>baseResponse=new BaseResponse<>();
		param.setOrgId(ContextUtils.getLoginUser().getOrgId());
		Page<ContractorInfoDTO> resultList= tContractorBasicInfoService.pageList(param);
		BaseResponseList<ContractorInfoDTO> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

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

    /* Private Methods */
	/**
     * 列表查询条件及查询参数
     */
	private QueryWrapper<TContractorBasicInfo> createQuery(TContractorBasicInfoParam queryParam){
		QueryWrapper<TContractorBasicInfo> queryWrapper=new QueryWrapper<>();
		if(StringHelper.isNotEmpty(queryParam.getProcessId())){
			queryWrapper.eq(TContractorBasicInfo.PROCESS_ID,queryParam.getProcessId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessStatus())){
			queryWrapper.eq(TContractorBasicInfo.PROCESS_STATUS,queryParam.getProcessStatus());
		}
		if (StringHelper.isNotEmpty(queryParam.getStatus())) {
			queryWrapper.eq(TContractorBasicInfo.STATUS, queryParam.getStatus());
		} else {
			queryWrapper.ne(TContractorBasicInfo.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(TContractorBasicInfo.UPDATE_DATE);
		}
		return queryWrapper;
	}
}
