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.extension.plugins.pagination.Page;
import com.testor.common.constant.StatusEnum;
import com.testor.common.core.enums.BaseStatusEnum;
import com.testor.common.core.utils.StringUtils;
import com.testor.common.model.UpdateProcessStatusReq;
import com.testor.module.contractor.enums.GeneralFlagEnum;
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.TContractorEvaluate;
import com.testor.module.contractor.manage.model.domain.TContractorEvaluateDetail;
import com.testor.module.contractor.manage.model.dto.ContractorEvaluateDto;
import com.testor.module.contractor.manage.model.dto.TContractorEvaluateDelParam;
import com.testor.module.contractor.manage.model.dto.TContractorEvaluateParam;
import com.testor.module.contractor.manage.service.TContractorEvaluateDetailService;
import com.testor.module.contractor.manage.service.TContractorEvaluateService;
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.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 java.util.ArrayList;
import java.util.List;

/**
 * 承包商考核评价Controller
 *
 * @author testor-framework
 * @date 2024-11-30 15:42:18
 */
@RestController
@RequestMapping("/contractorManage/evaluate")
@Api(value = "TContractorEvaluate", tags = "承包商考核评价")
@Slf4j
public class TContractorEvaluateController extends SuperController
{
    @Autowired
    private TContractorEvaluateService tContractorEvaluateService;

	@Autowired
	private TContractorEvaluateDetailService tContractorEvaluateDetailService;

	@Autowired
	private TContractorLedgerService tContractorLedgerService;

	@Autowired
	private TContractorProjectService tContractorProjectService;

