package com.prolog.upcloud.base.wh.operate.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.prolog.entity.vo.OutBoundRequestVO;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.lock.DistributedLock;
import com.prolog.framework.log.aop.annotation.UserLog;
import com.prolog.upcloud.base.wh.operate.controller.common.BaseController;
import com.prolog.upcloud.base.wh.operate.dto.ReplenishIncidentallyDTO;
import com.prolog.upcloud.base.wh.operate.dto.ReplenishPassiveDTO;
import com.prolog.upcloud.base.wh.operate.service.WmsReplenishService;
import com.prolog.upcloud.base.wh.operate.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
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 javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * @author wujunjie
 */
@Api(tags = "补货")
@RestController
@RequestMapping("/replenish")
@Slf4j
@Validated
public class ReplenishController extends BaseController {

    @Autowired
    WmsReplenishService wmsReplenishService;
    @Autowired
    private DistributedLock distributedLock;

    @UserLog("被动补货")
    @ApiOperation("被动补货")
    @PostMapping("v1/passive")
    public RestMessage<List<ReplenishPassiveDTO>> replenishPassive(@RequestBody @Valid ReplenishPassiveSaveVO saveVO) {
        return success(wmsReplenishService.replenishPassive(saveVO));
    }

    @UserLog("紧急补货")
    @ApiOperation("紧急补货")
    @PostMapping("v1/urgent")
    public RestMessage<String> replenishUrgent(@RequestBody @Valid ReplenishUrgentSaveVO saveVO) {
        String s = wmsReplenishService.replenishUrgent(saveVO);
        return RestMessage.success("成功", s);
    }

    @UserLog("主动补货")
    @ApiOperation("主动补货")
    @PostMapping("v1/initiative")
    public RestMessage<Object> replenishInitiative(@RequestBody @Valid ReplenishInitiativeSaveVO saveVO) {
        try {
            distributedLock.execute("initiative:create", 1000 * 60 * 10, () -> {
                wmsReplenishService.replenishInitiative(saveVO);
                return true;
            });
        } catch (Exception e) {
            if (StrUtil.isEmpty(e.getMessage())) {
                String msg = "执行分布式锁失败:" + JSONObject.toJSONString(e);
                log.error(msg, e);
                throw new BizException(msg, e);
            }
            if (e.getMessage().equals("redisTemplate is null")) {
                String msg = "执行分布式锁失败:" + e.getMessage();
                log.error(msg, e);
                throw new BizException(msg, e);
            }
            if (e.getMessage().contains("加锁失败")) {
                String msg = "有主动补货正在进行，请稍后再试!";
                log.error(msg, e);
                throw new BizException(msg, e);
            }
            throw new PrologException(e.getMessage());
        }
        return success();
    }

    @UserLog("预补货")
    @ApiOperation("预补货")
    @PostMapping("/v1/pre")
    public RestMessage<Object> replenishPre(@RequestBody List<@Valid ReplenishPreVO> vos) {
        wmsReplenishService.replenishPre(vos);
        return success();
    }

    @ApiOperation("补货查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "warehouseId", value = "仓库编码", required = true, dataType = "String"), @ApiImplicitParam(name = "autoBillNum", value = "自动单号", required = true, dataType = "String"), @ApiImplicitParam(name = "cargoOwnerId", value = "货主编码", required = true, dataType = "String"), @ApiImplicitParam(name = "businessType", value = "补货类型", required = true, dataType = "String"), @ApiImplicitParam(name = "status", value = "补货状态(0新生成/1下架/2上架)", required = true, dataType = "String"), @ApiImplicitParam(name = "omsBillNo", value = "oms单号", required = true, dataType = "String"), @ApiImplicitParam(name = "erpSrcId", value = "源单ID", required = true, dataType = "String"), @ApiImplicitParam(name = "erpSrcNo", value = "源单号", required = true, dataType = "String"), @ApiImplicitParam(name = "erpSrcLineId", value = "源单ID", required = true, dataType = "String")})
    @GetMapping("v1/list")
    public RestMessage<Page<ReplenishListVO>> getReplenishList(ReplenishQueryVO queryVO) {
        startPage();
        Page<ReplenishListVO> page = wmsReplenishService.getReplenishList(queryVO);
        return success(page == null ? emptyPage() : page);
    }

    @UserLog("上架/下架确认")
    @ApiOperation("上架/下架确认")
    @PostMapping("v1/confirm")
    public RestMessage<Object> confirmReplenish(@Valid @RequestBody MoveConfirmParamsVO moveConfirmParamsVO) {
        wmsReplenishService.confirmReplenish(moveConfirmParamsVO);
        return success();
    }

    @UserLog("上架/下架确认")
    @ApiOperation("上架/下架确认")
    @PostMapping("v1/auto-confirm")
    public RestMessage autoConfirmReplenish(@Valid @RequestBody MoveConfirmParamsVO moveConfirmParamsVO) {
        wmsReplenishService.autoConfirmReplenish(moveConfirmParamsVO);
        return success();
    }

    /**
     * 旧补货 上架/下架确认
     *
     * @param moveConfirmParamsVO
     * @return
     */
    @UserLog("上架/下架确认")
    @ApiOperation("上架/下架确认")
    @PostMapping("v2/confirm")
    public RestMessage<Object> confirmReplenishOld(@Valid @RequestBody MoveConfirmParamsVO moveConfirmParamsVO) {
        wmsReplenishService.confirmReplenishOld(moveConfirmParamsVO);
        return success();
    }

    @UserLog("补货取消")
    @ApiOperation("补货取消")
    @PostMapping("v1/cancel")
    public RestMessage cancelReplenish(@Valid @RequestBody ReplenishCancelVO replenishCancelVO) {
        wmsReplenishService.cancelReplenish(replenishCancelVO.getDetailIds());
        return success();
    }

    @UserLog("设备上架确认")
    @ApiOperation("设备上架确认")
    @PostMapping("v1/confirmReplenishDevice")
    public RestMessage confirmReplenishDevice() {
        wmsReplenishService.confirmReplenishDevice();
        return success();
    }

    @UserLog("顺带补货")
    @ApiOperation("顺带补货")
    @PostMapping("v1/replenishIncidentally")
    public RestMessage<List<ReplenishIncidentallyDTO>> replenishIncidentally(@RequestBody @Valid @NotNull(message = "参数不能为空") ReplenishIncidentallyVO vo) {
        List<ReplenishIncidentallyDTO> list = wmsReplenishService.replenishIncidentally(vo);
        return RestMessage.doSuccess(list);
    }

    @UserLog("定时任务-BC品预补货")
    @ApiOperation("定时任务-BC品预补货")
    @PostMapping("/v1/bc/auto-pre")
    public RestMessage<Object> autoBcPre(@RequestBody Map<String,Object> map) {
        wmsReplenishService.autoBcPre(map);
        return success();
    }

    @UserLog("根据波次id获取补货任务推送eis入参")
    @ApiOperation("顺带补货")
    @GetMapping("v1/getRepSendEisParamsByWaveId")
    public RestMessage<List<OutBoundRequestVO>> getRepSendEisParamsByWaveId(@RequestParam(value = "waveId") String waveId) {
        return RestMessage.doSuccess(wmsReplenishService.getRepSendEisParamsByWaveId(waveId));
    }
}