package com.testor.module.production.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
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.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;

import com.testor.module.production.model.domain.TProductionAccident;
import com.testor.module.production.model.dto.TProductionAccidentParam;
import com.testor.module.production.model.dto.TProductionAccidentDelParam;
import com.testor.module.production.service.TProductionAccidentService;

/**
 * 安全生产事故配置Controller
 *
 * @author testor-framework
 * @date 2022-11-17 11:37:56
 */
@RestController
@RequestMapping("/production")
@Api(value = "TProductionAccident", tags = "安全生产事故配置")
@Slf4j
public class TProductionAccidentController extends SuperController
{
    @Autowired
    private TProductionAccidentService tProductionAccidentService;

    @Autowired
	private SysOrgService sysOrgService;

    /* Generated Method*/
	@ApiOperation(value = "编辑 安全生产事故配置", notes = "Add TProductionAccident")
	@PostMapping(value = "/add")
	public BaseResponse<TProductionAccident>addEntity(@RequestBody TProductionAccident addRequest) throws BusinessException {
		BaseResponse<TProductionAccident> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.DAY_OF_MONTH,1);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String s = format.format(calendar.getTime());
			if (addRequest.getData().compareTo(s) > 0) {
				throw new BusinessException("日期不能超过"+s);
			}
			boolean result= tProductionAccidentService.saveOrUpdate(addRequest);
			if(result){
                TProductionAccident newEntity = new TProductionAccident();
				newEntity.setId(addRequest.getId());
				baseResponse.setData(newEntity);
			}
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取首页连续无生产事故天数 安全生产事故配置 ", notes = "Get TProductionAccident By Id")
	@GetMapping(value = "/getHomeProduction")
	public BaseResponse<Integer> getHomeProduction(String orgId){
		BaseResponse<Integer> baseResponse = new BaseResponse<>();
		if (StringHelper.isEmpty(orgId)) {
			orgId = ContextUtils.getLoginUser().getOrgId();
		}
		// 获取当前企业及下属企业
		List<String> list = new ArrayList<>();
		sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID,orgId)
			.ne(SysOrg.STATUS,BizConstants.STATUS_DELETE)
				.eq(SysOrg.IS_DEPT,"0").select(SysOrg.ORG_ID)
				.ne(SysOrg.STATUS,BizConstants.STATUS_DELETE)
				.or()
				.eq(SysOrg.ORG_ID,orgId)
		).forEach(item->{
			list.add(item.getOrgId());
		});
		int days = 0 ;
		if (ObjectHelper.isNotEmpty(list)) {
			List<TProductionAccident> accidents = tProductionAccidentService.list(new QueryWrapper<TProductionAccident>()
					.in(TProductionAccident.ORG_ID, list)
			);
			if (accidents.size() > 0) {
				List<TProductionAccident> collect = accidents.stream()
						.sorted(Comparator.comparing(TProductionAccident::getData).reversed()).collect(Collectors.toList());
				TProductionAccident accident = collect.get(0);
				// 权限范围内的最大日期
				String startDate = accident.getData();
				// 当前日期
				String endDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
				days = differentDaysByString(startDate, endDate);
				if (days < 0) {
					days = 0 ;
				}
			}
		}
		Integer integer = Integer.valueOf(days);
		baseResponse.setData(integer);
		return baseResponse;
	}

	/**
	 *
	 * @param startDate  开始日期
	 * @param endDate    结束日期
	 * @return 返回相差的天数
	 */
	public static int differentDaysByString(String startDate, String endDate) {
		int days = 0;
		try {
			days = (int) ((Objects.requireNonNull(parseDate(endDate)).getTime() - Objects.requireNonNull(parseDate(startDate)).getTime()) / (1000 * 3600 * 24));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return days;
	}

	/**
	 * 日期格式转换
	 * @param date 日期
	 * @return 日期格式
	 */
	public static Date parseDate(String date) throws ParseException {
		if (date.isEmpty()) {
			return null;
		}
		return new SimpleDateFormat("yyyy-MM-dd").parse(date);
	}


	@ApiOperation(value = "重置 安全生产事故配置 ", notes = "Get TProductionAccident By Id")
	@GetMapping(value = "/reset")
	public BaseResponse<TProductionAccident> reset(String orgId){
		BaseResponse<TProductionAccident> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(orgId)){
			TProductionAccident accident = tProductionAccidentService.getById(orgId);
			String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
			accident.setData(currentTime);
            tProductionAccidentService.saveOrUpdate(accident);
			baseResponse.setData(accident);
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 安全生产事故配置 分页列表", notes = "List TProductionAccident with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<TProductionAccident>>listEntity(TProductionAccidentParam param){
		BaseResponse<BaseResponseList<TProductionAccident>>baseResponse=new BaseResponse<>();
		UserInfo loginUser = ContextUtils.getLoginUser();
		SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
		String parentIds = sysOrg.getParentIds();
		String orgId = sysOrg.getOrgId();
		List<String> companyIds = param.getCompanyIds();
		IPage<TProductionAccident> resultList = tProductionAccidentService.getList(param, parentIds, orgId,companyIds);
		BaseResponseList<TProductionAccident> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

//	@ApiOperation(value = "修改 安全生产事故配置 ", notes = "Update TProductionAccident By Id")
//	@PutMapping(value = "/update")
	public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TProductionAccident updateRequest) throws BusinessException {
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.DAY_OF_MONTH,1);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String s = format.format(calendar.getTime());
			if (updateRequest.getData().compareTo(s) > 0) {
				throw new BusinessException("日期不能超过"+s);
			}
			TProductionAccident data=BeanHelper.beanToBean(updateRequest, TProductionAccident.class);
			boolean result= tProductionAccidentService.saveOrUpdate(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

//	@ApiOperation(value = "删除 安全生产事故配置 ", notes = "delete TProductionAccident By Id")
//	@PutMapping(value = "/delete")
	public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody TProductionAccidentDelParam deleteRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(deleteRequest)&&StringHelper.isNotEmpty(deleteRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            TProductionAccident data= new TProductionAccident();
			data.setId(deleteRequest.getId());
			data.setStatus(BizConstants.STATUS_DELETE);
			boolean result= tProductionAccidentService.updateById(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

//	@ApiOperation(value = "批量删除安全生产事故配置", notes = "delete TProductionAccident by batch Id")
//	@PutMapping(value = "/batch_delete")
	public BaseResponse<BizGeneralResponse> deleteEntityBatch(
			@RequestBody TProductionAccidentDelParam deleteRequest) {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
			List<TProductionAccident> tProductionAccidentList = new ArrayList<>();
            for(String id: deleteRequest.getIds()){
                TProductionAccident data= new TProductionAccident();
				data.setId(id);
				data.setStatus(BizConstants.STATUS_DELETE);
                tProductionAccidentList.add(data);
			}
			boolean result = tProductionAccidentService.updateBatchById(tProductionAccidentList);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}


//	@ApiOperation(value = "获取 安全生产事故配置 列表", notes = "List TProductionAccident all")
//	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<TProductionAccident>>listAllEntity(TProductionAccidentParam param){
		BaseResponse<BaseResponseList<TProductionAccident>>baseResponse=new BaseResponse<>();
		// TODO 根据需求修改查询条件及查询参数
		QueryWrapper<TProductionAccident> queryWrapper=this.createQuery(param);
		List<TProductionAccident> resultList=tProductionAccidentService.list(queryWrapper);
		BaseResponseList<TProductionAccident> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

    /* Private Methods */
	/**
     * 列表查询条件及查询参数
     */
	private QueryWrapper<TProductionAccident> createQuery(TProductionAccidentParam queryParam){
		QueryWrapper<TProductionAccident> queryWrapper=new QueryWrapper<>();
		if(StringHelper.isNotEmpty(queryParam.getOrgName())){
			queryWrapper.like(TProductionAccident.ORG_NAME,queryParam.getOrgName());
		}
		if(ObjectHelper.isNotEmpty(queryParam.getData())){
			queryWrapper.eq(TProductionAccident.DATA,queryParam.getData());
		}
		if (StringHelper.isNotEmpty(queryParam.getStatus())) {
			queryWrapper.eq(TProductionAccident.STATUS, queryParam.getStatus());
		} else {
			queryWrapper.ne(TProductionAccident.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(TProductionAccident.UPDATE_DATE);
		}
		return queryWrapper;
	}
}
