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.Dept;
import com.sy.coinage.sys.service.IDeptService;
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.IBaseInfoService;
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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * -rfid基础信息登记表Controller
 */
@Api(value = "rfid基础信息登记表接口", tags = {"rfid基础信息登记表接口"})
@RestController
@RequestMapping(value = "/baseInfo")
public class BaseInfoController extends BaseController {

    @Autowired
    private IBaseInfoService baseInfoService;

    @Autowired
    private IDeptService deptService;

    //=========pc接口
    @ApiOperation(value = "rfid基础信息登记列表")
    @PostMapping("/list")
    @ActiveFastJsonProfile(groups = "list", clazz = BaseInfo.class)
    public List<BaseInfo> list(@RequestBody BaseInfoListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<BaseInfo> queryWrapper = new LambdaQueryWrapper<>();
        List<BaseInfo> data = this.baseInfoService.list(queryWrapper);
        return data;
    }

    @ApiOperation(value = "rfid基础信息登记表分页列表")
    @PostMapping("/page")
    @ActiveFastJsonProfile(groups = "list", clazz = BaseInfo.class)
    public IPage<BaseInfo> page(@RequestBody BaseInfoListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<BaseInfo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.gt(BaseInfo::getStatus, 1); //将所有数据都显示
        queryWrapper.gt(BaseInfo::getId, 0); // 没条件时 排序生效
        queryWrapper.eq(req.getDeptId() != null && req.getDeptId() > 0, BaseInfo::getDeptId,
                req.getDeptId());
        if (req.getQualityStatus() != null && req.getQualityStatus() > 0) {
            if (req.getQualityStatus().intValue() == 2) {
                queryWrapper.and(qw -> {
                    qw.eq(BaseInfo::getQualityStatus, req.getQualityStatus())
                            .or().isNull(BaseInfo::getQualityStatus);
                });
            } else {
                queryWrapper.eq(BaseInfo::getQualityStatus, req.getQualityStatus());
            }
        }
        queryWrapper.eq(req.getLocWareId() != null && req.getLocWareId() > 0,
                BaseInfo::getLocWareId, req.getLocWareId());
        queryWrapper.eq(req.getSecuritiesId() != null && req.getSecuritiesId() > 0, BaseInfo::getSecuritiesId, req.getSecuritiesId());
        if (req.getStartDate() != null) {
            queryWrapper.ge(BaseInfo::getWeightDate, DateUtils.getDayStartTime(req.getStartDate()));
        }
        if (req.getEndDate() != null) {
            queryWrapper.le(BaseInfo::getWeightDate, DateUtils.getDayEndTime(req.getEndDate()));
        }
        if (req.getDeliveryStartDate() != null) {
            queryWrapper.le(BaseInfo::getDeliveryTime, DateUtils.getDayStartTime(req.getDeliveryStartDate()));
        }
        if (req.getDeliveryEndDate() != null) {
            queryWrapper.ge(BaseInfo::getDeliveryTime, DateUtils.getDayEndTime(req.getDeliveryEndDate()));
        }
        if (StringUtils.isNotBlank(req.getCrown())) {
            queryWrapper.eq(BaseInfo::getSerialNumber, req.getCrown());

        }
        //按照创建时间倒序排列
        queryWrapper.orderByDesc(BaseInfo::getCreateTime);
        Page<BaseInfo> page = new Page<>(req.getPage(), req.getRows());
        IPage<BaseInfo> data = this.baseInfoService.queryPageList(page, queryWrapper);
        return data;
    }

    @ApiOperation(value = "rfid基础信息登记表分页列表")
    @PostMapping("/page1")
    @ActiveFastJsonProfile(groups = "list", clazz = BaseInfo.class)
    public IPage<BaseInfo> page1(@RequestBody BaseInfoListReq req, @CurrentUser CacheUserVO user) {

        Dept dept = this.deptService.getById(user.getDeptId());
        LambdaQueryWrapper<BaseInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(BaseInfo::getId, 0); // 没条件时 排序生效
        queryWrapper.and(qw -> {
            qw.eq(BaseInfo::getLocWareId, dept.getRemark())
                    .or().isNull(BaseInfo::getLocWareId);
        });
        if (req.getQualityStatus() != null && req.getQualityStatus() > 0) {
            if (req.getQualityStatus().intValue() == 2) {
                queryWrapper.and(qw -> {
                    qw.eq(BaseInfo::getQualityStatus, req.getQualityStatus())
                            .or().isNull(BaseInfo::getQualityStatus);
                });
            } else {
                queryWrapper.eq(BaseInfo::getQualityStatus, req.getQualityStatus());
            }
        }
        queryWrapper.eq(req.getSecuritiesId() != null && req.getSecuritiesId() > 0, BaseInfo::getSecuritiesId, req.getSecuritiesId());
        if (req.getStartDate() != null) {
            queryWrapper.ge(BaseInfo::getWeightDate, DateUtils.getDayStartTime(req.getStartDate()));
        }
        if (req.getEndDate() != null) {
            queryWrapper.le(BaseInfo::getWeightDate, DateUtils.getDayEndTime(req.getEndDate()));
        }
        if (req.getDeliveryStartDate() != null) {
            queryWrapper.le(BaseInfo::getDeliveryTime, DateUtils.getDayStartTime(req.getDeliveryStartDate()));
        }
        if (req.getDeliveryEndDate() != null) {
            queryWrapper.ge(BaseInfo::getDeliveryTime, DateUtils.getDayEndTime(req.getDeliveryEndDate()));
        }
        if (StringUtils.isNotBlank(req.getCrown())) {
            queryWrapper.eq(BaseInfo::getSerialNumber, req.getCrown());

        }
        //按照创建时间倒序排列
        queryWrapper.orderByDesc(BaseInfo::getCreateTime);
        Page<BaseInfo> page = new Page<>(req.getPage(), req.getRows());
        IPage<BaseInfo> data = this.baseInfoService.queryPageList(page, queryWrapper);
        return data;
    }

