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

import com.alibaba.fastjson.JSON;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.entity.SearchFilter;
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.production.dto.AgainTaskDetail.AgainTaskDetailDto;
import com.sw.mes.yb.production.dto.AgainTaskDetail.TaskDetailExportDto;
import com.sw.mes.yb.production.dto.InputFurnaceBurden.InputFurnaceBurdenDto;
import com.sw.mes.yb.production.dto.InputFurnaceBurden.InputFurnaceBurdenExport;
import com.sw.mes.yb.production.dto.InputFurnaceBurden.InputFurnaceBurdenExportParam;
import com.sw.mes.yb.production.dto.InputFurnaceBurden.TaskFurnaceBurdenDto;
import com.sw.mes.yb.production.entity.AgainTaskDetail;
import com.sw.mes.yb.production.entity.InputFurnaceBurden;
import com.sw.mes.yb.production.service.AgainTaskDetailService;
import com.sw.mes.yb.production.service.InputFurnaceBurdenService;
import com.sw.mes.yb.production.service.LoadingTaskService;
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.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@RestController
@RequestMapping("/productionInputFurnaceBurden")
@Slf4j
@Api(description = "灌料记录接口")
public class InputFurnaceBurdenController {
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private InputFurnaceBurdenService inputFurnaceBurdenService;

	@Autowired
	private AgainTaskDetailService againTaskDetailService;

	@Autowired
	private LoadingTaskService loadingTaskService;

	@Autowired
	private DictionaryItemService dictionaryItemService;

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


	@ApiOperation(value = "分页查询灌料任务记录列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listTaskByPage")
	public Result<ResponsePage<TaskFurnaceBurdenDto>> listTaskByPage(ServletRequest request,@ApiIgnore RequestPage requestPage) {
		//罐料记录不显示新建、等待的状态的记录
		Collection<SearchFilter> searchFilters = new HashSet<>();
		searchFilters.add(new SearchFilter("rawStatus", SearchFilter.Operator.NOT, 0));
		searchFilters.add(new SearchFilter("rawStatus", SearchFilter.Operator.NOT, 6));
		searchFilters.add(new SearchFilter("rawStatus", SearchFilter.Operator.NOT, 7));
		Specification<AgainTaskDetail> specification = DynamicSpecifications.bySearchFilter(request, AgainTaskDetail.class, searchFilters);
    	Page<AgainTaskDetail> page = againTaskDetailService.findByExample(specification, PageUtil.createPageable(requestPage,new String[]{"startTime DESC"}));
		List<TaskFurnaceBurdenDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());

