package com.sw.mes.kanban.controller;

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.BeanUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.kanban.dto.DailyProductionRecordDto;
import com.sw.mes.kanban.dto.TotalProductionDto;
import com.sw.mes.kanban.entity.DailyProductionRecord;
import com.sw.mes.kanban.service.DailyProductionRecordService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;



/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/DailyProductionRecord")
@Slf4j
@Api(description = "日产量记录表接口")
public class DailyProductionRecordController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private DailyProductionRecordService dailyProductionRecordService;

	@ApiOperation(value = "分页查询日产量记录表列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<DailyProductionRecordDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<DailyProductionRecord> specification = DynamicSpecifications.bySearchFilter(request, DailyProductionRecord.class);
    	Page<DailyProductionRecord> page = dailyProductionRecordService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<DailyProductionRecordDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

	@ApiOperation(value = "获取所有日产量记录表")
	@GetMapping("/listAll")
	public Result<List<DailyProductionRecordDto>> listAll(ServletRequest request) {
		Specification<DailyProductionRecord> specification = DynamicSpecifications.bySearchFilter(request, DailyProductionRecord.class);
		List<DailyProductionRecord> dailyProductionRecords = dailyProductionRecordService.findByExampleSort(specification, null);
		List<DailyProductionRecordDto> dailyProductionRecordDtos = dailyProductionRecords.stream()
					.map(dailyProductionRecord -> toLazyDto(dailyProductionRecord))
					.collect(Collectors.toList());
		return ResultGenerator.success(dailyProductionRecordDtos);
	}

	@ApiOperation(value = "日产量记录表详细信息")
	@GetMapping("/{id}")
	public Result<DailyProductionRecordDto> get(@PathVariable @ApiParam(value="日产量记录表id") Integer id) {
		DailyProductionRecord dailyProductionRecord = dailyProductionRecordService.get(id);
		if (null == dailyProductionRecord)
			return ResultGenerator.fail("该日产量记录表不存在");
		return ResultGenerator.success(toEagerDto(dailyProductionRecord));
	}

	@ApiOperation(value = "创建日产量记录表")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "日产量记录表对象") DailyProductionRecordDto dailyProductionRecordDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		DailyProductionRecord dailyProductionRecord = fromDto(dailyProductionRecordDto);
		dailyProductionRecordService.saveOrUpdate(dailyProductionRecord);
		return ResultGenerator.success();
	}

    @ApiOperation(value = "更新日产量记录表")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "日产量记录表") DailyProductionRecordDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors())
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        if (dto.getId() == null)
            return ResultGenerator.fail("id不能为空");
            DailyProductionRecord entity = dailyProductionRecordService.get(dto.getId());
        if (entity == null)
            return ResultGenerator.fail("原信息不存在");
        try {
            DailyProductionRecord entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			dailyProductionRecordService.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 Integer[] ids) {
		for (Integer id : ids) {
				dailyProductionRecordService.delete(id);
		}
		return ResultGenerator.success();
	}


	@ApiOperation(value = "插入时间范围内的产量")
	@GetMapping("/runDailyProductionRecord")
	public Result runDailyProductionRecord(@ApiParam(value = "开始时间") String startTime,@ApiParam(value = "结束时间")  String endTime) {
		try {
			dailyProductionRecordService.runDailyProductionRecord(startTime,endTime);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}


	/**
	 * 传入参数格式（2024-04-01 08:30:00", "2024-04-20 08:29:59"）
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@ApiOperation(value = "批量插入时间范围内的产量")
	@GetMapping("/runBatchDailyProductionRecord")
	public Result runBatchDailyProductionRecord(@ApiParam(value = "开始时间") String startTime,@ApiParam(value = "结束时间")  String endTime) {
		try {
			dailyProductionRecordService.runBatchDailyProductionRecord(startTime,endTime);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success();
	}


	@ApiOperation(value = "获取时间范围产量")
	@GetMapping("/findProductionByTime")
	public Result<List<TotalProductionDto>> findProductionByTime(@ApiParam(value = "开始时间")@RequestParam String startTime,@ApiParam(value = "结束时间")@RequestParam String endTime) {
		List<TotalProductionDto> dtos;
		try {
			 dtos = dailyProductionRecordService.findProductionByTime(startTime,endTime);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success(dtos);
	}


	@ApiOperation(value = "获取时间范围产量")
	@GetMapping("/findDaysProductionByTime")
	public Result<Map<String,List<Map>>> findDaysProductionByTime(@RequestParam String startTime,@RequestParam String endTime) {
		Map<String,List<Map>> list;
		try {
			list = dailyProductionRecordService.findDaysProductionByTime(startTime,endTime);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
		return ResultGenerator.success(list);
	}







	public DailyProductionRecordDto toLazyDto(DailyProductionRecord entity) {
		return modelMapper.map(entity, DailyProductionRecordDto.class);
	}

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

	public DailyProductionRecord fromDto(DailyProductionRecordDto dto) {
		return modelMapper.map(dto, DailyProductionRecord.class);
	}


}
