package com.sy.coinage.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sy.coinage.app.req.OutboundReq;
import com.sy.coinage.app.req.ShopConfirmReq;
import com.sy.coinage.app.req.WareConfirmReq;
import com.sy.coinage.core.annotation.CurrentUser;
import com.sy.coinage.core.aop.annotation.Operation;
import com.sy.coinage.core.aop.annotation.Permission;
import com.sy.coinage.core.constants.BusinessEnum;
import com.sy.coinage.core.controller.BaseController;
import com.sy.coinage.core.exception.RetException;
import com.sy.coinage.core.interceptor.Create;
import com.sy.coinage.core.util.HttpClientUtil;
import com.sy.coinage.core.vo.CacheUserVO;
import com.sy.coinage.workshop.model.WorkshopOutbound;
import com.sy.coinage.workshop.model.WorkshopOutboundDetail;
import com.sy.coinage.workshop.req.OrderNoReq;
import com.sy.coinage.workshop.req.WorkshopOutboundReq;
import com.sy.coinage.workshop.service.IWorkshopOutboundDetailService;
import com.sy.coinage.workshop.service.IWorkshopOutboundService;
import com.sy.coinage.workshop.service.IWorkshopTransferService;
import com.sy.coinage.workshop.vo.WorkshopOutboundVO;
import io.netty.handler.timeout.ReadTimeoutException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
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 javax.validation.Valid;
import javax.validation.groups.Default;
import java.text.ParseException;
import java.util.List;

/**
 * -车间出库单据（库房解缴|）Controller
 */
@Slf4j
@Api(tags = "App-车间出库单据（库房解缴|）接口")
@RestController
@RequestMapping(value = "/app/shopOutbound")
public class AppWorkshopOutboundController extends BaseController {

    public  final String  outboundBeginEventUrl ="http://127.0.0.1:9995/relay/outbound/begin";

    public  final String  outboundEndEventUrl ="http://127.0.0.1:9995/relay/outbound/end";

    @Autowired
    private IWorkshopOutboundService workshopOutboundService;

    @Autowired
    private IWorkshopOutboundDetailService workshopOutboundDetailService;

    @Autowired
    private IWorkshopTransferService workshopTransferService;

    // =========== 车间出库
    @ApiOperation(value = "3.1 app添加车间解缴出库")
    @Operation(value = "app添加车间解缴出库")
    @PostMapping("/add")
    public Object add(@RequestBody @ApiParam(value = "新增请求bean") @Validated({Create.class}) WorkshopOutboundReq req,
                      @CurrentUser CacheUserVO user) throws ParseException {
        if (req.getAutoLs() == null && req.getManualLs() == null) {
            throw new ReadTimeoutException("扫描的rfid列表与手动录入rfid列表不能都为空");
        }
        this.workshopOutboundService.shopOut(req, user);
        return "";
    }

    @ApiOperation(value = "3.2 app添加车间内部出库")
    @Operation(value = "app添加车间内部出库")
    @PostMapping("/addInner")
//    @Permission("workshopOutbound:add")
    public Object addInner(@RequestBody @ApiParam(value = "新增请求bean") @Validated({Default.class}) WorkshopOutboundReq req,
                           @CurrentUser CacheUserVO user) throws ParseException {
        log.info("add Inner :添加车间内部出库 req:{}", req);
        if (req.getWareId() == null || req.getWareId() == 0) {
            throw new RetException("临时库id不能为空");
        }
//        this.workshopOutboundService.eliminateOut(req, user);
        this.workshopTransferService.eliminateOut(req, user);
        return "";
    }

    // =============总库入库


    @ApiOperation(value = "6.0 app获取所有解缴单号")
    @GetMapping("/list")
    public List<Object> shopOutboundList() {
        LambdaQueryWrapper<WorkshopOutbound> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(WorkshopOutbound::getOrderNo);
        // todo 由于总库获取解缴单可以是各部门的解缴单，因此不需要deptId条件，给注释掉
//        queryWrapper.eq(WorkshopOutbound::getDeptId, user.getDeptId());
        // 单据类型： 1: 解缴单  2: 返检单
        queryWrapper.eq(WorkshopOutbound::getOrderType, 1);
        // 状态:1.新建 2.已出库 3.已入库
        queryWrapper.eq(WorkshopOutbound::getStatus, 2);
        List<Object> data = this.workshopOutboundService.listObjs(queryWrapper);
        return data;
    }

