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

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.testor.common.constant.StatusEnum;
import com.testor.common.core.domain.R;
import com.testor.common.util.BeanConverUtil;
import com.testor.module.contractor.ledger.model.domain.*;
import com.testor.module.contractor.ledger.model.dto.TContractorMaterialParam;
import com.testor.module.contractor.ledger.model.dto.TContractorPersonParam;
import com.testor.module.contractor.ledger.model.dto.TContractorProtectiveEquipmentParam;
import com.testor.module.contractor.ledger.model.dto.TContractorToolsParam;
import com.testor.module.contractor.ledger.service.*;
import com.testor.module.contractor.manage.model.domain.TContractorAllowPerson;
import com.testor.module.contractor.manage.model.dto.*;
import com.testor.module.contractor.manage.service.*;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
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.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.TContractorAllow;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * 准入管理Controller
 *
 * @author testor-framework
 * @date 2024-11-26 14:07:35
 */
@RestController
@RequestMapping("/allow/allow")
@Api(value = "TContractorAllow", tags = "准入管理")
@Slf4j
public class TContractorAllowController extends SuperController
{
    @Autowired
    private TContractorAllowService tContractorAllowService;
	@Autowired
	private TContractorAllowPersonService tContractorAllowPersonService;
	@Autowired
	private TContractorAllowMaterialService tContractorAllowMaterialService;
    @Autowired
	private TContractorAllowProtectiveService tContractorAllowProtectiveService;
	@Autowired
	private TContractorAllowToolsService tContractorAllowToolsService;
	@Autowired
	private TContractorMaterialService tContractorMaterialService;
	@Autowired
	private TContractorPersonService tContractorPersonService;
	@Autowired
	private TContractorProtectiveEquipmentService tContractorProtectiveEquipmentService;
	@Autowired
	private TContractorToolsService tContractorToolsService;

	@Autowired
	private TContractorProjectService tContractorProjectService;

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

	@ApiOperation(value = "获取 准入管理 ", notes = "Get TContractorAllow By Id")
	@GetMapping(value = "/getByIds")
	public BaseResponse<TContractorAllowDTO> getByIds(@RequestParam String projId,@RequestParam String contractorId,@RequestParam String bizId){
		TContractorAllow tContractorAllow = tContractorAllowService.getOne(new QueryWrapper<TContractorAllow>().eq("proj_id", projId).eq("contractor_id", contractorId).eq("biz_id", bizId).ne("status", StatusEnum.DELETE.getCode()));
		if (tContractorAllow != null) {
			BaseResponse<TContractorAllowDTO> byId = getById(tContractorAllow.getId());
			return byId;
		}
		return new BaseResponse<>();
	}

