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.util.BeanConverUtil;
import com.testor.module.contractor.common.model.constant.ContractorProcessStatus;
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.TContractorBlacklist;
import com.testor.module.contractor.manage.model.domain.TContractorEvaluate;
import com.testor.module.contractor.manage.model.dto.ContractorBlacklistDto;
import com.testor.module.contractor.manage.model.dto.TContractorBlacklistDelParam;
import com.testor.module.contractor.manage.model.dto.TContractorBlacklistParam;
import com.testor.module.contractor.manage.service.TContractorBlacklistService;
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-12-01 11:15:44
 */
@RestController
@RequestMapping("/contractorManage/blacklist")
@Api(value = "TContractorBlacklist", tags = "承包商管理-考核评价-黑名单")
@Slf4j
public class TContractorBlacklistController extends SuperController
{
    @Autowired
    private TContractorBlacklistService tContractorBlacklistService;

	@Autowired
	private TContractorLedgerService tContractorLedgerService;

	@Autowired
	private TContractorProjectService tContractorProjectService;

    /* Generated Method*/
	@ApiOperation(value = "新增 承包商管理-考核评价-黑名单", notes = "Add TContractorBlacklist")
	@PostMapping(value = "/add")
	public BaseResponse<TContractorBlacklist>addEntity(@RequestBody TContractorBlacklist addRequest) {
		BaseResponse<TContractorBlacklist> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
			String id = IdHelper.getId32bit();
            TContractorBlacklist data=BeanHelper.beanToBean(addRequest,  TContractorBlacklist.class);
			data.setId(id);
			data.setProcessStatus(ContractorProcessStatus.PENDING_SUBMISSION.getValue());
			TContractorBlacklist history =
					tContractorBlacklistService.getByContractorId(addRequest.getContractorId());
			if(history != null){
				baseResponse.setCode(500);
				baseResponse.setMsg("该承包商已经在黑名单中，请勿重复添加");
				return baseResponse;
			}
			boolean result= tContractorBlacklistService.save(data);
			if(result){
                TContractorBlacklist newEntity = new TContractorBlacklist();
				newEntity.setId(id);
				baseResponse.setData(newEntity);
			}
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理-考核评价-黑名单 ", notes = "Get TContractorBlacklist By Id")
	@GetMapping(value = "/get")
	public BaseResponse<ContractorBlacklistDto> getById(String id){
		BaseResponse<ContractorBlacklistDto> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
            TContractorBlacklist data= tContractorBlacklistService.getById(id);
			ContractorBlacklistDto dto = BeanConverUtil.conver(data, ContractorBlacklistDto.class);
			if(data != null){
				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());
                }
			}
			baseResponse.setData(dto);
		}
		return baseResponse;
	}

	@ApiOperation(value = "修改 承包商管理-考核评价-黑名单 ", notes = "Update TContractorBlacklist By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorBlacklist updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            TContractorBlacklist data=BeanHelper.beanToBean(updateRequest, TContractorBlacklist.class);
			boolean result= tContractorBlacklistService.updateById(data);
			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 TContractorBlacklistParam 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())){
			TContractorBlacklist history =
					tContractorBlacklistService.getByContractorId(updateRequest.getContractorId());
			if(history != null){
				baseResponse.setCode(500);
				baseResponse.setMsg("该承包商已经在黑名单中，请勿重复添加");
				return baseResponse;
			}
		}
		tContractorBlacklistService.startProcess(updateRequest);
		return baseResponse;
	}

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

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

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

	@ApiOperation(value = "获取 承包商管理-考核评价-黑名单 分页列表", notes = "List TContractorBlacklist with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<ContractorBlacklistDto>>listEntity(TContractorBlacklistParam param){
		BaseResponse<BaseResponseList<ContractorBlacklistDto>>baseResponse=new BaseResponse<>();
		Page<ContractorBlacklistDto> resultList= tContractorBlacklistService.pageList(param);
		BaseResponseList<ContractorBlacklistDto> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

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

    /* Private Methods */
	/**
     * 列表查询条件及查询参数
     */
	private QueryWrapper<TContractorBlacklist> createQuery(TContractorBlacklistParam queryParam){
		QueryWrapper<TContractorBlacklist> queryWrapper=new QueryWrapper<>();
		if(StringHelper.isNotEmpty(queryParam.getContractorId())){
			queryWrapper.eq(TContractorBlacklist.CONTRACTOR_ID,queryParam.getContractorId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProjId())){
			queryWrapper.eq(TContractorBlacklist.PROJ_ID,queryParam.getProjId());
		}
		if(StringHelper.isNotEmpty(queryParam.getEvaluateId())){
			queryWrapper.eq(TContractorBlacklist.EVALUATE_ID,queryParam.getEvaluateId());
		}
		if(StringHelper.isNotEmpty(queryParam.getBizId())){
			queryWrapper.eq(TContractorBlacklist.BIZ_ID,queryParam.getBizId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessId())){
			queryWrapper.eq(TContractorBlacklist.PROCESS_ID,queryParam.getProcessId());
		}
		if(StringHelper.isNotEmpty(queryParam.getProcessStatus())){
			queryWrapper.eq(TContractorBlacklist.PROCESS_STATUS,queryParam.getProcessStatus());
		}
		if(StringHelper.isNotEmpty(queryParam.getViolationReasonId())){
			queryWrapper.eq(TContractorBlacklist.VIOLATION_REASON_ID,queryParam.getViolationReasonId());
		}
		if(StringHelper.isNotEmpty(queryParam.getViolationReason())){
			queryWrapper.eq(TContractorBlacklist.VIOLATION_REASON,queryParam.getViolationReason());
		}
		if(StringHelper.isNotEmpty(queryParam.getAccidentDesc())){
			queryWrapper.eq(TContractorBlacklist.ACCIDENT_DESC,queryParam.getAccidentDesc());
		}
		if(StringHelper.isNotEmpty(queryParam.getRejectOpinion())){
			queryWrapper.eq(TContractorBlacklist.REJECT_OPINION,queryParam.getRejectOpinion());
		}
		if(StringHelper.isNotEmpty(queryParam.getOrgId())){
			queryWrapper.eq(TContractorBlacklist.ORG_ID,queryParam.getOrgId());
		}
		if (StringHelper.isNotEmpty(queryParam.getStatus())) {
			queryWrapper.eq(TContractorBlacklist.STATUS, queryParam.getStatus());
		} else {
			queryWrapper.ne(TContractorBlacklist.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(TContractorBlacklist.UPDATE_DATE);
		}
		return queryWrapper;
	}
}
