package com.shkj.wms.controller.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.shkj.common.annotation.Log;
import com.shkj.common.annotation.RepeatSubmit;
import com.shkj.common.constant.RedisConstant;
import com.shkj.common.core.controller.BaseController;
import com.shkj.common.core.domain.Result;
import com.shkj.common.core.page.TableDataInfo;
import com.shkj.common.utils.DateUtils;
import com.shkj.common.utils.StringUtils;
import com.shkj.wms.bo.*;
import com.shkj.wms.config.ValidList;
import com.shkj.wms.domain.BaseBarcodesIn;
import com.shkj.wms.domain.BaseContainer;
import com.shkj.wms.domain.BusinDataTask;
import com.shkj.wms.domain.BusinDataTaskGoods;
import com.shkj.wms.service.*;
import com.shkj.wms.utils.JsonUtil;
import com.shkj.wms.vo.BaseContainerVo;
import com.shkj.wms.vo.BaseDeriveTraverseVo;
import com.shkj.wms.vo.BasePointDeviceVo;
import com.shkj.wms.vo.BusinDataTaskGoodsVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor(onConstructor_ =@Autowired)
@RestController
@RequestMapping("/wms/billin")
public class BusinBillInController extends BaseController {

    @Autowired
    IBusinBillheadService iBusinBillheadService;

    @Autowired
    IBaseBarcodesInService iBaseBarcodesInService;

    @Autowired
    IBusinDataTaskService iBusinDataTaskService;

    @Autowired
    IPutInOutStorageService iPutInOutStorageService;

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    IBaseContainerService iBaseContainerService;
    @Resource
    IBusinDataTaskGoodsService iBusinDataTaskGoodsService;

    /**
     * 人工下料，确认入库接口
     */
    @PostMapping("/saveBillTaskIn")
    @RepeatSubmit
    public Result<Boolean> saveBillTaskIn(@Valid @RequestBody BillTaskAddbo billTaskAddbo){
        if (billTaskAddbo.getContainerCode() == null){
            if (billTaskAddbo.getContainerCodes() == null){
                return Result.err().msg("无此治具号的容器");
            }
            BaseContainer one = iBaseContainerService.getOne(new LambdaQueryWrapper<BaseContainer>()
                    .eq(BaseContainer::getContainerCode, billTaskAddbo.getContainerCodes()));
            billTaskAddbo.setContainerCode(one.getId());
        }
        if(StringUtils.isNotEmpty(billTaskAddbo.getContaineckUpObjrCode()) && "2".equals(billTaskAddbo.getContaineckUpObjrCode())){
            String idArr = redisTemplate.opsForValue().get(RedisConstant.Replenishment).toString();
            String[] idArrs = idArr.split("_");
            billTaskAddbo.setStartPoint(idArrs[3]);
        }
        return iPutInOutStorageService.saveBillTaskIn(billTaskAddbo,"RG");
    }

    @GetMapping("/checkContainer")
    public Result<List<BaseBarcodesIn>> checkContainer(@NotNull String containerCode) {
        List<BaseBarcodesIn> baseBarcodesInList = new ArrayList<>();
        BaseContainer one = iBaseContainerService.getOne(new LambdaQueryWrapper<BaseContainer>()
                .eq(BaseContainer::getContainerCode, containerCode));


//        redisTemplate.opsForValue().set(RedisConstant.Replenishment, "10355_10_32292_Artificial01");


        String idArr = redisTemplate.opsForValue().get(RedisConstant.Replenishment).toString();
        String[] idArrs = idArr.split("_");
        if(ObjectUtils.isNotEmpty(one) && idArrs[2].equals(one.getId().toString())){
            List<BusinDataTaskGoodsVo> goodsVos = iBusinDataTaskGoodsService.selectBusinTaskGoodsByTaskCode(Long.valueOf(idArrs[0]));
            for (BusinDataTaskGoodsVo goodsVo : goodsVos) {
                baseBarcodesInList.add(iBaseBarcodesInService.getBaseBarcodesInByQrCode(goodsVo.getQrCode()).getData());
            }
        }
        return Result.ok().data(baseBarcodesInList);
    }

    /**
     * 自动入库流程(物料到位后，生成入库任务，待任务下发)
     */
    @PostMapping("/saveBusinBillTaskData")
    @RepeatSubmit
    public Result<Long> saveBusinBillTaskData(@Valid @RequestBody MachineHandAddBo bo){
        return iPutInOutStorageService.saveBusinBillTaskData(bo,null);
    }

    /**
     * 堆垛机入库完成后，增加库存
     */
    @PostMapping("/productDeposit")
    @RepeatSubmit
    public Result<Boolean> productDeposit(@RequestParam Long taskId){
        return iPutInOutStorageService.productDeposit(taskId);
    }



    /**
     * 传入任务ID，执行任务相关流程
     */
    @PostMapping("/exeTaskProcess")
    @RepeatSubmit
    public Result<String> saveBusinBillTaskData(BusinTaskExeBo bo){
        return iPutInOutStorageService.exeTaskPutinStorage(bo);
    }



    /**
     * 人工下料，入库计划管理接口
     */
    @GetMapping("/getBillInPlanData")
    @RepeatSubmit
    public TableDataInfo<BaseBarcodesIn> getBillInPlanData(BaseBarcodesInQueryBo bo)
    {
        startPage();
        List<BaseBarcodesIn> list =iBaseBarcodesInService.getBillInPlanData(bo);
        return getDataTable(list);
    }