	@ApiOperation(value = "获取 准入管理 ", notes = "Get TContractorAllow By Id")
	@GetMapping(value = "/get")
	public BaseResponse<TContractorAllowDTO> getById(@RequestParam String id){
		BaseResponse<TContractorAllowDTO> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
            TContractorAllow tContractorAllow= tContractorAllowService.getById(id);
			TContractorAllowDTO tContractorAllowDTO = BeanConverUtil.conver(tContractorAllow, TContractorAllowDTO.class);
			//存入人员
			List<String> personIdsByAllowId = tContractorAllowPersonService.getIdsByAllowId(id);
			if (personIdsByAllowId != null && personIdsByAllowId.size() > 0) {
				TContractorPersonParam tContractorPersonParam = new TContractorPersonParam();
				tContractorPersonParam.setIds(personIdsByAllowId);
				tContractorPersonParam.setTypeQuery("1");
				List<TContractorPerson> tContractorPeople = tContractorPersonService.listAllEntity(tContractorPersonParam);
				tContractorAllowDTO.setPersonList(tContractorPeople);
				tContractorAllowDTO.setPersonIds(personIdsByAllowId);
			}
			//存入材料
			List<String> materialIdsByAllowId = tContractorAllowMaterialService.getIdsByAllowId(id);
			if (materialIdsByAllowId != null && materialIdsByAllowId.size() > 0) {
				TContractorMaterialParam tContractorMaterialParam = new TContractorMaterialParam();
				tContractorMaterialParam.setIds(materialIdsByAllowId);
				tContractorMaterialParam.setTypeQuery("1");
				List<TContractorMaterial> tContractorMaterialList = tContractorMaterialService.listAllEntity(tContractorMaterialParam);
				tContractorAllowDTO.setMaterialList(tContractorMaterialList);
				tContractorAllowDTO.setMaterialIds(materialIdsByAllowId);
			}
			//存入防护用品
			List<String> protectiveIdsByAllowId = tContractorAllowProtectiveService.getIdsByAllowId(id);
			if (protectiveIdsByAllowId != null && protectiveIdsByAllowId.size() > 0) {
				TContractorProtectiveEquipmentParam tContractorProtectiveEquipmentParam = new TContractorProtectiveEquipmentParam();
				tContractorProtectiveEquipmentParam.setIds(protectiveIdsByAllowId);
				tContractorProtectiveEquipmentParam.setTypeQuery("1");
				List<TContractorProtectiveEquipment> tContractorProtectiveEquipmentList = tContractorProtectiveEquipmentService.listAllEntity(tContractorProtectiveEquipmentParam);
				tContractorAllowDTO.setTContractorProtectiveEquipments(tContractorProtectiveEquipmentList);
				tContractorAllowDTO.setProtectiveIds(protectiveIdsByAllowId);
			}
			//存入工具
			List<String> toolIdsByAllowId = tContractorAllowToolsService.getIdsByAllowId(id);
			if (toolIdsByAllowId != null && toolIdsByAllowId.size() > 0) {
				TContractorToolsParam tContractorToolsParam = new TContractorToolsParam();
				tContractorToolsParam.setIds(toolIdsByAllowId);
				tContractorToolsParam.setTypeQuery("1");
				List<TContractorTools> tContractorToolsList = tContractorToolsService.listAllEntity(tContractorToolsParam);
				tContractorAllowDTO.setTContractorTools(tContractorToolsList);
				tContractorAllowDTO.setToolsIds(toolIdsByAllowId);
			}

			if(null != tContractorAllowDTO){
				if(tContractorAllowDTO.getProjId() != null) {
					List<TContractorProject> contractorProject = tContractorProjectService.list(new LambdaQueryWrapper<TContractorProject>()
							.eq(TContractorProject::getId, tContractorAllowDTO.getProjId()));
					if (contractorProject != null && !contractorProject.isEmpty()) {
						// 使用Stream API提取项目名称并用逗号拼接
						String projectNames = contractorProject.stream()
								.map(TContractorProject::getName) // 假设TContractorProject有getName方法
								.filter(StringUtils::isNotBlank) // 过滤掉空值
								.collect(Collectors.joining(",")); // 用逗号拼接

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


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

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

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

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

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

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

	@ApiOperation(value = "获取 准入管理 分页列表", notes = "List TContractorAllow with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<TContractorAllowDTO>>listEntity(TContractorAllowParam param){
		BaseResponse<BaseResponseList<TContractorAllowDTO>>baseResponse=new BaseResponse<>();
		String orgId = ContextUtils.getLoginUser().getOrgId();
		param.setOrgId(orgId);
		param.setCreateBy(getUserId());
		Page<TContractorAllowDTO> resultList= tContractorAllowService.pageList(param);
		BaseResponseList<TContractorAllowDTO> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}


	@ApiOperation("删除准入管理数据并回退基本信息状态")
	@GetMapping("/deleteAdmission")
	public BaseResponse deleteAdmission(@RequestParam String id) throws BusinessException {
		tContractorAllowService.deleteAdmissionAndRollback(
				id);
		return BaseResponse.success();
	}

}