		for (TaskFurnaceBurdenDto taskFurnaceBurdenDto : dtos) {
			List<InputFurnaceBurden> logs = inputFurnaceBurdenService.findByAgainTaskDetailId(taskFurnaceBurdenDto.getId());
			List<InputFurnaceBurdenDto> logDtos = logs.stream()
	                .map(entity -> toLazyDto(entity))
	                .collect(Collectors.toList());
			taskFurnaceBurdenDto.setInputFurnaceBurdenDto(logDtos);
		}

		ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
	}

    @ApiOperation(value = "灌料任务导出")
	@GetMapping("/export")
    public void export(InputFurnaceBurdenExportParam param, HttpServletResponse response){
	    if (StringUtils.isBlank(param.getSearch_GTE_startTime()) || StringUtils.isBlank(param.getSearch_LTE_startTime())){
	        throw new RuntimeException("灌料时间不能空");
        }
		List<Map<String, Object>> mapList = againTaskDetailService.findTaskAndDetails(param);
		List<TaskDetailExportDto> list = mapList.stream()
				.map(item -> JSON.parseObject(JSON.toJSONString(item), TaskDetailExportDto.class))
				.collect(Collectors.toList());

		// 从线边仓补充物料信息
		// loadingTaskService.addMaterialInfoFromWarehouse(list);

		// 转换供应商编码
		for (TaskDetailExportDto dto : list) {
			DictionaryItem item = dictionaryItemService.findByThemeValueAndNameAndEnable("crucibleSupplier", dto.getFactoryBrand(), true);
			if (ObjectUtils.isEmpty(item)) continue;
			dto.setFactoryBrand(item.getValue());
		}

		try {
            EasyExcelUtils.write(response, TaskDetailExportDto.class, "灌料任务及明细", "灌料任务及明细", list);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


	@ApiOperation(value = "获取所有灌料记录")
	@GetMapping("/listAll")
	public Result<List<InputFurnaceBurdenDto>> listAll(ServletRequest request) {
		Specification<InputFurnaceBurden> specification = DynamicSpecifications.bySearchFilter(request, InputFurnaceBurden.class);
		List<InputFurnaceBurden> inputFurnaceBurdens = inputFurnaceBurdenService.findByExampleSort(specification, null);
		List<InputFurnaceBurdenDto> inputFurnaceBurdenDtos = inputFurnaceBurdens.stream()
					.map(inputFurnaceBurden -> toLazyDto(inputFurnaceBurden))
					.collect(Collectors.toList());
		return ResultGenerator.success(inputFurnaceBurdenDtos);
	}

	@ApiOperation(value = "灌料记录详细信息")
	@GetMapping("/{id}")
	public Result<InputFurnaceBurdenDto> get(@PathVariable @ApiParam(value="灌料记录id") Long id) {
		InputFurnaceBurden inputFurnaceBurden = inputFurnaceBurdenService.get(id);
		if (null == inputFurnaceBurden) {
            return ResultGenerator.fail("该灌料记录不存在");
        }
		return ResultGenerator.success(toEagerDto(inputFurnaceBurden));
	}

	@ApiOperation(value = "开始灌料")
	@PostMapping("/start")
	public Result start(@RequestBody @ApiParam(value = "灌料记录对象") InputFurnaceBurdenDto inputFurnaceBurdenDto) {
		try {
			inputFurnaceBurdenService.startInputFurnace(inputFurnaceBurdenDto);
			return ResultGenerator.success(new Date());
		}catch (Exception e) {
			e.printStackTrace();
			return ResultGenerator.fail(e.getMessage());
		}
	}


	@ApiOperation(value = "退出但不取消灌料")
	@PostMapping("/back")
	public Result back(@RequestBody @ApiParam(value = "灌料记录对象") InputFurnaceBurdenDto inputFurnaceBurdenDto) {
		try {
			inputFurnaceBurdenService.back(inputFurnaceBurdenDto);
			return ResultGenerator.success(new Date());
		}catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}


	@ApiOperation(value = "获取开始灌料操作信息")
	@PostMapping("/getStartInfo")
	public Result getStartInfo(@ApiParam(value = "桶任务记录Id(production_again_task_detail.id)") Long againTaskDetailId) {
		try {
			InputFurnaceBurdenDto inputFurnaceBurdenDto = inputFurnaceBurdenService.getStartInfo(againTaskDetailId);
			return ResultGenerator.success(inputFurnaceBurdenDto);
		}catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}



	@ApiOperation(value = "取消开始灌料操作")
	@PostMapping("/cancel")
	public Result cancel(@ApiParam(value = "桶任务记录Id(production_again_task_detail.id)") Long againTaskDetailId) {
		try {
			inputFurnaceBurdenService.cancelInputFurnace(againTaskDetailId);
			return ResultGenerator.success(new Date());
		}catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}


	@ApiOperation(value = "完成灌料")
	@PostMapping("/success")
	public Result success(@RequestBody @Valid @ApiParam(value = "灌料记录对象") InputFurnaceBurdenDto inputFurnaceBurdenDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}

		if(StringUtils.isBlank(inputFurnaceBurdenDto.getVehicleCode())) {
			return ResultGenerator.fail("请输入载具编号");
		}

		if(StringUtils.isBlank(inputFurnaceBurdenDto.getLeftCode())) {
			return ResultGenerator.fail("请输入左桶编号");
		}

		if(inputFurnaceBurdenDto.getPailNum()==2 && StringUtils.isBlank(inputFurnaceBurdenDto.getRightCode())) {
			return ResultGenerator.fail("请输入右桶编号");
		}

		if (CollectionUtils.isEmpty(inputFurnaceBurdenDto.getDetails())){
			return ResultGenerator.fail("投料明细不能为空");
		}

		try {
			inputFurnaceBurdenService.endInputFurnace(inputFurnaceBurdenDto, AgainTaskDetailDto.rawStatus_4, BaseContextHandler.getUsername());
			return ResultGenerator.success();
		}catch (Exception e) {
			return ResultGenerator.fail(e.getMessage());
		}
	}

    @ApiOperation(value = "更新灌料记录")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "灌料记录") InputFurnaceBurdenDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
            InputFurnaceBurden entity = inputFurnaceBurdenService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            InputFurnaceBurden entityfromFto = fromDto(dto);
			BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
			inputFurnaceBurdenService.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) {
				inputFurnaceBurdenService.delete(id);
		}
		return ResultGenerator.success();
	}

	public InputFurnaceBurdenDto toLazyDto(InputFurnaceBurden entity) {
		return modelMapper.map(entity, InputFurnaceBurdenDto.class);
	}

	public TaskFurnaceBurdenDto toLazyDto(AgainTaskDetail entity) {
		return modelMapper.map(entity, TaskFurnaceBurdenDto.class);
	}

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

	public InputFurnaceBurden fromDto(InputFurnaceBurdenDto dto) {
		return modelMapper.map(dto, InputFurnaceBurden.class);
	}


}
