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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sw.mes.base.factory.init.entity.Device;
import com.sw.mes.base.factory.init.entity.Equipment;
import com.sw.mes.base.factory.init.entity.FactoryModel;
import com.sw.mes.base.factory.init.service.DeviceService;
import com.sw.mes.base.factory.init.service.EquipmentService;
import com.sw.mes.base.factory.init.service.FactoryModelService;
import com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.store.WarehouseOutputBillBo;
import com.sw.mes.core.dto.store.WarehouseOutputBillDetailBo;
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.plan.entity.ProductionSchedule;
import com.sw.mes.yb.plan.service.ProductionScheduleService;
import com.sw.mes.yb.seed.dto.SeedMaterialsRecordDto;
import com.sw.mes.yb.seed.dto.SeedPlanOrderDto;
import com.sw.mes.yb.seed.dto.WarehouseInventoryDto;
import com.sw.mes.yb.seed.entity.SeedData;
import com.sw.mes.yb.seed.entity.SeedMaterialsRecord;
import com.sw.mes.yb.seed.entity.SeedPlanOrder;
import com.sw.mes.yb.seed.service.SeedMaterialsRecordService;
import com.sw.mes.yb.seed.service.SeedService;
import io.swagger.annotations.*;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.spring.web.json.Json;

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

@RestController
@RequestMapping("/seed/materials")
@Api(description = "籽晶领用记录接口")
@Transactional
public class SeedMaterialsRecordController {
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    private SeedMaterialsRecordService recordService;

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

    @GetMapping("/listAll")
    @ApiOperation(value = "查询籽晶领用记录列表")
    public Result<List<SeedMaterialsRecordDto>> listAll(ServletRequest request) {
        Specification<SeedMaterialsRecord> specification = DynamicSpecifications.bySearchFilter(request, SeedMaterialsRecord.class);
        List<SeedMaterialsRecord> seedMaterialsRecords = recordService.findByExampleSort(specification, null);
        List<SeedMaterialsRecordDto> dtos = seedMaterialsRecords.stream().map(entity ->
                toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(dtos);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询籽晶领用记录详情")
    public Result<SeedMaterialsRecordDto> getById(@PathVariable @ApiParam(value = "id") Long id) {
        SeedMaterialsRecord seedMaterialsRecord = recordService.get(id);
        if (ObjectUtils.isEmpty(seedMaterialsRecord)) {
            return ResultGenerator.fail("未查到相关数据!");
        }
        return ResultGenerator.success(toEagerDto(seedMaterialsRecord));
    }

    @ApiOperation(value = "创建籽晶领用记录")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "SeedMaterialsRecordDto的对象") SeedMaterialsRecordDto materialsRecordDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return recordService.create(materialsRecordDto);
    }

    @ApiOperation(value = "更新籽晶领用记录")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "SeedMaterialsRecordDto的对象") SeedMaterialsRecordDto materialsRecordDto
            , BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        SeedMaterialsRecord seedMaterialsRecord = recordService.get(materialsRecordDto.getId());
        if (ObjectUtils.isEmpty(seedMaterialsRecord)) {
            return ResultGenerator.fail("该领料记录不存在!");
        }
        seedMaterialsRecord.setRethrowsNumber(materialsRecordDto.getRethrowsNumber());
        seedMaterialsRecord.setCreateBy(BaseContextHandler.getUsername());
        seedMaterialsRecord.setCreateDate(new Date());
        recordService.saveOrUpdate(seedMaterialsRecord);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "删除籽晶领用记录")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            recordService.delete(id);
        }
        return ResultGenerator.success();
    }

    @ApiOperation(value = "导出籽晶领用记录接口")
    @GetMapping("/export")
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
            Specification<SeedMaterialsRecord> specification = DynamicSpecifications.bySearchFilter(request, SeedMaterialsRecord.class);
            List<SeedMaterialsRecord> seedMaterialsRecords = recordService.findByExampleSort(specification, null);
            List<SeedMaterialsRecordDto> dtos = seedMaterialsRecords.stream().map(entity ->
                    toLazyDto(entity)).collect(Collectors.toList());
            ExcelUtil.exportExcel(dtos, "籽晶领用记录", SeedMaterialsRecordDto.class, response);
        } catch (Exception e) {
            throw new RuntimeException("籽晶领用记录导出失败，错误信息：" + e.getMessage());
        }
    }

    public SeedMaterialsRecordDto toLazyDto(SeedMaterialsRecord entity) {
        SeedMaterialsRecordDto seedMaterialsRecordDto = new SeedMaterialsRecordDto();
        BeanUtils.copyProperties(entity, seedMaterialsRecordDto);
        return seedMaterialsRecordDto;
    }

    public SeedMaterialsRecordDto toEagerDto(SeedMaterialsRecord entity) {
        SeedMaterialsRecordDto seedMaterialsRecordDto = new SeedMaterialsRecordDto();
        BeanUtils.copyProperties(entity, seedMaterialsRecordDto);
        return seedMaterialsRecordDto;
    }

    public SeedMaterialsRecord fromDto(SeedMaterialsRecordDto dto) {
        SeedMaterialsRecord seedMaterialsRecord = new SeedMaterialsRecord();
        BeanUtils.copyProperties(dto, seedMaterialsRecord);
        return seedMaterialsRecord;
    }
}
