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

import com.sw.mes.agv.dao.MonitorEquipmentChargeDAO;
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.pc.dao.StoreMixInfoDao;
import com.sw.mes.yb.pc.dto.StoreMixInfoItemDto;
import com.sw.mes.yb.pc.entity.StoreMixInfo;
import com.sw.mes.yb.pc.entity.StoreMixInfoItem;
import com.sw.mes.yb.pc.service.StoreMixInfoItemService;
import com.sw.mes.yb.pc.service.StoreMixInfoService;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author liru
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("pc/storeMixInfoItem")
@Slf4j
@Api(description = "配料明细")
public class StoreMixInfoItemController {

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private StoreMixInfoItemService storeMixInfoItemService;

    @Autowired
    private StoreMixInfoService storeMixInfoService;

    @Autowired
    private StoreMixInfoDao storeMixInfoDao;


    @Autowired
    private MonitorEquipmentChargeDAO monitorEquipmentChargeDAO;

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

    @ApiOperation(value = "详细信息")
    @GetMapping("/{id}")
    public Result<StoreMixInfoItemDto> get(@PathVariable @ApiParam(value = "设备类型id") Integer id) {
        StoreMixInfoItem storeMixInfoItem = storeMixInfoItemService.get(id);
        if (null == storeMixInfoItem) {
            return ResultGenerator.fail("该对象不存在");
        }
        return ResultGenerator.success(toEagerDto(storeMixInfoItem));
    }

    @ApiOperation(value = "创建")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "Dto对象") StoreMixInfoItemDto storeMixInfoItemDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        StoreMixInfoItem storeMixInfoItem = fromDto(storeMixInfoItemDto);
        storeMixInfoItemService.saveOrUpdate(storeMixInfoItem);
        return ResultGenerator.success();
    }

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

    public StoreMixInfoItemDto toLazyDto(StoreMixInfoItem entity) {
        return modelMapper.map(entity, StoreMixInfoItemDto.class);
    }

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

    public StoreMixInfoItem fromDto(StoreMixInfoItemDto dto) {
        return modelMapper.map(dto, StoreMixInfoItem.class);
    }


//    待配料monitor_equipment_charge
//    配料记录store_mix_info
//    点检记录zhxx_operate_crucible_check_data

    @ApiOperation(value = "设备对调")
    @PostMapping("/exchange")
    public Result exchange(@ApiParam(value = "传入map；key：old;new") @RequestBody Map<String, Object> bodyMap) {
        String oldCode = null;
        String newCode = null;
        if (bodyMap.get("old") != null) {
            oldCode = bodyMap.get("old").toString();
        }
        if (bodyMap.get("new") != null) {
            newCode = bodyMap.get("new").toString();
        }
        StoreMixInfo storeMixInfoOld;
        List<StoreMixInfo> storeMixInfoOldList;
        if (oldCode == null || (storeMixInfoOldList = storeMixInfoDao.findByLotNo(oldCode)).size() != 1) {
            return ResultGenerator.fail("旧炉次号不存在配料记录！");
        }
        storeMixInfoOld = storeMixInfoOldList.get(0);
        StoreMixInfo storeMixInfoNew;
        List<StoreMixInfo> storeMixInfoNewList;
        if (newCode == null || (storeMixInfoNewList = storeMixInfoDao.findByLotNo(newCode)).size() != 1) {
            return ResultGenerator.fail("新炉次号不存在配料记录！");
        }
        storeMixInfoNew = storeMixInfoNewList.get(0);
//        if (crucibleCheckDataDAO.countByLotNo(oldCode).intValue() != 0) {
//            return ResultGenerator.fail("旧炉次号已存在点检记录！");
//        }
//        if (crucibleCheckDataDAO.countByLotNo(newCode).intValue() != 0) {
//            return ResultGenerator.fail("新炉次号已存在点检记录！");
//        }
        try {
            storeMixInfoService.exchange(storeMixInfoOld, storeMixInfoNew);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }

    }

    @ApiOperation(value = "更换坩埚")
    @PostMapping("/changeCode")
    public Result changeCode(@ApiParam(value = "传入map；key：old;new") @RequestBody Map<String, Object> bodyMap) {
        String oldCode = null;
        String newCode = null;
        if (bodyMap.get("old") != null) {
            oldCode = bodyMap.get("old").toString();
        }
        if (bodyMap.get("new") != null) {
            newCode = bodyMap.get("new").toString();
        }
        if (newCode == null || storeMixInfoDao.countByCode(newCode) != 0) {
            return ResultGenerator.fail("新坩埚已存在配料记录！");
        }
//        if (oldCode == null || crucibleCheckDataDAO.countByCode(oldCode).intValue() != 0) {
//            return ResultGenerator.fail("原坩埚已点检!");
//        }
//        if (crucibleCheckDataDAO.countByCode(newCode).intValue() != 0) {
//            return ResultGenerator.fail("新坩埚已点检!");
//        }
        if (storeMixInfoDao.countByCode(oldCode).intValue() != 1) {
            return ResultGenerator.fail("原坩埚不存在配料记录！");
        }
        try {
            storeMixInfoService.updateCode(oldCode, newCode);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }

    }

    @ApiOperation(value = "更换设备")
    @PostMapping("/changeDeviceNo")
    public Result changeDeviceNo(@ApiParam(value = "传入map； key：old;new") @RequestBody Map<String, Object> bodyMap) {
        String oldCode = null;
        String newCode = null;
        if (bodyMap.get("old") != null) {
            oldCode = bodyMap.get("old").toString();
        }
        if (bodyMap.get("new") != null) {
            newCode = bodyMap.get("new").toString();
        }
        StoreMixInfo storeMixInfoOld;
        List<StoreMixInfo> storeMixInfoList = new ArrayList<>();
        if (oldCode == null || (storeMixInfoList = storeMixInfoDao.findByLotNo(oldCode)).size() != 1) {
            return ResultGenerator.fail("旧炉次号不存在配料记录！");
        }
        storeMixInfoOld = storeMixInfoList.get(0);
//        if (crucibleCheckDataDAO.countByLotNo(oldCode).intValue() != 0) {
//            return ResultGenerator.fail("旧炉次号已存在点检记录！");
//        }
        if (newCode == null || newCode.length() != 9 || storeMixInfoDao.countByLotNo(newCode).intValue() != 0) {
            return ResultGenerator.fail("新炉次号已存在配料记录或新炉次号格式错误！");
        }
        String newDeviceNo = monitorEquipmentChargeDAO.getNameByLotNo(newCode);
//        String newDeviceNo = newCode.substring(4, 7);
        if (newDeviceNo != null) {
            try {
                storeMixInfoService.changeDeviceNo(storeMixInfoOld, newCode, newDeviceNo);
                return ResultGenerator.success();
            } catch (Exception e) {
                return ResultGenerator.fail(e.getMessage());
            }
        }
        return ResultGenerator.fail("请检查新炉次号信息！");
    }

    @ApiOperation(value = "退料")
    @PostMapping("/backOff")
    public Result backOff(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Integer[] ids) {

        try {
            storeMixInfoItemService.backOff(ids);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultGenerator.success();
    }

}







