package com.tzy.controller.ierp;

import com.tzy.annotation.ApiLimitRule;
import com.tzy.annotation.RequireRoles;
import com.tzy.ierp.domain.PyErpRandomCode;
import com.tzy.ierp.dto.PyErpRandomCodeDto;
import com.tzy.ierp.dto.PyErpRandomCodeReq;
import com.tzy.common.config.handle.ApiVersion;
import com.tzy.common.dto.OutDTO;
import com.tzy.common.utils.UserType;
import com.tzy.common.utils.bean.BeanUtils;
import com.tzy.framework.web.domain.LimitRule;
import com.tzy.ierp.enums.PyRandomCodeEnums;
import com.tzy.ierp.service.PyErpRandomCodeService;
import com.tzy.valid.Select;
import com.tzy.valid.Update;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 *
 */
@Api(tags = "随机码接口" , value = "随机码接口")
@RestController
@RequestMapping("/api/{version}/erpRandomCode")
@Slf4j
public class PyErpRandomCodeController {
    @Autowired
    private PyErpRandomCodeService pyErpRandomCodeService;

    /**
     * 生态购随机码 查询
     */
    @ApiOperation( value = "生态购随机码 查询")
    @ApiVersion(1.0)
    @ApiLimitRule(seconds = 1, limitCount = 1, type = LimitRule.USER, msg = "操作频繁!")
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    @RequireRoles(value = {UserType.USER_ROLE_ADMIN, UserType.USER_ROLE_SHIPPING, UserType.USER_ROLE_ECOLOGICAL_SHOPPING})
    @ResponseBody
    public OutDTO query(@Validated(Select.class) @RequestBody PyErpRandomCodeReq req) {
        PyErpRandomCode randomCode = pyErpRandomCodeService.getPyErpRandomCode(req);
        PyErpRandomCodeDto dto = new PyErpRandomCodeDto();
        BeanUtils.copyProperties(randomCode, dto);
        dto.setStatusMsg(PyRandomCodeEnums.getMsg(randomCode.getStatus()));
        if(Objects.equals(dto.getStatus(), PyRandomCodeEnums.CANCEL.getCode())){
            return OutDTO.error500("该核销码已作废!");
        }
        return OutDTO.ok()
                .put("data", dto);
    }

    /**
     * 生态购随机码 系统入库绑定
     *
     * @param req
     * @return
     */
    @ApiOperation( value = "生态购随机码 系统入库绑定")
    @ApiVersion(1.0)
    @ApiLimitRule(seconds = 1, limitCount = 1, type = LimitRule.USER, msg = "操作频繁!")
    @RequestMapping(value = "/sysIn", method = RequestMethod.POST)
    @RequireRoles(value = {UserType.USER_ROLE_ADMIN, UserType.USER_ROLE_SHIPPING, UserType.USER_ROLE_ECOLOGICAL_SHOPPING})
    @ResponseBody
    public OutDTO sysIn(@Validated(Update.class) @RequestBody PyErpRandomCodeReq req) {
        if(!pyErpRandomCodeService.sysIn(req)){
            return OutDTO.error500("入库绑定失败!")
                    ;
        }
        return OutDTO.ok();
    }
}