    @ApiOperation(value = "6.1 app根据解缴单号，获取返检基本信息接口")
    @PostMapping("/getInfoByOrderNo")
    public WorkshopOutboundVO shopGetInfoByOrderNo(@RequestBody @Valid OrderNoReq req) {
        WorkshopOutboundVO data = new WorkshopOutboundVO();
        LambdaQueryWrapper<WorkshopOutbound> queryWrapper = new LambdaQueryWrapper<>();
        //<delete by hliu ,总库获取解缴单列表信息，不需要部门限定，因此删除部门条件>
//        queryWrapper.eq(WorkshopOutbound::getDeptId, user.getDeptId());
        //</delete>
        // 单据类型： 1: 解缴单  2: 返检单
        queryWrapper.eq(WorkshopOutbound::getOrderType, 1);
        // 单号
        queryWrapper.eq(WorkshopOutbound::getOrderNo, req.getOrderNo());
        // 状态:1.新建 2.已出库 3.已入库
        queryWrapper.eq(WorkshopOutbound::getStatus, 2);
        WorkshopOutbound model = this.workshopOutboundService.getOne(queryWrapper);
        BeanUtils.copyProperties(model, data);
        List<WorkshopOutboundDetail> list = workshopOutboundDetailService.list(new LambdaQueryWrapper<WorkshopOutboundDetail>().eq(WorkshopOutboundDetail::getOutId, model.getId()));
        data.setDetailList(list);
        return data;
    }

    @ApiOperation(value = "6.2.1 app总库解缴单入库选择库位事件接口")
    @PostMapping("/outboundBeginEvent")
    public Object outboundBeginEvent(@RequestBody @Valid OutboundReq req, @CurrentUser CacheUserVO user){
        log.info("6.2.1 app总库解缴单入库选择库位事件接口={}", req);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("thread  trigger light outboundBeginEventUrl is comming  ");
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("wareId",req.getWareId());
                    jsonObj.put("areaId",req.getAreaId());
                    HttpClientUtil.post(outboundBeginEventUrl, jsonObj.toJSONString());
                    log.info("thread outbound ware confirm begin event is ending ,url :{} ,json: {}",outboundBeginEventUrl,jsonObj.toJSONString());

                } catch (Exception e) {
                    log.error("outboundBeginEventUrl is error, req:{},error:{}",req,e.getMessage());
                }
            }
        }).start();

        return "";

    }

    @ApiOperation(value = "6.2 app总库解缴单入库确认")
    @PostMapping("/wareConfirm")
    public List<String> shopWareConfirm(@RequestBody @Valid ShopConfirmReq req, @CurrentUser CacheUserVO user) {
        log.info("6.2 app总库解缴单入库确认={}", req);
        if ((req.getManualArray() == null || req.getManualArray().size() == 0) && (req.getAutoArray() == null || req.getAutoArray().size() == 0)) {
            throw new RetException("自动扫描的集合与手动扫描的集合不能都为空");
        }
        List<String> data = this.workshopOutboundService.wareIn(req, user);

        //add by hliu date=20240226 触发灯控事件：总库解接单入库
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    log.info("thread  trigger light outboundEndEventUrl is comming  ");
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("wareId",req.getWareId());
                    jsonObj.put("areaId",req.getAreaId());
                    HttpClientUtil.post(outboundEndEventUrl, jsonObj.toJSONString());
                    log.info("thread outbound ware confirm end event is ending ,url :{} ,json: {}",outboundEndEventUrl,jsonObj.toJSONString());

                } catch (Exception e) {
                    log.error("outboundBeginEventUrl is error, req:{},error:{}",req,e.getMessage());
                }
            }
        }).start();

        return data;
    }

}
