/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.modules.quartz.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uhf.api.cls.Reader;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.basicdata.domain.BillType;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.repository.BillTypeRepository;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.businessdata.domain.AgvTask;
import com.youchain.businessdata.domain.Asn;
import com.youchain.businessdata.repository.AgvTaskRepository;
import com.youchain.businessdata.repository.AsnRepository;
import com.youchain.businessdata.service.AgvTaskService;
import com.youchain.businessdata.service.AsnService;
import com.youchain.exception.BadRequestException;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.system.repository.DeptRepository;
import com.youchain.rfid.RfidDocJava;
import com.youchain.utils.BaseStatus;
import com.youchain.utils.BizStatus;
import com.youchain.utils.UrlApi;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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 java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;


/**
 * 测试用
 * @author Liu Xue
 * @date 2019-01-08
 */
@Slf4j
@Service
@RestController
@RequestMapping("/api/test")
public class TestTask {
    @Autowired
    private AgvTaskRepository agvTaskRepository;
    @Autowired
    private PointRepository pointRepository;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private AsnRepository asnRepository;
    @Autowired
    private AsnService asnService;
    @Autowired
    private  AgvTaskService agvTaskService;

    private static final int MAX_TASK_COUNT = 4;
    private static final long TIMEOUT_MS = 600000; // 10分钟，以毫秒为单位
    private long lastTaskTime = System.currentTimeMillis();
    /** 占用库位*/
    /*@PostMapping("/startAsn")
    @AnonymousAccess*/
    @Transactional
    public ResponseEntity<Object> startAsn(String req){
        JSONArray data=new JSONArray();
        JSONObject jsonObject=JSONObject.parseObject(req);
        JSONArray billTypeArray=jsonObject.getJSONArray("billType");
        for (int i = 0; i < billTypeArray.size(); i++) {
            List<Asn> asnList=asnRepository.findByBillType(billTypeArray.getString(i));
            for (int j = 0; j < asnList.size(); j++) {
                Asn asn=asnList.get(j);
                ApiResult apiResult = asnService.startAsn(asn);
                data.add(apiResult);
            }
        }
        ApiResult apiResult=ApiResult.fail(200,"操作成功",null);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
    @PostMapping("/asnTask")
    @AnonymousAccess
    public ResponseEntity<Object> asnTask(){
        System.out.println("查询Task任务生成AgvTask入库任务");
        ApiResult apiResult = agvTaskService.addAgvAsn(BizStatus.RM_RK);
        return new ResponseEntity<>(apiResult, HttpStatus.valueOf(apiResult.getStatus()));
    }
//    @PostMapping("/asnPutaway")
//    @AnonymousAccess
    public void posApiUrl(String req){
        JSONObject requestJson=JSONObject.parseObject(req);
        UrlApi.containerIn=requestJson.getString("containerIn");
        UrlApi.containerOut=requestJson.getString("containerOut");
        UrlApi.submitMission=requestJson.getString("submitMission");
        UrlApi.sapIpPort=requestJson.getString("sapIpPort");

        System.out.println("更新地址");
        System.out.println(UrlApi.containerIn);
        System.out.println(UrlApi.containerOut);
        System.out.println(UrlApi.submitMission);
    }
    public void LinkOpenRfidDoor(String req){
        JSONObject requestJson=JSONObject.parseObject(req);
        RfidDocJava.POWER=requestJson.getIntValue("power");
        BaseStatus.DoorPoint_BCP_SUM=requestJson.getIntValue("bcp_rfid_sum");
        BaseStatus.DoorPoint_LX_SUM=requestJson.getIntValue("lx_rfid_sum");
        String err = RfidDocJava.linkOpen();
        if (!err.equals("MT_OK_ERR")){
            throw new BadRequestException(HttpStatus.NOT_IMPLEMENTED, "连接感应门失败:"+err);
        }
    }
    public void TimingSendAgvTask(){
        // 定时发送任务
        List<AgvTask> agvTasks=agvTaskRepository.findByTiming();
        for (int i = 0; i < agvTasks.size(); i++) {
            agvTaskService.sendAgvTaskImpl(agvTasks.get(i));
        }
    }
    public void posBaseStatus(String req){
        BaseStatus.Dept=deptRepository.getById(7l);

        JSONObject requestJson=JSONObject.parseObject(req);
        // 感应门终点编码
        String doorPointCodeEnd = requestJson.getString("DoorPointEnd");
        BaseStatus.DoorPoint=pointRepository.findByCode(doorPointCodeEnd);

        // 启动感应门 编码
        String DoorPointStart = requestJson.getString("DoorPointStart");
        BaseStatus.DoorPointEd=pointRepository.findByCode(DoorPointStart);
        // 料箱货架去 点位
        String LxZPointCode = requestJson.getString("LxZPoint");
        BaseStatus.LxZPoint=pointRepository.findByCode(LxZPointCode);
        // 感应门编码解析RFID规则 长度
        JSONObject rfidVerify = requestJson.getJSONObject("RfidVerify");
        BaseStatus.lengthVerifyList = JSONObject.parseArray(rfidVerify.getJSONArray("LengthList").toJSONString(),Long.class);

    }
    @Transactional
    public void asnPutaway(String req){
        synchronized (BaseStatus.Lock.rfid_SJ) {
            Point point=pointRepository.getById(BaseStatus.DoorPoint.getId());
            String st = point.getStorageType();
            if (st.equals("BTP")){
                agvTaskService.addTaskRfid(BizStatus.BCP);
            }else if (st.equals("LXZ")){
                agvTaskService.addTaskRfid(BizStatus.LX);
            }
        }
    }
}
