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

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.testor.biz.sys.dict.data.model.domain.SysDictData;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.common.excel.ExcelResult;
import com.testor.common.util.BeanConverUtil;
import com.testor.common.util.excel.EasyExcelUtil;
import com.testor.module.contractor.ledger.model.domain.*;
import com.testor.module.contractor.ledger.model.dto.TContractorPersonDto;
import com.testor.module.contractor.ledger.model.dto.TContractorProjectParam;
import com.testor.module.contractor.ledger.model.template.PersonTemplate;
import com.testor.module.contractor.ledger.model.template.ProjectTemplate;
import com.testor.module.contractor.ledger.service.TContractorInfoService;
import com.testor.module.contractor.ledger.service.TContractorPersonCertificateService;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.model.dto.NewTreeVo;
import com.testor.module.sys.service.NewSysDictDataService;
import com.testor.module.sys.service.NewSysOrgService;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
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.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.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;

import com.testor.module.contractor.ledger.model.dto.TContractorPersonParam;
import com.testor.module.contractor.ledger.model.dto.TContractorPersonDelParam;
import com.testor.module.contractor.ledger.service.TContractorPersonService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 承包商管理人员台账Controller
 *
 * @author testor-framework
 * @date 2024-11-20 09:58:38
 */
@RestController
@RequestMapping("/contractor/person")
@Api(value = "TContractorPerson", tags = "承包商管理人员台账")
@Slf4j
public class TContractorPersonController extends SuperController
{
    @Autowired
    private TContractorPersonService tContractorPersonService;

	@Autowired
	private NewSysDictDataService newSysDictDataService;

	@Autowired
	private TContractorInfoService tContractorInfoService;

	@Autowired
	private TContractorPersonCertificateService tContractorPersonCertificateService;

    /* Generated Method*/
	@ApiOperation(value = "新增 承包商管理人员台账", notes = "Add TContractorPerson")
	@PostMapping(value = "/add")
	public BaseResponse<TContractorPerson>addEntity(@RequestBody TContractorPersonDto addRequest) {
		BaseResponse<TContractorPerson> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			TContractorPerson tContractorPerson = tContractorPersonService.addEntity(addRequest);
			baseResponse.setData(tContractorPerson);
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理人员台账 ", notes = "Get TContractorPerson By Id")
	@GetMapping(value = "/get")
	public BaseResponse<TContractorPersonDto> getById(String id){
		BaseResponse<TContractorPersonDto> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
            TContractorPerson data= tContractorPersonService.getById(id);
			data.setAge((long) IdcardUtil.getAgeByIdCard(data.getIdCardNo()));
			TContractorPersonDto tContractorPersonDto = BeanConverUtil.conver(data, TContractorPersonDto.class);
			/*TContractorInfo tContractorInfo = tContractorInfoService.getById(tContractorPersonDto.getInfoId());
			if (tContractorInfo != null) {
				tContractorPersonDto.setInfoName(tContractorInfo.getName());
			}*/
			tContractorPersonDto.setInfoName(tContractorInfoService.getName(tContractorPersonDto.getInfoId()));
			List<TContractorPersonCertificate> tContractorPersonCertificates = tContractorPersonCertificateService.list(new LambdaQueryWrapper<TContractorPersonCertificate>().eq(TContractorPersonCertificate::getPersonId, id));
			tContractorPersonDto.setTContractorPersonCertificates(tContractorPersonCertificates);
			baseResponse.setData(tContractorPersonDto);
		}
		return baseResponse;
	}

	@ApiOperation(value = "修改 承包商管理人员台账 ", notes = "Update TContractorPerson By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TContractorPersonDto updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常

			boolean result= tContractorPersonService.updateEntity(updateRequest);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

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

	@ApiOperation(value = "下载导入模板", notes = "下载导入模板")
	@GetMapping(value = "/download-template")
	public void downloadTemplate(HttpServletResponse response) {
		tContractorPersonService.downloadTemplate(response);
	}

	@ApiOperation(value = "导入模板", notes = "导入模板")
	@PostMapping(value = "/import-template")
	public BaseResponse<BizGeneralResponse>  importTemplate(@RequestParam("file") MultipartFile file) throws IOException {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		tContractorPersonService.importTemplate(file);
		baseResponse.setMsg("导入成功");
		return baseResponse;
	}

	@ApiOperation(value = "exportPersonLedger", notes = "导出人员台账")
	@GetMapping(value = "/exportPersonLedger")
	public void exportProjectLedger(HttpServletResponse response, TContractorPersonParam param) {
		BaseResponse<BaseResponseList<TContractorPerson>> baseResponseListBaseResponse = listAllEntity(param);
		List<TContractorPerson> data = baseResponseListBaseResponse.getData().getData();

		List<PersonTemplate> templates = BeanConverUtil.converList(data, PersonTemplate.class);
		for (PersonTemplate template : templates) {
			SysDictData jobTitle = newSysDictDataService.getDictTypeDetail(template.getJobTitleId(), null, null);
			if (jobTitle != null) {
				template.setJobTitleName(jobTitle.getDictValue());
			}
			SysDictData jobNature = newSysDictDataService.getDictTypeDetail(template.getJobNatureId(), null, null);
			if (jobNature != null) {
				template.setJobNatureName(jobNature.getDictValue());
			}
			TContractorInfo infoByName = tContractorInfoService.getById(template.getInfoId());
			if (infoByName != null) {
				template.setInfoId(infoByName.getName());
			}

		}
		EasyExcelUtil.writeExcelBySelect(response, "人员台账", "人员台账", templates);
	}

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

	@ApiOperation(value = "获取 承包商管理人员台账 分页列表", notes = "List TContractorPerson with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<TContractorPerson>>listEntity(TContractorPersonParam param){
		BaseResponse<BaseResponseList<TContractorPerson>>baseResponse=new BaseResponse<>();

		Page<TContractorPerson> resultList= tContractorPersonService.listEntity(param);
		List<TContractorPerson> records = resultList.getRecords();
		for (TContractorPerson record : records) {
			record.setAge((long) IdcardUtil.getAgeByIdCard(record.getIdCardNo()));
		}
		BaseResponseList<TContractorPerson> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理人员台账 列表", notes = "List TContractorPerson all")
	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<TContractorPerson>>listAllEntity(TContractorPersonParam param){
		BaseResponse<BaseResponseList<TContractorPerson>>baseResponse=new BaseResponse<>();
		// TODO 根据需求修改查询条件及查询参数
		List<TContractorPerson> resultList=tContractorPersonService.listAllEntity(param);
		BaseResponseList<TContractorPerson> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "获取 承包商管理人员台账 列表", notes = "List TContractorPerson all")
	@GetMapping(value = "/validPeopleList")
	public  BaseResponse<BaseResponseList<TContractorPerson>>ValidPeopleList(TContractorPersonParam param){
		BaseResponse<BaseResponseList<TContractorPerson>>baseResponse=new BaseResponse<>();
		// TODO 根据需求修改查询条件及查询参数
		List<TContractorPerson> resultList=tContractorPersonService.ValidPeopleList(param);
		BaseResponseList<TContractorPerson> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}


	@ApiOperation("获取用户树")
	@GetMapping("/getTreeUser")
	public BaseResponse<NewTreeVo> getTreeUser(String orgId){
		BaseResponse<NewTreeVo> baseResponse = new BaseResponse<>();
		NewTreeVo newTreeVo =	tContractorPersonService.getTreeUser(orgId);
		baseResponse.setData(newTreeVo);
		return baseResponse;
	}

}
