package com.sy.coinage.workshop.controller;

import com.sy.coinage.core.exception.RetException;
import com.sy.coinage.core.redis.RedisService;
import com.sy.coinage.core.util.DateUtils;
import com.sy.coinage.sys.req.DeptReq;
import com.sy.coinage.workshop.req.vo.BaseInfoVO;
import com.sy.coinage.workshop.service.IBaseInfoService;
import com.sy.coinage.workshop.service.IProductService;
import com.sy.coinage.workshop.service.IWorkshopOutboundDetailService;
import io.netty.handler.timeout.ReadTimeoutException;
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.*;

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

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * -车间出库单据（库房解缴|返检单据|）Controller
 */
@Api(value = "车间出库单据（库房解缴|返检单据|）接口", tags = {"车间出库单据（库房解缴|返检单据|）接口"})
@RestController
@RequestMapping(value = "/workshopOutbound")
public class WorkshopOutboundController extends BaseController {

    @Autowired
    private IWorkshopOutboundService workshopOutboundService;

    @Autowired
    private IWorkshopOutboundDetailService workshopOutboundDetailService;

    @Autowired
    private IProductService productService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IBaseInfoService baseInfoService;

    //=========pc接口

    /**
     * 车间出库单据（库房解缴|返检单据|）分页列表
     */
    @ApiOperation(value = "车间出库单据（库房解缴|返检单据|）分页列表")
    @PostMapping("/page")
    @ActiveFastJsonProfile(groups = "list", clazz = WorkshopOutbound.class)
    public IPage<WorkshopOutbound> page(@RequestBody WorkshopOutboundListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<WorkshopOutbound> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(req.getOrderNo()), WorkshopOutbound::getOrderNo, req.getOrderNo());
        queryWrapper.eq(req.getSecuritiesId() != null && req.getSecuritiesId() > 0, WorkshopOutbound::getSecuritiesId, req.getSecuritiesId());
        if (req.getCreateTime() != null && StringUtils.isNotBlank(String.valueOf(req.getCreateTime()))) {
            queryWrapper.between(WorkshopOutbound::getCreateTime, DateUtils.getDayStartTime(req.getCreateTime()), DateUtils.getDayEndTime(req.getCreateTime()));
        }
        queryWrapper.orderByDesc(WorkshopOutbound::getId);
        Page<WorkshopOutbound> page = new Page<>(req.getPage(), req.getRows());
        IPage<WorkshopOutbound> data = this.workshopOutboundService.page(page, queryWrapper);
        return data;
    }

    @ApiOperation(value = "车间出库单据已完成列表/用于返检")
    @GetMapping("/finishList")
    @ActiveFastJsonProfile(groups = "finishList", clazz = WorkshopOutbound.class)
    public List<WorkshopOutbound> allInList(@CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<WorkshopOutbound> queryWrapper = new LambdaQueryWrapper<>();
        // 单据类型： 1: 解缴单  2: 返捡单
        queryWrapper.eq(WorkshopOutbound::getOrderType, 1);
        // 状态:1.新建 2.已出库 3.已入库
        queryWrapper.eq(WorkshopOutbound::getStatus, 3);
        List<WorkshopOutbound> list = this.workshopOutboundService.list(queryWrapper);
        List<WorkshopOutbound> data = list.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(item -> item.getDeptId()))),
                        ArrayList::new)
                );
        return data;
    }

    @ApiOperation(value = "车间出库单据已完成品名列表/用于返检")
    @GetMapping("/securitiesList")
    @ActiveFastJsonProfile(groups = "securitiesList", clazz = WorkshopOutbound.class)
    public List<WorkshopOutbound> securitiesList(@CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<WorkshopOutbound> queryWrapper = new LambdaQueryWrapper<>();
        // 单据类型： 1: 解缴单  2: 返捡单
        queryWrapper.eq(WorkshopOutbound::getOrderType, 1);
        // 状态:1.新建 2.已出库 3.已入库
        queryWrapper.eq(WorkshopOutbound::getStatus, 3);
        queryWrapper.eq(WorkshopOutbound::getDeptId, user.getDeptId());
        List<WorkshopOutbound> list = this.workshopOutboundService.list(queryWrapper);
        List<WorkshopOutbound> data = list.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(item -> item.getDeptId()))),
                        ArrayList::new)
                );
        return data;
    }

    @ApiOperation(value = "根据rfid获取详细信息")
    @PostMapping("/loadByRfid")
    public List<BaseInfoVO> loadByRfid(@RequestBody @Valid RfidListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<BaseInfo> queryWrapper = new LambdaQueryWrapper<>();
        for (BaseInfoVO vo : req.getDetailList()) {
            if (vo.getId() == null || vo.getId().intValue() == 0) {
                // 验证是否重复
                long count = this.workshopOutboundDetailService.myCount(vo.getSerialNumber());
                if (count > 0) {
                    throw new RetException("编号" + vo.getSerialNumber() + "已存在其他返检单中");
                }
                queryWrapper.clear();
                queryWrapper.eq(BaseInfo::getSerialNumber, vo.getSerialNumber());
                // 生命周期状态:1初始登记 2:车间入库 3:车间出库 4:总库入库  5:主库抽检出库 6.车间抽检入库确认 7.车间抽检出库8 主库抽检返回确认 9返捡总库出库 10:返捡车间确认 11拆包 12：已发货 13:返回机台
                queryWrapper.and(wq -> {
                    wq.eq(BaseInfo::getStatus, 4).or().eq(BaseInfo::getStatus, 8).or().eq(BaseInfo::getStatus, 11);
                });
                queryWrapper.orderByAsc(BaseInfo::getId);
                Page<BaseInfo> page = new Page<>(1, 1);
                IPage<BaseInfo> resp = this.baseInfoService.page(page, queryWrapper);
                if (resp.getRecords() != null && resp.getRecords().size() > 0) {
                    BeanUtils.copyProperties(resp.getRecords().get(0), vo);
                }
//                BaseInfo info = this.baseInfoService.getOne(queryWrapper);
            }
        }
        return req.getDetailList();
    }

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

    @ApiOperation(value = "创建返检任务")
    @Operation(value = "创建返检任务")
    @PostMapping("/add")
    public Object add(
            @RequestBody @ApiParam(value = "新增请求bean") @Validated({Create.class}) WorkshopOutboundAddReq req,
            @CurrentUser CacheUserVO user) {
        this.workshopOutboundService.create(req, user);
        return "";
    }

    @ApiOperation(value = "修改返检任务")
    @Operation(value = "修改返检任务")
    @PostMapping("/update")
    public Object update(
            @RequestBody @ApiParam(value = "新增请求bean") @Validated({Update.class}) WorkshopOutboundAddReq req,
            @CurrentUser CacheUserVO user) {
        this.workshopOutboundService.update(req, user);
        return "";
    }


    /**
     * 车间出库单据（库房解缴|返检单据|）详情
     */
    @ApiOperation(value = "车间出库单据（库房解缴|返检单据|）-通过ID查询单条数据")
    @PostMapping("/get")
    @ActiveFastJsonProfile(groups = "get", clazz = WorkshopOutbound.class)
    public WorkshopOutboundVO get(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req) {
        WorkshopOutboundVO data = null;
        WorkshopOutbound model = this.workshopOutboundService.getById(req.getId());
        data = new WorkshopOutboundVO();
        BeanUtils.copyProperties(model, data);
        return data;
    }

    @ApiOperation(value = "车间出库单据（库房解缴|返检单据|）-通过ID查询单条数据")
    @PostMapping("/getBack")
    @ActiveFastJsonProfile(groups = "get", clazz = WorkshopOutbound.class)
    public WorkshopOutboundBackVO getBack(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req) {
        WorkshopOutboundBackVO data = null;
        WorkshopOutbound model = this.workshopOutboundService.getById(req.getId());
        data = new WorkshopOutboundBackVO();
        BeanUtils.copyProperties(model, data);
        List<BaseInfoVO> list = workshopOutboundDetailService.listVO(model.getId());
        data.setDetailList(list);
        return data;
    }


    /**
     * 删除车间出库单据（库房解缴|返检单据|）
     */
    @ApiOperation(value = "删除车间出库单据（库房解缴|返检单据|）")
//    @Operation(value = "删除车间出库单据（库房解缴|返检单据|）")
    @PostMapping("/delete")
//    @Permission("workshopOutbound:delete")
    public Object delete(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req, @CurrentUser CacheUserVO user) {
        this.workshopOutboundService.delete(req.getId());
        return "";
    }

}