    /* Generated Method*/
	@ApiOperation(value = "新增 承包商考核评价", notes = "Add TContractorEvaluate")
	@PostMapping(value = "/add")
	public BaseResponse<TContractorEvaluate>addEntity(@RequestBody TContractorEvaluateParam addRequest) {
		BaseResponse<TContractorEvaluate> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			TContractorEvaluate data =
					tContractorEvaluateService.getByContractorId(addRequest.getContractorId());

			if(data != null){
				baseResponse.setCode(500);
				baseResponse.setMsg("该承包商已经评价过了，请勿重新评价");
				return baseResponse;
			}
			TContractorLedgerDto  ledgerDto = tContractorLedgerService.getLedgerById(addRequest.getContractorId());
			if(ledgerDto != null && ledgerDto.getTContractorInfo() != null && GeneralFlagEnum.YES.getCode().equals(ledgerDto.getTContractorInfo().getIsBlacklist())) {
				baseResponse.setCode(500);
				baseResponse.setMsg("该承包商已经被列入黑名单，请勿评价");
				return baseResponse;
			}
			// TODO 按需求添加数据去重，特殊值设定，业务异常
			String id = IdHelper.getId32bit();
            data = tContractorEvaluateService.addEntity(addRequest);
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商考核评价 ", notes = "Get TContractorEvaluate By Id")
	@GetMapping(value = "/get")
	public BaseResponse<ContractorEvaluateDto> getById(String id){
		BaseResponse<ContractorEvaluateDto> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
            TContractorEvaluate data= tContractorEvaluateService.getById(id);
			List<TContractorEvaluateDetail> evaluateDetails =
					tContractorEvaluateDetailService.list(new QueryWrapper<TContractorEvaluateDetail>().eq(TContractorEvaluateDetail.EVALUATE_ID,id).orderByAsc(TContractorEvaluateDetail.INDEX_CODE));
			ContractorEvaluateDto dto = BeanHelper.beanToBean(data, ContractorEvaluateDto.class);
			TContractorLedgerDto ledgerDto = tContractorLedgerService.getLedgerById(data.getContractorId());
			if(ledgerDto != null && ledgerDto.getTContractorInfo() != null) {
				dto.setContractorName(ledgerDto.getTContractorInfo().getName());
			}
			TContractorProject project = tContractorProjectService.getById(data.getProjId());
			if(project != null) {
				dto.setProjectName(project.getName());
			}
			dto.setEvaluateDetails(evaluateDetails);
			baseResponse.setData(dto);
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商考核评价 ", notes = "Get TContractorEvaluate By projId,contractorId,bizId")
	@GetMapping(value = "/getIds")
	public BaseResponse<ContractorEvaluateDto> getByIds(@RequestParam String projId,@RequestParam String contractorId,@RequestParam String bizId){
		BaseResponse<ContractorEvaluateDto> baseResponse=new BaseResponse<>();
		// TODO 按需求添加业务异常判断
		TContractorEvaluate data= tContractorEvaluateService.getOne(new QueryWrapper<TContractorEvaluate>().eq(
				"proj_id", projId).eq("contractor_id", contractorId).eq("biz_id", bizId).ne("status",
				StatusEnum.DELETE.getCode()).last("limit 1"),false);
		ContractorEvaluateDto dto = BeanHelper.beanToBean(data, ContractorEvaluateDto.class);
		if(data != null) {
			List<TContractorEvaluateDetail> evaluateDetails =
					tContractorEvaluateDetailService.list(new QueryWrapper<TContractorEvaluateDetail>().eq(TContractorEvaluateDetail.EVALUATE_ID, data.getId()).orderByAsc(TContractorEvaluateDetail.INDEX_CODE));

			TContractorLedgerDto ledgerDto = tContractorLedgerService.getLedgerById(data.getContractorId());
			if (ledgerDto != null && ledgerDto.getTContractorInfo() != null) {
				dto.setContractorName(ledgerDto.getTContractorInfo().getName());
			}
			TContractorProject project = tContractorProjectService.getById(data.getProjId());
			if (project != null) {
				dto.setProjectName(project.getName());
			}
			dto.setEvaluateDetails(evaluateDetails);
		}
		baseResponse.setData(dto);
		return baseResponse;
	}



	@ApiOperation(value = "修改 承包商考核评价 ", notes = "Update TContractorEvaluate By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorEvaluateParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId()) && StringHelper.isNotEmpty(updateRequest.getEvaluateDetails())){
			boolean result= tContractorEvaluateService.updateEntity(updateRequest);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "更新流程状态", notes = "更新审批流程状态")
	@PostMapping(value = "/updateProcessStatus")
	public BaseResponse updateProcessStatus(@RequestBody UpdateProcessStatusReq updateProcessStatusReq) throws Exception {
		tContractorEvaluateService.updateProcessStatus(updateProcessStatusReq);
		return BaseResponse.success();
	}

	@ApiOperation(value = "提交", notes = "启动流程")
	@PostMapping(value = "/submit")
	@Transactional(rollbackFor = Exception.class)
	public BaseResponse<BizGeneralResponse> startProcess(@RequestBody TContractorEvaluateParam updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isEmpty(updateRequest)){
			baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
			baseResponse.setMsg(BaseStatusEnum.UN_DATA.msg());
			return baseResponse;
		}
		// 如果是新增页面提交，需要校验该承包商是否已经进行过评价，如果评价过，则返回提示信息
		if(StringUtils.isEmpty(updateRequest.getId())){
			TContractorEvaluate data =
					tContractorEvaluateService.getByContractorId(updateRequest.getContractorId());
			if(data != null){
				baseResponse.setCode(500);
				baseResponse.setMsg("该承包商已经评价过了，请勿重新评价");
				return baseResponse;
			}
			TContractorLedgerDto  ledgerDto = tContractorLedgerService.getLedgerById(updateRequest.getContractorId());
			if(ledgerDto != null && ledgerDto.getTContractorInfo() != null && GeneralFlagEnum.YES.getCode().equals(ledgerDto.getTContractorInfo().getIsBlacklist())) {
				baseResponse.setCode(500);
				baseResponse.setMsg("该承包商已经被列入黑名单，请勿评价");
				return baseResponse;
			}
		}
		tContractorEvaluateService.startProcess(updateRequest);
		return baseResponse;
	}

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

    @ApiOperation(value = "承包商考核评价-下一步", notes = "Submit TContractorEvaluate to next step")
    @PostMapping(value = "/nextStep")
    public BaseResponse<BizGeneralResponse> nextStep(@RequestBody TContractorEvaluateParam updateRequest){
        BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
        if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
            tContractorEvaluateService.nextStep(updateRequest);
        }
        return baseResponse;
    }


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

