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

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sw.mes.core.enums.EnumValues;
import com.sw.mes.yb.accessory.dto.AccessoryApplyDto;
import com.sw.mes.yb.accessory.dto.AccessoryMaterialDto;
import com.sw.mes.yb.accessory.dto.IdDto;
import com.sw.mes.yb.accessory.entity.AccessoryApply;
import com.sw.mes.yb.accessory.entity.AccessoryMaterial;
import com.sw.mes.yb.accessory.service.impl.AccessoryApplyServiceImpl;
import com.sw.mes.yb.accessory.vo.WmsResult;
import com.sw.mes.yb.accessory.service.AccessoryApplyService;
import com.sw.mes.yb.accessory.service.AccessoryMaterialService;

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 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.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/accessoryApply")
@Slf4j
@Api(description = "热场申请记录接口")
public class AccessoryApplyController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private AccessoryApplyService accessoryApplyService;

    @Autowired
    private AccessoryMaterialService accessoryMaterialService;

    @ApiOperation(value = "分页查询热场申请记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_material.codes", value = "料号", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_goodsCode", value = "唯一条码(热场条码)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "search_LIKE_pickNo", value = "申请单号", dataType = "string", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<AccessoryApplyDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<AccessoryApply> specification = DynamicSpecifications.bySearchFilter(request, AccessoryApply.class);
        Page<AccessoryApply> page = accessoryApplyService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<AccessoryApplyDto> 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<AccessoryApplyDto>> listAll(ServletRequest request) {
        Specification<AccessoryApply> specification = DynamicSpecifications.bySearchFilter(request, AccessoryApply.class);
        List<AccessoryApply> accessoryApplys = accessoryApplyService.findByExampleSort(specification, null);
        List<AccessoryApplyDto> accessoryApplyDtos = accessoryApplys.stream()
                .map(accessoryApply -> toLazyDto(accessoryApply))
                .collect(Collectors.toList());
        return ResultGenerator.success(accessoryApplyDtos);
    }

    @ApiOperation(value = "热场申请详细信息")
    @GetMapping("/{id}")
    public Result<AccessoryApplyDto> get(@PathVariable @ApiParam(value = "热场申请id") Long id) {
        AccessoryApply accessoryApply = accessoryApplyService.get(id);
        if (null == accessoryApply) {
            return ResultGenerator.fail("该热场申请不存在");
        }
        return ResultGenerator.success(toEagerDto(accessoryApply));
    }

    @ApiOperation(value = "热场要料申请")
    @PostMapping("/create")
    public Result create(@RequestBody @ApiParam(value = "热场申请对象") IdDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("申请信息不存在");
        }
        try {
            accessoryApplyService.apply(dto);
            return ResultGenerator.success();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(ExceptionUtil.stacktraceToString(e));
            return ResultGenerator.fail(e.getMessage());
        }
//		try {
//			AccessoryApply entityfromFto = fromDto(accessoryApplyDto);
//			accessoryApplyService.saveOrUpdate(entityfromFto);
//		} catch (Exception e) {
//			return ResultGenerator.fail(e.getMessage());
//		}
//		return ResultGenerator.success();
    }

    @ApiOperation(value = "热场新建要料申请")
    @PostMapping("/create1")
    public Result create1(@RequestBody @ApiParam(value = "热场申请对象") @Valid AccessoryApplyDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
//        if (dto.getId() == null) {
//            return ResultGenerator.fail("申请信息不存在");
//        }
        try {
            accessoryApplyService.apply1(dto);
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error(ExceptionUtil.stacktraceToString(e));
            return ResultGenerator.fail(e.getMessage());
        }
//		try {
//			AccessoryApply entityfromFto = fromDto(accessoryApplyDto);
//			accessoryApplyService.saveOrUpdate(entityfromFto);
//		} catch (Exception e) {
//			return ResultGenerator.fail(e.getMessage());
//		}
//		return ResultGenerator.success();
    }

    @ApiOperation(value = "获取要料单号")
    @GetMapping("/getPickNo")
    public Result getPickNo(String deviceNo) {
        AccessoryApplyServiceImpl accessoryApplyService = new AccessoryApplyServiceImpl();
        return ResultGenerator.success(accessoryApplyService.getPickNo(deviceNo));
    }

    @ApiOperation(value = "更新热场申请")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "热场申请") AccessoryApplyDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        AccessoryApply entity = accessoryApplyService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            AccessoryApply entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            accessoryApplyService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error(ExceptionUtil.stacktraceToString(e));
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "热场取消更换申请")
    @PostMapping("/cancel")
    public Result cancel(@RequestBody @ApiParam(value = "热场申请dto") IdDto dto) {
        if (dto.getId() == null) {
            return ResultGenerator.fail("申请信息不存在");
        }
        try {
            accessoryApplyService.cancel(dto.getId());
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error(ExceptionUtil.stacktraceToString(e));
            e.printStackTrace();
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "热场取消更换申请")
    @PostMapping("/cancelByOrderNum")
    public Result cancelByOrderNum(@RequestParam("orderNum") String orderNum) {
        try {
            accessoryApplyService.cancelByOrderNum(orderNum);
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error(ExceptionUtil.stacktraceToString(e));
            e.printStackTrace();
            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) {
            accessoryApplyService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "更新热场申请状态")
    @PostMapping("/updateState/{id}")
    public Result updateState(@PathVariable @ApiParam(value = "热场申请id") Long id) {

        AccessoryApply entity = accessoryApplyService.get(id);
        if (entity == null) {
            return ResultGenerator.fail("申请信息不存在");
        }
        try {
            if (entity.getState().equals(EnumValues.PickInfoStatus.ENDDING.getKey())) {
                return ResultGenerator.fail("此申请已出库，不允许取消");
            }
            entity.setState(EnumValues.PickInfoStatus.CANCEL.getKey());
            accessoryApplyService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            log.error(ExceptionUtil.stacktraceToString(e));
            return ResultGenerator.fail(e.getMessage());
        }
    }

    public AccessoryApplyDto toLazyDto(AccessoryApply entity) {
        AccessoryApplyDto accessoryApplyDto = modelMapper.map(entity, AccessoryApplyDto.class);
        if (entity.getState() != null) {
            accessoryApplyDto.setState(EnumValues.PickInfoStatus.valueOf(entity.getState()).getValue());
        }
        if (accessoryApplyDto.getMaterialId() != null) {
            AccessoryMaterial accessoryMaterial = accessoryMaterialService.get(accessoryApplyDto.getMaterialId());
            if (accessoryMaterial != null) {
                AccessoryMaterialDto materialDto = modelMapper.map(accessoryMaterial, AccessoryMaterialDto.class);
                accessoryApplyDto.setMaterialDto(materialDto);
            }
        }
        return accessoryApplyDto;
    }

    public AccessoryApplyDto toEagerDto(AccessoryApply entity) {
        AccessoryApplyDto dto = modelMapper.map(entity, AccessoryApplyDto.class);
        if (dto.getMaterialId() != null) {
            AccessoryMaterial accessoryMaterial = accessoryMaterialService.get(dto.getMaterialId());
            if (accessoryMaterial != null) {
                AccessoryMaterialDto materialDto = modelMapper.map(accessoryMaterial, AccessoryMaterialDto.class);
                dto.setMaterialDto(materialDto);
            }
        }
        return dto;
    }

    public AccessoryApply fromDto(AccessoryApplyDto dto) {
        return modelMapper.map(dto, AccessoryApply.class);
    }


//    @GetMapping("/abc")
//    public Result abc(String str) {
//        String ss = toWmsService.ss(str);
//        System.out.println(ss);
//        WmsResult wmsResult = JSON.parseObject(ss, new TypeReference<WmsResult>() {
//        });
//        return ResultGenerator.success(wmsResult.toString());
//    }
}
