package com.sy.coinage.workshop.controller;

import com.sy.coinage.core.constants.Constants;
import com.sy.coinage.core.exception.RetException;
import com.sy.coinage.workshop.service.IBaseInfoService;
import com.sy.coinage.workshop.service.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.List;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sy.coinage.core.annotation.ActiveFastJsonProfile;
import com.sy.coinage.core.annotation.CurrentUser;
import com.sy.coinage.core.aop.annotation.Permission;
import com.sy.coinage.core.aop.annotation.Operation;
import com.sy.coinage.core.controller.BaseController;
import com.sy.coinage.core.interceptor.Create;
import com.sy.coinage.core.interceptor.Update;
import com.sy.coinage.core.req.*;
import com.sy.coinage.core.vo.*;

import com.sy.coinage.workshop.model.*;
import com.sy.coinage.workshop.service.IDeliveryJumpService;
import com.sy.coinage.workshop.vo.*;
import com.sy.coinage.workshop.req.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

@Api(value = "接口", tags = {"接口"})
@RestController
@RequestMapping(value = "/deliveryJump")
public class DeliveryJumpController extends BaseController {

    @Autowired
    private IDeliveryJumpService deliveryJumpService;

    @Autowired
    private IBaseInfoService baseInfoService;

    @Autowired
    private IProductService productService;

    @ApiOperation(value = "分页列表")
    @PostMapping("/page")
    @ActiveFastJsonProfile(groups = "list", clazz = DeliveryJump.class)
    public IPage<DeliveryJump> page(@RequestBody @ApiParam(value = "列表查询请求bean") DeliveryJumpListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<DeliveryJump> queryWrapper = new LambdaQueryWrapper<>();
        if (req.getSecuritiesId() != null && req.getSecuritiesId() > 0) {
            queryWrapper.eq(DeliveryJump::getSecuritiesId, req.getSecuritiesId());
        }
        if (req.getEnable() != null && req.getEnable() > 0) {
            queryWrapper.eq(DeliveryJump::getEnable, req.getEnable());
        }
        Page<DeliveryJump> page = new Page<>(req.getPage(), req.getRows());
        IPage<DeliveryJump> data = this.deliveryJumpService.page(page, queryWrapper);
        return data;
    }

    @ApiOperation(value = "列表")
    @PostMapping("/list")
    @ActiveFastJsonProfile(groups = "list", clazz = DeliveryJump.class)
    public List<DeliveryJump> list(@RequestBody @ApiParam(value = "列表查询请求bean") @Valid DeliveryJumpListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<DeliveryJump> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeliveryJump::getSecuritiesId, req.getSecuritiesId());
        queryWrapper.eq(DeliveryJump::getEnable, Constants.STATUS_USABLE);
        if (req.getStatus().intValue() == 2) {
            queryWrapper.eq(DeliveryJump::getStatus, 1);
        } else {
            queryWrapper.lt(DeliveryJump::getStatus, 2);
        }
        List<DeliveryJump> data = this.deliveryJumpService.list(queryWrapper);
        return data;
    }

    @ApiOperation(value = "获取详情")
    @PostMapping("/get")
    @ActiveFastJsonProfile(groups = "get", clazz = DeliveryJump.class)
    public DeliveryJumpVO get(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req) {
        DeliveryJumpVO data = null;
        DeliveryJump model = this.deliveryJumpService.getById(req.getId());
        data = new DeliveryJumpVO();
        BeanUtils.copyProperties(model, data);
        return data;
    }

    // @ApiOperation(value = "选项")
    // @GetMapping("/opt")
    // public List<OptVO> opt(){
    // List<OptVO> data = this.deliveryJumpService.opt();
    //   return data;
    // }

    @ApiOperation(value = "新增")
    @Operation(value = "新增")
    @PostMapping("/add")