    @ApiOperation(value = "新拍记录分页列表")
    @PostMapping("/newPalletPage")
    @ActiveFastJsonProfile(groups = "list", clazz = BaseInfo.class)
    public IPage<BaseInfo> newPalletPage(@RequestBody BaseInfoListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<BaseInfo> queryWrapper = new LambdaQueryWrapper<>();
        // 绑定rfid数据的来源类型： 1:封包线整拍数据 2.封包线非整拍数据
        // 大于2 = 3:拆包后新构成的rfid 4:原有物料整拍绑定 5.原有物料整拍绑定（原始非整拍）
        queryWrapper.gt(BaseInfo::getOriginType, 2);
        queryWrapper.orderByDesc(BaseInfo::getCreateTime);
        Page<BaseInfo> page = new Page<>(req.getPage(), req.getRows());
        IPage<BaseInfo> data = this.baseInfoService.page(page, queryWrapper);
        if (data.getRecords() != null && data.getRecords().size() > 0) {
            // 查询已拆包的
            List<BaseInfo> oldList = this.getOldList();
            for (BaseInfo vo : data.getRecords()) {
                Optional<BaseInfo> old = oldList.stream().filter(item -> item.getSerialNumber().equals(vo.getSerialNumber())).findFirst();
                if (old.isPresent()) {
                    vo.setOldRfid(old.get().getRfid());
                    vo.setOldCrownBetween(old.get().getCrownBetween());
                }
            }
        }
        return data;
    }

    private List<BaseInfo> getOldList() {
        LambdaQueryWrapper<BaseInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseInfo::getUnpackageStatus, 2);
        return this.baseInfoService.list(queryWrapper);
    }

    @ApiOperation(value = "修改基础信息质量状态")
    @Operation(value = "修改基础信息质量状态")
    @PostMapping("/updateQuality")
//    @Permission("baseInfo:update")
    public Object updateQuality(@RequestBody @ApiParam(value = "修改质量状态请求bean") @Valid QualityReq req,
                                @CurrentUser CacheUserVO user) {
        BaseInfo model = this.baseInfoService.getById(req.getId());
        model.setQualityStatus(req.getQualityStatus());
        model.setQualityTime(new Date());
        this.baseInfoService.updateById(model);
        return "";
    }


    /**
     * rfid基础信息登记表详情
     */
    @ApiOperation(value = "rfid基础信息登记表-通过ID查询单条数据")
    @PostMapping("/get")
    @ActiveFastJsonProfile(groups = "get", clazz = BaseInfo.class)
    public BaseInfoVO get(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req) {
        BaseInfoVO data = null;
        BaseInfo model = this.baseInfoService.getById(req.getId());
        data = new BaseInfoVO();
        BeanUtils.copyProperties(model, data);
        return data;
    }


    @ApiOperation(value = "新增rfid基础信息登记表")
    @Operation(value = "新增rfid基础信息登记表")
    @PostMapping("/add")
//    @Permission("baseInfo:add")
    public Object add(@RequestBody @ApiParam(value = "新增请求bean") @Validated({Create.class}) BaseInfoReq req,
                    @CurrentUser CacheUserVO user) {
        this.baseInfoService.add(req, user);
        return "";
    }

    /**
     * 修改rfid基础信息登记表
     */
    @ApiOperation(value = "修改rfid基础信息登记表")
    @Operation(value = "修改rfid基础信息登记表")
    @PostMapping("/update")
    public Object update(@RequestBody @ApiParam(value = "修改请求bean") @Validated({Update.class}) BaseInfoReq req,
                    @CurrentUser CacheUserVO user) {
//        BaseInfo model = this.baseInfoService.getById(req.getId());
//        BeanUtils.copyProperties(req, model);
//        model.setCrownBetween(model.getCrownPrefix() +"-"+ model.getCrownFrom() + " 至 "
//                + model.getCrownPrefix() +"-"+ model.getCrownTo());
//        this.baseInfoService.updateById(model);
        this.baseInfoService.updateRfidInfo(req);
        return "";
    }
    /**
     * 删除rfid基础信息登记表
     */
    @ApiOperation(value = "删除rfid基础信息登记表")
    @Operation(value = "删除rfid基础信息登记表")
    @PostMapping("/delete")
    @Permission("baseInfo:delete")
    public Object delete(@RequestBody @ApiParam(value = "主键请求bean") @Valid IdReq req, @CurrentUser CacheUserVO user) {
        BaseInfo model = this.baseInfoService.getById(req.getId());
        // model.setDelFlag(Constants.STATUS_FORBIDDEN);
        // this.baseInfoService.updateById(model);
        this.baseInfoService.removeById(req.getId());
        return "";
    }

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

    @ApiOperation(value = "打印空白标签")
    @GetMapping("/printBlankTag")
    public Object printBlankTag() {
        this.baseInfoService.printBlankTag();
        return "";
    }

}
