package com.sw.mes.yb.check.controller;

import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.*;
import com.sw.mes.yb.check.dto.ExceptManageDto;
import com.sw.mes.yb.check.entity.ExceptManage;
import com.sw.mes.yb.check.service.ExceptManageService;
import com.sw.mes.yb.report.entity.CrystalPullingInfo;
import com.sw.mes.yb.report.entity.CrystalPullingInfoLog;
import com.sw.mes.yb.report.service.CrystalPullingInfoLogService;
import com.sw.mes.yb.report.service.CrystalPullingInfoService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/exceptManage")
@Slf4j
@Api(description = "单晶异常管理信息接口")
public class ExceptManageController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private ExceptManageService exceptManageService;

	@Autowired
	private DictionaryItemService dictionaryItemService;

	@Autowired
	private CrystalPullingInfoService crystalPullingInfoService;

	@Autowired
	private CrystalPullingInfoLogService crystalPullingInfoLogService;

	@ApiOperation(value = "分页查询单晶异常管理信息列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_deviceNo", value = "设备编号", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LIKE_lotNo", value = "炉次号", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_GTE_operateDate", value = "查询时间1", dataType = "string", paramType = "query"),
		@ApiImplicitParam(name = "search_LT_operateDate", value = "查询时间1", dataType = "string", paramType = "query")
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<ExceptManageDto>> listByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		Specification<ExceptManage> specification = DynamicSpecifications.bySearchFilter(request, ExceptManage.class);
    	Page<ExceptManage> page = exceptManageService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<ExceptManageDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		//查询更新掉实时信息
		refreshExceptManageByLotNo(dtos);
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有单晶异常管理信息")
	@GetMapping("/listAll")
	public Result<List<ExceptManageDto>> listAll(ServletRequest request) {
		Specification<ExceptManage> specification = DynamicSpecifications.bySearchFilter(request, ExceptManage.class);
		List<ExceptManage> exceptManages = exceptManageService.findByExampleSort(specification, null);
		List<ExceptManageDto> exceptManageDtos = exceptManages.stream()
					.map(exceptManage -> toLazyDto(exceptManage))
					.collect(Collectors.toList());
		return ResultGenerator.success(exceptManageDtos);
	}

	@ApiOperation(value = "单晶异常管理信息详细信息")
	@GetMapping("/{id}")
	public Result<ExceptManageDto> get(@PathVariable @ApiParam(value="单晶异常管理信息id") Long id) {
		ExceptManage exceptManage = exceptManageService.get(id);
		if (null == exceptManage)
			return ResultGenerator.fail("该单晶异常管理信息不存在");
		return ResultGenerator.success(toEagerDto(exceptManage));
	}

	@ApiOperation(value = "创建单晶异常管理信息")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "单晶异常管理信息对象") ExceptManageDto exceptManageDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		ExceptManage exceptManage = fromDto(exceptManageDto);
		exceptManage.setOperateDate(new Date());
		exceptManage.setUserName(BaseContextHandler.getUsername());
		exceptManage.setUserId(BaseContextHandler.getUserID().toString());
		exceptManageService.saveOrUpdate(exceptManage);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新单晶异常管理信息")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "单晶异常管理信息") ExceptManageDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            ExceptManage entity = exceptManageService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            ExceptManage entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			entity.setUpdateUser(BaseContextHandler.getUsername());
			entity.setUpdateTime(new Date());
			exceptManageService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

	@ApiOperation(value = "删除单晶异常管理信息")
	@PostMapping("/delete")
	public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
		for (Long id : ids) {
			exceptManageService.delete(id);
		}
		return ResultGenerator.success();
	}

	@ApiOperation(value = "异常类型")
	@GetMapping(value="/exceptionType")
	public Result exceptionType() {

		List<String> wasteTypes = dictionaryItemService.findValueByThemeValueAndEnable("异常类型",true);
		if(wasteTypes != null && wasteTypes.size() > 0) {
			return ResultGenerator.success(wasteTypes);
		}

		return ResultGenerator.success();
	}

	@ApiOperation(value = "根据炉次号查询实时数据")
	@GetMapping(value="/findInfoRealTime")
	public Result findInfo(@ApiParam(value = "炉次号", type = "query") @RequestParam String lotNo) {
		ExceptManage exceptManage = new ExceptManage();
		if (StringUtils.isNotBlank(lotNo)){
			exceptManage.setLotNo(lotNo);
			exceptManage = initInfo(exceptManage);
		}
		return ResultGenerator.success(exceptManage);
	}

	/**
	 * 数据导入
	 *
	 * @param file
	 */
	@ApiOperation(value = "导入")
	@PostMapping("/import")
	public Result importGrade(MultipartFile file) {
		try {
			 exceptManageService.readInfoImport(file);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}



	/**
	 * @Description: 查询时更新炉次当前实时情况
	 * @Param: [exceptManages]
	 * @return: void
	 * @Author: zhangliangzheng
	 * @Date: 2022/1/12 9:05
	 */
	private void refreshExceptManageByLotNo(List<ExceptManageDto> exceptManages){
		if (CollectionUtils.isEmpty(exceptManages)){
			return;
		}
		for (ExceptManageDto exceptManageDto : exceptManages){
			ExceptManage exceptManage = exceptManageService.get(exceptManageDto.getId());
			if (null != exceptManage.getRecordStatus() && exceptManage.getRecordStatus() == 2){
				continue;
			}
			exceptManage = initInfo(exceptManage);
			exceptManageService.saveOrUpdate(exceptManage);
			exceptManageDto = toLazyDto(exceptManage);
		}
	}

	public ExceptManage initInfo(ExceptManage exceptManage){
		String lotNo = exceptManage.getLotNo();
		//先查询记录表中是否存在
		if (StringUtils.isNotBlank(lotNo)){
			CrystalPullingInfoLog crystalPullingInfoLog = crystalPullingInfoLogService.getCrystalPullingInfoLogByLotNo(lotNo);
			if (null != crystalPullingInfoLog){
				if (null != crystalPullingInfoLog.getStartTime() && null != crystalPullingInfoLog.getStopTime()){
					exceptManage.setResidualWeight(BigDecimal.valueOf(0));
					exceptManage.setRunTime(BigDecimal.valueOf(DateUtil.hourBetween(crystalPullingInfoLog.getStartTime(), crystalPullingInfoLog.getStopTime())).setScale(2, BigDecimal.ROUND_HALF_UP));
				}
				exceptManage.setCrystalInfo(crystalPullingInfoLog.getInfo());
				//在拉晶情况信息记录中存在表示已停炉
				exceptManage.setRecordStatus(2);
			}else {
				CrystalPullingInfo crystalInfo = crystalPullingInfoService.getCrystalPullingInfoByLotNo(lotNo);
				if (null != crystalInfo){
					exceptManage.setResidualWeight(crystalInfo.getResidualWeight());
					if (null != crystalInfo.getStartTime()){
						exceptManage.setRunTime(BigDecimal.valueOf(DateUtil.hourBetween(crystalInfo.getStartTime(), new Date())).setScale(2, BigDecimal.ROUND_HALF_UP));
					}
					exceptManage.setCrystalInfo(crystalInfo.getInfo());
				}
			}
		}
		return exceptManage;
	}

	public ExceptManageDto toLazyDto(ExceptManage entity) {
		return modelMapper.map(entity, ExceptManageDto.class);
	}

	public ExceptManageDto toEagerDto(ExceptManage entity) {
		ExceptManageDto dto = modelMapper.map(entity, ExceptManageDto.class);
		return dto;
	}

	public ExceptManage fromDto(ExceptManageDto dto) {
		return modelMapper.map(dto, ExceptManage.class);
	}


}