    /**
     * App人工入库（出库异常区域），呼叫空治具，创建任务
     */
    @PostMapping("/callContainer")
    @RepeatSubmit
    public Result<Boolean> callContainer(@RequestBody BaseContainerCallBo  bo){
        return iBusinDataTaskService.insertBusinTask(bo);
    }

    /**
     * App人工入库，获取人工入库点位
     */
    @GetMapping("/getManualWarehousingPoint")
    @RepeatSubmit
    public Result<BasePointDeviceVo> getManualWarehousingPoint(){
        return iBusinDataTaskService.getManualWarehousingPoint();
    }

    /**
     * 补货入库:根据qrcode获取相关信息
     */
    @PostMapping("/getInfoByQrCode")
    public Result<List<BaseBarcodesIn>> getInfoByQrCode(@RequestBody String params){
        Map<String, String> stringStringMap = JsonUtil.JsonStrToMap(params);
        List<BaseBarcodesIn> baseBarcodesInList = new ArrayList<>();
        if(StringUtils.isNotEmpty(stringStringMap.get("barCode"))){
            List<BaseBarcodesIn> baseBarcodesIns = iBaseBarcodesInService.getBillInPlanData(new BaseBarcodesInQueryBo().setQrCode(stringStringMap.get("barCode")));
            if(ObjectUtils.isNotEmpty(baseBarcodesIns)){
                baseBarcodesInList.add(baseBarcodesIns.get(0));
            }
        }
        return Result.ok().data(baseBarcodesInList);
    }

    /**
     * App补货入库---治具出库
     */
    @GetMapping("/getReplenishmentAndOutbound")
    @RepeatSubmit
    public Result<Boolean> getReplenishmentAndOutbound(@RequestParam String startPoint,@RequestParam String barcodesList){
        BusinOutboundQueryBo bo = new BusinOutboundQueryBo();
        List<BasinBarcodeInAddBo> basinBarcodeInAddBoList = JSONArray.parseArray(barcodesList,BasinBarcodeInAddBo.class);
        bo.setStartPoint(startPoint);
        bo.setBarcodesList(basinBarcodeInAddBoList);

        return iBusinDataTaskService.getReplenishmentAndOutbound(bo);
    }


    /**
     * App补货入库---确认入库
     */
    @GetMapping("/saveReplenishmentBillTaskIn")
    @RepeatSubmit
    public Result<Boolean> saveReplenishmentBillTaskIn(BillTaskAddbo bo){
        return iPutInOutStorageService.saveBillTaskIn(bo,"RG");
    }

    /**
     * 根据派生判断是否属于同一套保险杠
     */
    @PostMapping("/queryderiveId")
    @RepeatSubmit
    public  Result<Boolean> queryderiveId(@RequestBody BillTaskAddbo billTaskAddbo){
        return  iPutInOutStorageService.queryderiveId(billTaskAddbo);
    }
    /**
     * 根据派生拿到当前保险杠一套应为几个
     */
    @PostMapping("/getnumberderive")
    @RepeatSubmit
    public  Result getnumberderive(@RequestBody BillTaskAddbo billTaskAddbo){

        return iPutInOutStorageService.getnumberderive(billTaskAddbo);
    }

    @GetMapping("/PLCAuto")
    public Result PLCAuto(){
        HashMap<String, Boolean> map = new HashMap<>();
        map.put("plcauto",false);
        if ((boolean) redisTemplate.opsForValue().get("PLCAuto")){
            map.put("plcauto",true);
        }
        return Result.ok().data(map);
    }

    /**
     * 出库异常点位呼叫AGV数量
     */
    @PostMapping("/callContainerCount")
    @RepeatSubmit
    public Result<Integer> callContainerCount(){
        return Result.ok().data(iBusinDataTaskService.callContainerCount());
    }

    /**
     * 出库异常点agv取货完成送往异常区(pc出库异常放货完成)
     */
    @PostMapping("/goAbnormal")
    @RepeatSubmit
    public Result goAbnormal(@RequestBody String allQrCode){
        Map data = JSONObject.parseObject(allQrCode);
        return iBusinDataTaskService.goAbnormal(data);
    }

    /**
     * 出库放货:呼叫空治具
     */
    @PostMapping("/CallAirFixture")
    @RepeatSubmit
    public Result CallAirFixture(@RequestBody String taskId){
        return iBusinDataTaskService.CallAirFixture(taskId);
    }

    /**
     * 平库出库呼叫agv
     */
    @PostMapping("/CallRCS")
    public Result CallRcs(@RequestBody BaseDeriveTraverseVo baseDeriveTraverseVo){
        return iBusinDataTaskService.CallRcs(baseDeriveTraverseVo);
    }

    /**
     * 出库放货:放货时查询是否是平库的库存
     */
    @PostMapping("/QueryBarCode")
    public Result QueryBarCode(@RequestBody String QrCode){
        Map<String, String> stringStringMap = JsonUtil.JsonStrToMap(QrCode);
        String qrCode = stringStringMap.get("QrCode");
        return iBusinDataTaskService.QueryBarCode(qrCode);
    }

 }
