package com.sy.coinage.workshop.controller;

import com.sy.coinage.core.redis.RedisService;
import com.sy.coinage.core.util.DateUtils;
import com.sy.coinage.sys.model.Dict;
import com.sy.coinage.sys.service.IDictService;
import com.sy.coinage.workshop.service.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

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.IDeliveryService;
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;

/**
 * -发货单主表Controller
 */
@Api(value = "发货单主表接口", tags = {"发货单主表接口"})
@RestController
@RequestMapping(value = "/delivery")
public class DeliveryController extends BaseController {

    @Autowired
    private IDeliveryService deliveryService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IDictService dictService;

    /**
     * 发货单主表分页列表
     */
    @ApiOperation(value = "发货单主表分页列表")
    @PostMapping("/list")
    @ActiveFastJsonProfile(groups = "list", clazz = Delivery.class)
    public IPage<Delivery> list(@RequestBody DeliveryListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<Delivery> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(req.getOrderNo()), Delivery::getOrderNo, req.getOrderNo());
        queryWrapper.eq(req.getAddressId() != null && req.getAddressId() > 0, Delivery::getAddressId, req.getAddressId());
        queryWrapper.eq(req.getSecuritiesId() != null && req.getSecuritiesId() > 0, Delivery::getSecuritiesId, req.getSecuritiesId());
        if (req.getDeliveryTime() != null && StringUtils.isNotBlank(String.valueOf(req.getDeliveryTime()))) {
            queryWrapper.between(Delivery::getDeliveryTime, DateUtils.getDayStartTime(req.getDeliveryTime()), DateUtils.getDayEndTime(req.getDeliveryTime()));
        }
        Page<Delivery> page = new Page<>(req.getPage(), req.getRows());
        IPage<Delivery> data = this.deliveryService.page(page, queryWrapper);
        return data;
    }


    /**
     * 发货单主表详情
     */
    @ApiOperation(value = "发货单主表-通过ID查询单条数据")
    @PostMapping("/get")
    @ActiveFastJsonProfile(groups = "get", clazz = Delivery.class)
    public DeliveryVO get(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req) {
        DeliveryVO data = null;
        Delivery model = this.deliveryService.getById(req.getId());
        data = new DeliveryVO();
        BeanUtils.copyProperties(model, data);
        return data;
    }

    /**
     * 发货单主表列表项
     */
    // @GetMapping("/opt")
    // public List<OptVO> opt(){
    // List<OptVO> data = this.deliveryService.opt();
    // return data;
    // }

    /**
     * 新增发货单主表
     *
     * @param req {@link DeliveryReq}
     * @return
     */
    @ApiOperation(value = "新增发货单主表")
    @Operation(value = "新增发货单主表")
    @PostMapping("/add")
//    @Permission("delivery:add")
    public Object add(@RequestBody @ApiParam(value = "新增请求bean") @Validated({Create.class}) DeliveryReq req,
                    @CurrentUser CacheUserVO user) {
        Delivery model = new Delivery();
        BeanUtils.copyProperties(req, model);
        // 发货单状态  1:初始化 2 已发货
        model.setStatus(1);
        model.setCreateId(user.getId());
        model.setCreateBy(user.getRealName());
        Dict dict = this.dictService.getByVal("addressOpt", model.getAddressId(), null);
        model.setAddressCn(dict.getName());
        Product product = this.productService.getById(req.getSecuritiesId());
        model.setSecurities(product.getSecurities());
        model.setPlanTotalBox(model.getPlanPar() * product.getBoxAmount() + model.getPlanBoxNum());
        model.setOrderNo(this.creadeOutOrderNo(model.getSecurities()));
        this.deliveryService.save(model);
        // 单号增加
        this.addOutOrderNo(model.getSecurities());
        return "";
    }

    @ApiOperation(value = "生成返检单号")
    @PostMapping("/createOrderNo")
    public String createOrderNo(@RequestBody @Valid CreateOrderNoReq req, @CurrentUser CacheUserVO user) {
        Product product = this.productService.getById(req.getSecuritiesId());
        String data = this.creadeOutOrderNo(product.getSecurities());
        return data;
    }

    public void addOutOrderNo(String securities) {
        String key = "out_num:" + securities;
        this.redisService.set(key, String.valueOf(Integer.parseInt(this.redisService.get(key)) + 1));
    }

    public String creadeOutOrderNo(String securities) {
        // 车间出库单号由系统自动生成，编号由“品名+部门编号+T2+3位数字编号”构成，Y211-1T2001
        // 车间出库单号
        String resp = null;
        String key = "out_num:" + securities;
        if (redisService.hasKey(key)) {
            resp = securities + "-" + String.format("%04d", Integer.parseInt(this.redisService.get(key)) + 1);
        } else {
            this.redisService.set(key, "0");
            resp = securities + "-" + String.format("%04d", 1);
        }
        return resp;
    }

    /**
     * 修改发货单主表H
     */
    @ApiOperation(value = "修改发货单主表")
    @Operation(value = "修改发货单主表")
    @PostMapping("/update")
//    @Permission("delivery:update")
    public Object update(@RequestBody @ApiParam(value = "修改请求bean") @Validated({Update.class}) DeliveryReq req,
                         @CurrentUser CacheUserVO user) {
        Delivery model = this.deliveryService.getById(req.getId());
        model.setPlanBoxNum(req.getPlanBoxNum());
        model.setPlanPar(req.getPlanPar());
        if (!model.getAddressId().equals(req.getAddressId())) {
            Dict dict = this.dictService.getByVal("addressOpt", model.getAddressId(), null);
            model.setAddressCn(dict.getName());
        }
        Product product = this.productService.getById(req.getSecuritiesId());
        model.setSecurities(product.getSecurities());
        model.setPlanTotalBox(model.getPlanPar() * product.getBoxAmount() + model.getPlanBoxNum());
        this.deliveryService.updateById(model);
        return "";
    }


    /**
     * 删除发货单主表
     */
    @ApiOperation(value = "删除发货单主表")
    @Operation(value = "删除发货单主表")
    @PostMapping("/delete")
//    @Permission("delivery:delete")
    public Object delete(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req, @CurrentUser CacheUserVO user) {
        Delivery model = this.deliveryService.getById(req.getId());
        // 验证是否相同租户
        // this.validTenant(user, model.getTenantId());
        // model.setDelFlag(Constants.STATUS_FORBIDDEN);
        // this.deliveryService.updateById(model);
        this.deliveryService.removeById(req.getId());
        return "";
    }

    @ApiOperation(value = "打印")
    @PostMapping("/print")
    public Object print(@RequestBody IdReq req, @CurrentUser CacheUserVO user) {
        this.deliveryService.print(req.getId(), user);
        return "";
    }

}