	@ApiOperation(value = "批量删除承包商考核评价", notes = "delete TContractorEvaluate by batch Id")
	@PutMapping(value = "/batch_delete")
	public BaseResponse<BizGeneralResponse> deleteEntityBatch(
			@RequestBody TContractorEvaluateDelParam deleteRequest) {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
			List<TContractorEvaluate> tContractorEvaluateList = new ArrayList<>();
            for(String id: deleteRequest.getIds()){
                TContractorEvaluate data= new TContractorEvaluate();
				data.setId(id);
				data.setStatus(BizConstants.STATUS_DELETE);
                tContractorEvaluateList.add(data);
			}
			boolean result = tContractorEvaluateService.updateBatchById(tContractorEvaluateList);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商考核评价 分页列表", notes = "List TContractorEvaluate with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<ContractorEvaluateDto>>listEntity(TContractorEvaluateParam param){
		BaseResponse<BaseResponseList<ContractorEvaluateDto>>baseResponse=new BaseResponse<>();
		Page<ContractorEvaluateDto> resultList = tContractorEvaluateService.pageList(param);
		BaseResponseList<ContractorEvaluateDto> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

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

    /* Private Methods */
	/**
     * 列表查询条件及查询参数
     */
	private QueryWrapper<TContractorEvaluate> createQuery(TContractorEvaluateParam queryParam){
		QueryWrapper<TContractorEvaluate> queryWrapper=new QueryWrapper<>();
		if(StringHelper.isNotEmpty(queryParam.getContractorId())){
			queryWrapper.eq(TContractorEvaluate.CONTRACTOR_ID,queryParam.getContractorId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProjId())){
			queryWrapper.eq(TContractorEvaluate.PROJ_ID,queryParam.getProjId());
		}
		if(StringHelper.isNotEmpty(queryParam.getBizId())){
			queryWrapper.eq(TContractorEvaluate.BIZ_ID,queryParam.getBizId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessId())){
			queryWrapper.eq(TContractorEvaluate.PROCESS_ID,queryParam.getProcessId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessStatus())){
			queryWrapper.eq(TContractorEvaluate.PROCESS_STATUS,queryParam.getProcessStatus());
		}
		if(StringHelper.isNotEmpty(queryParam.getEvaluationSheetTypeId())){
			queryWrapper.eq(TContractorEvaluate.EVALUATION_SHEET_TYPE_ID,queryParam.getEvaluationSheetTypeId());
		}
		if(StringHelper.isNotEmpty(queryParam.getEvaluationSheetType())){
			queryWrapper.eq(TContractorEvaluate.EVALUATION_SHEET_TYPE,queryParam.getEvaluationSheetType());
		}
		if(StringHelper.isNotEmpty(queryParam.getEvaluationSubjectId())){
			queryWrapper.eq(TContractorEvaluate.EVALUATION_SUBJECT_ID,queryParam.getEvaluationSubjectId());
		}
		if(StringHelper.isNotEmpty(queryParam.getEvaluationSubject())){
			queryWrapper.eq(TContractorEvaluate.EVALUATION_SUBJECT,queryParam.getEvaluationSubject());
		}
		if(StringHelper.isNotEmpty(queryParam.getEvaluationCycleId())){
			queryWrapper.eq(TContractorEvaluate.EVALUATION_CYCLE_ID,queryParam.getEvaluationCycleId());
		}
		if(StringHelper.isNotEmpty(queryParam.getEvaluationCycle())){
			queryWrapper.eq(TContractorEvaluate.EVALUATION_CYCLE,queryParam.getEvaluationCycle());
		}
		if(StringHelper.isNotEmpty(queryParam.getIfVeto())){
			queryWrapper.eq(TContractorEvaluate.IF_VETO,queryParam.getIfVeto());
		}
		if(ObjectHelper.isNotEmpty(queryParam.getScore())){
			queryWrapper.eq(TContractorEvaluate.SCORE,queryParam.getScore());
		}
		if(StringHelper.isNotEmpty(queryParam.getRejectOpinion())){
			queryWrapper.eq(TContractorEvaluate.REJECT_OPINION,queryParam.getRejectOpinion());
		}
		if(StringHelper.isNotEmpty(queryParam.getOrgId())){
			queryWrapper.eq(TContractorEvaluate.ORG_ID,queryParam.getOrgId());
		}
		if (StringHelper.isNotEmpty(queryParam.getStatus())) {
			queryWrapper.eq(TContractorEvaluate.STATUS, queryParam.getStatus());
		} else {
			queryWrapper.ne(TContractorEvaluate.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(TContractorEvaluate.UPDATE_DATE);
		}
		return queryWrapper;
	}
}