//    @Permission("deliveryJump:add")
    public Object add(@RequestBody @ApiParam(value = "新增请求bean") @Validated({Create.class}) DeliveryJumpReq req, @CurrentUser CacheUserVO user) {
        String[] startStr = req.getSerialNumberStart().split("-");
        String[] endStr = req.getSerialNumberEnd().split("-");
        if (!endStr[0].equals(startStr[0])) {
            throw new RetException("开始拍号和结束拍号前缀不相同，start=" + req.getSerialNumberStart() + ",end=" + req.getSerialNumberEnd());
        }
        Integer start = Integer.parseInt(startStr[1]);
        Integer end = Integer.parseInt(endStr[1]);
        Integer total = end - start;
        if (total < 0) {
            throw new RetException("开始拍号不能小于结束拍号，start=" + req.getSerialNumberStart() + ",end=" + req.getSerialNumberEnd());
        }
//        Integer jumpQty = this.validSerialNumber(req);
        DeliveryJump model = new DeliveryJump();
        BeanUtils.copyProperties(req, model);
        if (total > 0) {
            // 验证开始和结束区间的所有序号状态是否存在
            for (int i = 0; i <= total; i++) {
                // 拼接序号
                String serialNumber = startStr[0] + "-" + String.format("%04d", (start + i));
                // 不存在会抛出异常 校验状态入了部门临时库后的状态都可以。即base_info表里的status>1的状态
                BaseInfo info = this.baseInfoService.getBySerialNumberNoUnpackage(serialNumber, 1);
                if (i == 0) {
                    model.setCrownFrom(info.getCrownFrom());
                }
                if (i == total) {
                    model.setCrownTo(info.getCrownTo());
                }
            }
        } else {
            // 开始拍号与结束拍号相同
            // 不存在会抛出异常 校验状态入了部门临时库后的状态都可以。即base_info表里的status>1的状态
            BaseInfo info = this.baseInfoService.getBySerialNumberNoUnpackage(req.getSerialNumberStart(), 1);
            model.setCrownFrom(info.getCrownFrom());
            model.setCrownTo(info.getCrownTo());
        }

        Product product = this.productService.getByCache(req.getSecuritiesId());
        model.setSecurities(product.getSecurities());
        model.setCreator(user.getRealName());
        model.setEnable(Constants.STATUS_USABLE);
        model.setStatus(0);
        model.setJumpQty(total + 1);
        this.deliveryJumpService.save(model);
        return "";
    }

    @ApiOperation(value = "修改")
    @Operation(value = "修改")
    @PostMapping("/update")
//    @Permission("deliveryJump:update")
    public Object update(@RequestBody @ApiParam(value = "修改请求bean") @Validated({Update.class}) DeliveryJumpReq req, @CurrentUser CacheUserVO user) {
        String[] startStr = req.getSerialNumberStart().split("-");
        String[] endStr = req.getSerialNumberEnd().split("-");
        if (!endStr[0].equals(startStr[0])) {
            throw new RetException("开始拍号和结束拍号前缀不相同，start=" + req.getSerialNumberStart() + ",end=" + req.getSerialNumberEnd());
        }
        Integer start = Integer.parseInt(startStr[1]);
        Integer end = Integer.parseInt(endStr[1]);
        Integer total = end - start;
        if (total < 0) {
            throw new RetException("开始拍号不能小于结束拍号，start=" + req.getSerialNumberStart() + ",end=" + req.getSerialNumberEnd());
        }
        DeliveryJump model = this.deliveryJumpService.getById(req.getId());
        BeanUtils.copyProperties(req, model);
        if (total > 0) {
            // 验证开始和结束区间的所有序号状态是否存在
            for (int i = 0; i <= total; i++) {
                // 拼接序号
                String serialNumber = startStr[0] + "-" + String.format("%04d", (start + i));
                // 不存在会抛出异常
                BaseInfo info = this.baseInfoService.getBySerialNumberNoUnpackage(serialNumber, 1);
                if (i == 0) {
                    model.setCrownFrom(info.getCrownFrom());
                }
                if (i == total) {
                    model.setCrownTo(info.getCrownTo());
                }
            }
        } else {
            // 开始拍号与结束拍号相同
            // 不存在会抛出异常
            BaseInfo info = this.baseInfoService.getBySerialNumberNoUnpackage(req.getSerialNumberStart(), 1);
            model.setCrownFrom(info.getCrownFrom());
            model.setCrownTo(info.getCrownTo());
        }
        Product product = this.productService.getByCache(req.getSecuritiesId());
        model.setSecurities(product.getSecurities());
        model.setCreator(user.getRealName());
        model.setJumpQty(total + 1);
        this.deliveryJumpService.updateById(model);
        return "";
    }

    @ApiOperation(value = "修改状态")
    @Operation(value = "修改状态")
    @PostMapping("/status")
//    @Permission("deliveryJump:update")
    public Integer status(@RequestBody @Valid IdReq req, @CurrentUser CacheUserVO user) {
        DeliveryJump model = this.deliveryJumpService.getById(req.getId());
        if (null != model.getEnable() && model.getEnable().intValue() == Constants.STATUS_FORBIDDEN) {
            model.setEnable(Constants.STATUS_USABLE);
        } else {
            model.setEnable(Constants.STATUS_FORBIDDEN);
        }
        this.deliveryJumpService.updateById(model);
        return model.getStatus();
    }


}
