package com.testor.module.safeCheck.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.testor.biz.sys.dict.data.model.domain.SysDictData;
import com.testor.biz.sys.dict.data.service.SysDictDataService;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.module.safeCheck.model.domain.TSafeCheckOrg;
import com.testor.module.safeCheck.model.domain.TSafeCheckPerson;
import com.testor.module.safeCheck.model.domain.TSafeCheckPersonArrange;
import com.testor.module.safeCheck.model.dto.TSafeCheckOrgParam;
import com.testor.module.safeCheck.model.para.TSafeCheckPlanPara;
import com.testor.module.safeCheck.service.TSafeCheckOrgService;
import com.testor.module.safeCheck.service.TSafeCheckPersonArrangeService;
import com.testor.module.safeCheck.service.TSafeCheckPersonService;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.service.NewSysOrgService;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
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.safeCheck.model.domain.TSafeCheckPlan;
import com.testor.module.safeCheck.model.dto.TSafeCheckPlanParam;
import com.testor.module.safeCheck.model.dto.TSafeCheckPlanDelParam;
import com.testor.module.safeCheck.service.TSafeCheckPlanService;

/**
 * 安全检查计划Controller
 *
 * @author testor-framework
 * @date 2024-09-03 08:04:18
 */
@RestController
@RequestMapping("/safeCheck/plan")
@Api(value = "TSafeCheckPlan", tags = "安全检查计划")
@Slf4j
public class TSafeCheckPlanController extends SuperController
{
    @Autowired
    private TSafeCheckPlanService tSafeCheckPlanService;

	@Autowired
	private TSafeCheckOrgService tSafeCheckOrgService;

	@Autowired
	private NewSysOrgService sysOrgService;

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysDictDataService sysDictDataService;

	@Autowired
	private TSafeCheckPersonService tSafeCheckPersonService;

	@Autowired
	private TSafeCheckPersonArrangeService tSafeCheckPersonArrangeService;

    /* Generated Method*/
	@ApiOperation(value = "新增 安全检查计划", notes = "Add TSafeCheckPlan")
	@PostMapping(value = "/add")
	public BaseResponse<TSafeCheckPlan>addEntity(@RequestBody TSafeCheckPlanPara addRequest) {
		BaseResponse<TSafeCheckPlan> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
			String id = IdHelper.getId32bit();
            TSafeCheckPlan data=BeanHelper.beanToBean(addRequest,  TSafeCheckPlan.class);
            data.setStartDate(DateUtil.date(addRequest.getStartDate()));
			data.setEndDate(DateUtil.date(addRequest.getEndDate()));
			data.setId(id);
			boolean result= tSafeCheckPlanService.add(data);
			if(result){
                TSafeCheckPlan newEntity = new TSafeCheckPlan();
				newEntity.setId(id);
				baseResponse.setData(newEntity);
			}
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 安全检查计划 ", notes = "Get TSafeCheckPlan By Id")
	@GetMapping(value = "/get")
	public BaseResponse<TSafeCheckPlan> getById(String id){
		BaseResponse<TSafeCheckPlan> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
            TSafeCheckPlan data= tSafeCheckPlanService.getById(id);
			List<TSafeCheckPerson> listByPlanId = tSafeCheckPersonService.getListByPlanId(data.getId());
			listByPlanId = listByPlanId.stream().peek(tSafeCheckPerson -> {
				List<String> userNames = new ArrayList<>();
				List<TSafeCheckPersonArrange> tSafeCheckPersonArranges = tSafeCheckPersonArrangeService.list(new LambdaQueryWrapper<TSafeCheckPersonArrange>().eq(TSafeCheckPersonArrange::getCheckPersonId, tSafeCheckPerson.getId()));
				tSafeCheckPersonArranges = tSafeCheckPersonArranges.stream().peek(tSafeCheckPersonArrange -> {
					String userId = tSafeCheckPersonArrange.getUserId();
					SysUser sysUser = sysUserService.getById(userId);
					if (sysUser != null){
						String userName = sysUser.getUserName();
						tSafeCheckPersonArrange.setUserName(userName);
						userNames.add(userName);
					}
				}).collect(Collectors.toList());
				tSafeCheckPerson.setTSafeCheckPersonArranges(tSafeCheckPersonArranges);
				tSafeCheckPerson.setPeopleName(String.join(",", userNames));
				SysDictData byId = sysDictDataService.getById(tSafeCheckPerson.getCheckType());
				if (byId != null){
					tSafeCheckPerson.setCheckTypeName(byId.getDictValue());
				}
            }).collect(Collectors.toList());

			data.setTSafeCheckPersonList(listByPlanId);
			List<TSafeCheckOrg> listByPlanId1 = tSafeCheckOrgService.getListByPlanId(data.getId());
			listByPlanId1 = listByPlanId1.stream().peek(tSafeCheckOrg -> {
				NewSysOrg byId = sysOrgService.getById(tSafeCheckOrg.getCheckOrgId());
				if (byId != null) {
					tSafeCheckOrg.setCheckOrgName(byId.getOrgName());
					tSafeCheckOrg.setTreeLevel(byId.getTreeLevel());
					tSafeCheckOrg.setNature(byId.getNature());
				}
            }).collect(Collectors.toList());
			data.setTSafeCheckOrgs(listByPlanId1);
			baseResponse.setData(data);
		}
		return baseResponse;
	}

