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

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.yb.turnstore.dto.TurnstoreDto;
import com.sw.mes.yb.turnstore.entity.Turnstore;
import com.sw.mes.yb.turnstore.service.TurnstoreService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
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("/turnstore")
@Slf4j
@Api(description = "周转库库存接口")
public class TurnstoreController {
	@Autowired
    ModelMapper modelMapper;

	@Autowired
	private TurnstoreService turnstoreService;



	@ApiOperation(value = "入库统计接口")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sDate", value = "开始日期", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "eDate", value = "结束日期", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "入库类型", dataType = "string", paramType = "query")
	})
	@RequestMapping(value="/getStaticIn", method= RequestMethod.GET)
	public Result getStaticIn(String sDate, String eDate, String type){
		if(StringUtils.isBlank(sDate)){
			return ResultGenerator.fail("开始日期不能为空");
		}
		if(StringUtils.isBlank(eDate)){
			return ResultGenerator.fail("结束日期不能为空");
		}
		if(StringUtils.isBlank(type)){
			return ResultGenerator.fail("入库类型不能为空");
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date sdate = null;
		try {
			sdate = format.parse(sDate);
		} catch (ParseException e) {
			return ResultGenerator.fail("开始日期错误");
		}

		Date edate = null;
		try {
			edate = format.parse(eDate);
		} catch (ParseException e) {
			return ResultGenerator.fail("结束日期错误");
		}

		Calendar sCa = Calendar.getInstance();
		sCa.setTime(sdate);
		sCa.add(Calendar.MINUTE,510);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//开始日期加08:30
		String sDateStr = sdf.format(sCa.getTime());
		//结束日期加1天08：30
		Calendar eCa = Calendar.getInstance();
		eCa.setTime(edate);
		eCa.add(Calendar.MINUTE,1950);
		String eDateStr = sdf.format(eCa.getTime());

		List<Map<String,Object>> list = turnstoreService.getStaticIn(sDateStr,eDateStr,type);
		return ResultGenerator.success(list);
	}

	@ApiOperation(value = "出库统计接口")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sDate", value = "开始日期", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "eDate", value = "结束日期", dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "type", value = "入库类型", dataType = "string", paramType = "query")
	})
	@RequestMapping(value="/getStaticOut", method= RequestMethod.GET)
	public Result getStaticOut(String sDate, String eDate, String type){
		if(StringUtils.isBlank(sDate)){
			return ResultGenerator.fail("开始日期不能为空");
		}
		if(StringUtils.isBlank(eDate)){
			return ResultGenerator.fail("结束日期不能为空");
		}
		if(StringUtils.isBlank(type)){
			return ResultGenerator.fail("入库类型不能为空");
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date sdate = null;
		try {
			sdate = format.parse(sDate);
		} catch (ParseException e) {
			return ResultGenerator.fail("开始日期错误");
		}

		Date edate = null;
		try {
			edate = format.parse(eDate);
		} catch (ParseException e) {
			return ResultGenerator.fail("结束日期错误");
		}

		Calendar sCa = Calendar.getInstance();
		sCa.setTime(sdate);
		sCa.add(Calendar.MINUTE,510);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//开始日期加08:30
		String sDateStr = sdf.format(sCa.getTime());
		//结束日期加1天08：30
		Calendar eCa = Calendar.getInstance();
		eCa.setTime(edate);
		eCa.add(Calendar.MINUTE,1950);
		String eDateStr = sdf.format(eCa.getTime());
		List<Map<String,Object>> list = turnstoreService.getStaticOut(sDate,eDate,type);
		return ResultGenerator.success(list);
	}

	@ApiOperation(value = "分页查询周转库库存列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
		@ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
	})
	@GetMapping("/listByPage")
	public Result<ResponsePage<TurnstoreDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
		Specification<Turnstore> specification = DynamicSpecifications.bySearchFilter(request, Turnstore.class);
    	Page<Turnstore> page = turnstoreService.findByExample(specification, PageUtil.createPageable(requestPage));
		List<TurnstoreDto> 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<TurnstoreDto>> listAll(ServletRequest request) {
		Specification<Turnstore> specification = DynamicSpecifications.bySearchFilter(request, Turnstore.class);
		List<Turnstore> turnstores = turnstoreService.findByExampleSort(specification, null);
		List<TurnstoreDto> turnstoreDtos = turnstores.stream()
					.map(turnstore -> toLazyDto(turnstore))
					.collect(Collectors.toList());
		return ResultGenerator.success(turnstoreDtos);
	}

	@ApiOperation(value = "周转库库存详细信息")
	@GetMapping("/{id}")
	public Result<TurnstoreDto> get(@PathVariable @ApiParam(value="周转库库存id") Integer id) {
		Turnstore turnstore = turnstoreService.get(id);
		if (null == turnstore) {
            return ResultGenerator.fail("该周转库库存不存在");
        }
		return ResultGenerator.success(toEagerDto(turnstore));
	}

	@ApiOperation(value = "创建周转库库存")
	@PostMapping("/create")
	public Result create(@RequestBody @Valid @ApiParam(value = "周转库库存对象") TurnstoreDto turnstoreDto, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
		}
		Turnstore turnstore = fromDto(turnstoreDto);
		turnstoreService.saveOrUpdate(turnstore);
		return ResultGenerator.success();
	}

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

	public TurnstoreDto toLazyDto(Turnstore entity) {
		//ModelMapper modelMapper = new ModelMapper();
		modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
		modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
		return modelMapper.map(entity, TurnstoreDto.class);
	}

	public TurnstoreDto toEagerDto(Turnstore entity) {
		//ModelMapper modelMapper = new ModelMapper();
		modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
		modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
		TurnstoreDto dto = modelMapper.map(entity, TurnstoreDto.class);
		return dto;
	}

	public Turnstore fromDto(TurnstoreDto dto) {
		//ModelMapper modelMapper = new ModelMapper();
		modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
		modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
		return modelMapper.map(dto, Turnstore.class);
	}


}
