package com.ximai.mes.restful;

import com.alibaba.fastjson.JSON;
import com.ximai.common.core.controller.BaseController;
import com.ximai.common.core.domain.SapAjaxResult;
import com.ximai.framework.security.BasicAuth;
import com.ximai.mes.pro.domain.sap.SAPDtoTmToolBody;
import com.ximai.mes.tm.service.ITmToolService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ Author: chicheng.li
 * @ Date  : 2024/2/21
 */
@RestController
@RequestMapping(value = "/api/v1/toolmachine")
public class ToolMachineRestController extends BaseController {
    @Autowired
    private ITmToolService iTmToolService;


    @ApiOperation(value = "sap刀模版通用接口")
    @BasicAuth
    @RequestMapping(value = "/sapapi", method = RequestMethod.POST)
    public SapAjaxResult add(@RequestBody String tmToolJson) {
        SAPDtoTmToolBody sapDtoTmToolBody = null;
        int resultcode = 0;
        try {
            sapDtoTmToolBody = JSON.parseObject(tmToolJson, SAPDtoTmToolBody.class);
            String actionType = sapDtoTmToolBody.getTmTools().stream().findFirst().get().getActionType();
            switch (actionType) {
                case "insert":
                    resultcode = iTmToolService.insertObj(sapDtoTmToolBody);
                    break;
                case "delete":
                    List<SAPDtoTmToolBody.SnBody> snBodies = sapDtoTmToolBody.getSnBodies();
                    Set<String> codes = snBodies.stream().map(SAPDtoTmToolBody.SnBody::getToolCode).collect(Collectors.toSet());
                    for (String code : codes) {
                        resultcode = iTmToolService.deleteTmToolByToolCode(code);
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
//            throw new RuntimeException(e);
            return SapAjaxResult.error(e.getMessage());
        }
        return sapToAjax(resultcode);
    }

}