	@ApiOperation(value = "修改 安全检查计划 ", notes = "Update TSafeCheckPlan By Id")
	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TSafeCheckPlanPara updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
            TSafeCheckPlan data=BeanHelper.beanToBean(updateRequest, TSafeCheckPlan.class);
			data.setStartDate(DateUtil.date(updateRequest.getStartDate()));
			data.setEndDate(DateUtil.date(updateRequest.getEndDate()));
			boolean update = tSafeCheckPlanService.update(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(update)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "复制 安全检查计划 ", notes = "Update TSafeCheckPlan By Id")
	@PutMapping(value = "/copyPlan")
	public BaseResponse<BizGeneralResponse> copyPlan(@RequestBody TSafeCheckPlan updateRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			boolean result= tSafeCheckPlanService.copyPlan(updateRequest);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;

	}

	@ApiOperation(value = "删除 安全检查计划 ", notes = "delete TSafeCheckPlan By Id")
	@PutMapping(value = "/delete")
	public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TSafeCheckPlanDelParam deleteRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(deleteRequest)&&StringHelper.isNotEmpty(deleteRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            TSafeCheckPlan data= new TSafeCheckPlan();
			data.setId(deleteRequest.getId());
			data.setStatus(BizConstants.STATUS_DELETE);
			boolean update = tSafeCheckPlanService.update(data);
			tSafeCheckPlanService.delCheckOrgAndPerson(data.getId());
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(update)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "批量删除安全检查计划", notes = "delete TSafeCheckPlan by batch Id")
	@PutMapping(value = "/batch_delete")
	public BaseResponse<BizGeneralResponse> deleteEntityBatch(
			@RequestBody TSafeCheckPlanDelParam deleteRequest) {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
			List<TSafeCheckPlan> tSafeCheckPlanList = new ArrayList<>();
            for(String id: deleteRequest.getIds()){
                TSafeCheckPlan data= new TSafeCheckPlan();
				data.setId(id);
				data.setStatus(BizConstants.STATUS_DELETE);
                tSafeCheckPlanList.add(data);
				//删除被检查机构和检查人信息
				tSafeCheckPlanService.delCheckOrgAndPerson(data.getId());
			}
			boolean result = tSafeCheckPlanService.updateBatchById(tSafeCheckPlanList);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 安全检查计划 分页列表", notes = "List TSafeCheckPlan with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<TSafeCheckPlan>>listEntity(TSafeCheckPlanParam param){
		BaseResponse<BaseResponseList<TSafeCheckPlan>>baseResponse=new BaseResponse<>();
		Page<TSafeCheckPlan> resultList= tSafeCheckPlanService.pageList(param);
		BaseResponseList<TSafeCheckPlan> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "获取 安全检查计划 列表", notes = "List TSafeCheckPlan all")
	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<TSafeCheckPlan>>listAllEntity(TSafeCheckPlanParam param){
		BaseResponse<BaseResponseList<TSafeCheckPlan>>baseResponse=new BaseResponse<>();
		List<TSafeCheckPlan> resultList=tSafeCheckPlanService.findList(param);
		BaseResponseList<TSafeCheckPlan> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

    /* Private Methods */
	/**
     * 列表查询条件及查询参数
     */
	private QueryWrapper<TSafeCheckPlan> createQuery(TSafeCheckPlanParam queryParam){
		QueryWrapper<TSafeCheckPlan> queryWrapper=new QueryWrapper<>();
		if(StringHelper.isNotEmpty(queryParam.getOrgId())){
			queryWrapper.eq(TSafeCheckPlan.ORG_ID,queryParam.getOrgId());
		}
		//如果计划状态不为空
		if(StringHelper.isNotEmpty(queryParam.getPlanStatus())){
			Date now = new Date();
			//未开始
			if (queryParam.getPlanStatus().equals("0")){
				queryWrapper.gt(TSafeCheckPlan.START_DATE, now);
			//进行中
			}else if (queryParam.getPlanStatus().equals("1")){
				queryWrapper.le(TSafeCheckPlan.START_DATE, now)
						.ge(TSafeCheckPlan.START_DATE, now);
			//未开始
			}else if (queryParam.getPlanStatus().equals("2")){
				queryWrapper.lt(TSafeCheckPlan.START_DATE, now);
			}
		}
		if(StringHelper.isNotEmpty(queryParam.getName())){
			queryWrapper.like(TSafeCheckPlan.NAME,queryParam.getName());
		}
		if(ObjectHelper.isNotEmpty(queryParam.getStartDate())){
			queryWrapper.ge(TSafeCheckPlan.START_DATE,queryParam.getStartDate());
		}
		if(ObjectHelper.isNotEmpty(queryParam.getEndDate())){
			queryWrapper.le(TSafeCheckPlan.END_DATE,queryParam.getEndDate());
		}
		if(StringHelper.isNotEmpty(queryParam.getInWeekend())){
			queryWrapper.eq(TSafeCheckPlan.IN_WEEKEND,queryParam.getInWeekend());
		}
		if(StringHelper.isNotEmpty(queryParam.getInHoliday())){
			queryWrapper.eq(TSafeCheckPlan.IN_HOLIDAY,queryParam.getInHoliday());
		}
		if(ObjectHelper.isNotEmpty(queryParam.getAdvanceHour())){
			queryWrapper.eq(TSafeCheckPlan.ADVANCE_HOUR,queryParam.getAdvanceHour());
		}
		if (StringHelper.isNotEmpty(queryParam.getStatus())) {
			queryWrapper.eq(TSafeCheckPlan.STATUS, queryParam.getStatus());
		} else {
			queryWrapper.ne(TSafeCheckPlan.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(TSafeCheckPlan.UPDATE_DATE);
		}
		return queryWrapper;
	}
}
