package com.chinaitop.depot.intelligent.IntelligentDetection.service;

import com.chinaitop.depot.intelligent.IntelligentDetection.mapper.TTimingTaskHistoryMapper;
import com.chinaitop.depot.intelligent.IntelligentDetection.model.TTimingTask;
import com.chinaitop.depot.intelligent.IntelligentDetection.model.TTimingTaskHistory;
import com.chinaitop.depot.intelligent.basicdata.model.BasicStorehouse;
import com.chinaitop.depot.intelligent.basicdata.model.TJctable;
import com.chinaitop.depot.intelligent.basicdata.service.BasicStorehouseService;
import com.chinaitop.depot.intelligent.basicdata.service.QuantityService;
import com.chinaitop.depot.intelligent.grainNumberMonitor.service.MonitorWarningService;
import com.chinaitop.depot.intelligent.socket.SocketClient;
import com.chinaitop.depot.intelligent.utils.ConstUtils;
import com.chinaitop.depot.intelligent.utils.DateUtils;
import com.chinaitop.depot.intelligent.utils.HexConvertUtils;
import com.chinaitop.depot.intelligent.utils.UuidUtils;
import com.google.common.collect.Lists;
import com.unissoft.model.TypeEnum;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wzx
 * @time 2018/6/9
 */
@Component("testTask")
public class TestTask extends AbstractTask {

    @Value("${gas-org-ids}")
    private String orgIds = "386";

    @Resource
    TTimingTaskService tTimingTaskService;

    @Resource
    private ConstUtils constUtils;

    @Resource
    private SocketClient socketClient;

    @Resource
    private TTimingTaskHistoryMapper tTimingTaskHistoryMapper;

    @Resource
    private MonitorWarningService monitorWarningService;

    @Resource
    private QuantityService quantityService;

    @Resource
    private BasicStorehouseService basicStorehouseService;

    private Logger logger = LoggerFactory.getLogger(TestTask.class);

    @PostConstruct
    public void init() {
        this.cronExpression = "0/2 * * * * ? ";
    }

    @Override
    protected void executeInternal(JobExecutionContext context) {
        logger.info("检测任务开始执行");
        try {
            String jobId = context.getTrigger().getJobKey().getName();
            TTimingTask tTimingTask = tTimingTaskService.getById(jobId);
            //要检测的仓房
            String cfCodes = tTimingTask.getvCfCode();
            //要检测的类型0粮温，1虫害，2气体，3能耗，4数量，5水分，6气象
            String type = tTimingTask.gettCategory();
            String orgId = tTimingTask.getOrgId();
            //存储检测操作历史数据
            ArrayList<TTimingTaskHistory> taskHistorys = Lists.newArrayList();
            String[] sArray = cfCodes.split(",");
            if (StringUtils.isNotBlank(cfCodes) && type.equals("0")) {
                for (String cfCode : sArray) {
                    // 0X02粮情数据采集,仓房号,设备编号若为0则控全部
                    String dir = constUtils.directiveJoint(constUtils.GRAIN_TYPE, cfCode, "0"); // TODO 暂时未接入设备编号
                    // 16进制字符串转byte数组
                    byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                    // 发送指令
                    String s = socketClient.startClient(bytes);
                    // 0：失败；1：成功；2：设备通讯异常；3：设备故障；4：未知原因; 5: 本地模式(有的设备有本地模式，即无法远程控制)
                    BasicStorehouse basicStorehouse = basicStorehouseService.queryOrgNameOrCode(orgId, cfCode);//获取仓房名称
                    TTimingTaskHistory taskHistory = saveTaskHistory(tTimingTask, "", s, "粮温", basicStorehouse == null ? "" : basicStorehouse.getStorehouseName());
                    taskHistory.setOrgId(orgId);
                    taskHistorys.add(taskHistory);
                }
            } else if (StringUtils.isNotBlank(cfCodes) && type.equals("1")) {
                for (String cfCode : sArray) {
                    // 0X02粮情数据采集,仓房号,设备编号若为0则控全部
                    String dir = constUtils.directiveJoint(constUtils.WORM_TYPE, cfCode, "0"); // TODO 暂时未接入设备编号
                    // 16进制字符串转byte数组
                    byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                    // 发送指令
                    String s = socketClient.startClient(bytes);
                    BasicStorehouse basicStorehouse = basicStorehouseService.queryOrgNameOrCode(orgId, cfCode);
                    TTimingTaskHistory taskHistory = saveTaskHistory(tTimingTask, "", s, "虫害", basicStorehouse == null ? "" : basicStorehouse.getStorehouseName());
                    taskHistory.setOrgId(orgId);
                    taskHistorys.add(taskHistory);
                }
            } else if (StringUtils.isNotBlank(cfCodes) && type.equals("2")) {
                List<String> list = Arrays.asList(orgIds.split(","));
                String gasType = "";
                for (String cfCode : sArray) {
                    if (list.contains(orgId)) {
                        gasType = constUtils.MGAS_TYPE;
                    } else {
                        gasType = constUtils.GAS_TYPE;
                    }
                    if (StringUtils.isNotBlank(cfCode)) {
                        // 数据采集,仓房号,设备编号若为0则控全部
                        String dir = constUtils.directiveJoint(constUtils.F_EXTENT, constUtils.SUB_P, gasType, cfCode, "");
                        // 16进制字符串转byte数组
                        byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                        // 发送指令
                        String s = socketClient.startClient(bytes);
                        BasicStorehouse basicStorehouse = basicStorehouseService.queryOrgNameOrCode(orgId, cfCode);
                        TTimingTaskHistory taskHistory = saveTaskHistory(tTimingTask, "", s, "气体", basicStorehouse == null ? "" : basicStorehouse.getStorehouseName());
                        taskHistory.setOrgId(orgId);
                        taskHistorys.add(taskHistory);
                    }
                }
            } else if (StringUtils.isNotBlank(cfCodes) && type.equals("3")) {
                StringBuffer buffered = new StringBuffer();
                buffered.append(ConstUtils.HEADER);// 起始标志
                buffered.append(ConstUtils.F_EXTENT);// 报文体长度
                buffered.append(ConstUtils.ENER_TYPE);// TYPE类型
                buffered.append(ConstUtils.F_SUB_P);// 分包相关
                buffered.append("0000000000");// 所有仓房
                String dir = buffered.toString();
                // 16进制字符串转byte数组
                byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                // 发送指令
                String s = socketClient.startClient(bytes);
                BasicStorehouse basicStorehouse = basicStorehouseService.queryOrgNameOrCode(orgId, "");
                TTimingTaskHistory taskHistory = saveTaskHistory(tTimingTask, basicStorehouse.getDepotName(), s, "能耗", "");
                taskHistory.setOrgId(orgId);
                taskHistorys.add(taskHistory);
            } else if (StringUtils.isNotBlank(cfCodes) && type.equals("5")) {
                for (String cfCode : sArray) {
                    //水分数据采集,仓房号,设备编号若为0则控全部
                    String dir = constUtils.directiveJoint(constUtils.DEW_TYPE, cfCode, "0"); // TODO 暂时未接入设备编号
                    // 16进制字符串转byte数组
                    byte[] bytes = HexConvertUtils.hexStringToByte(dir);
                    // 发送指令
                    String s = socketClient.startClient(bytes);
                    // 0：失败；1：成功；2：设备通讯异常；3：设备故障；4：未知原因; 5: 本地模式(有的设备有本地模式，即无法远程控制)
                    BasicStorehouse basicStorehouse = basicStorehouseService.queryOrgNameOrCode(orgId, cfCode);
                    TTimingTaskHistory taskHistory = saveTaskHistory(tTimingTask, "", s, "水分", basicStorehouse == null ? "" : basicStorehouse.getStorehouseName());
                    taskHistory.setOrgId(orgId);
                    taskHistorys.add(taskHistory);
                }
            } else if (type.equals("6")) {
                //7E 0005 06 0101 0000000000
                byte[] b = new byte[11];
                b[0] = 0x7E;
                b[1] = 0x00;
                b[2] = 0x05;
                b[3] = 0X06;
                b[4] = 0x01;
                b[5] = 0x01;
                b[6] = 0x00;
                b[7] = 0x00;
                b[8] = 0x00;
                b[9] = 0x00;
                b[10] = 0x00;
                // 发送指令
                String s = socketClient.startClient(b);
                // 0：失败；1：成功；2：设备通讯异常；3：设备故障；4：未知原因; 5: 本地模式(有的设备有本地模式，即无法远程控制)
                BasicStorehouse basicStorehouse = basicStorehouseService.queryOrgNameOrCode(orgId, "");
                TTimingTaskHistory taskHistory = saveTaskHistory(tTimingTask, basicStorehouse.getDepotName(), s, "气象", "");
                taskHistory.setOrgId(orgId);
                taskHistorys.add(taskHistory);
            } else if (StringUtils.isNotBlank(cfCodes) && type.equals("4")) {
                List<String> cfs = Arrays.asList(cfCodes.split(","));
                List<TJctable> byCodes = quantityService.getByCodes(cfs);
                if (byCodes != null && byCodes.size() > 0) {
                    List<String> tcfs = byCodes.stream().map(t -> t.getvCfCode()).collect(Collectors.toList());
                    List<String> wss = byCodes.stream().map(t -> t.getvWsSrc()).collect(Collectors.toList());
                    List<String> cfcodes = byCodes.stream().map(t -> t.getvRemark()).collect(Collectors.toList());
                    //数量检测
                    for (int i = 0; i < tcfs.size(); i++) {
                        String cf = tcfs.get(i);
                        String ws = wss.get(i);
                        String cfcode = cfcodes.get(i);
                        String s = monitorWarningService.sendNumberMonitor(cf, ws);
                        BasicStorehouse basicStorehouse = basicStorehouseService.queryOrgNameOrCode(orgId, cfcode);
                        TTimingTaskHistory taskHistory = saveTaskHistory(tTimingTask, "", s, "数量", basicStorehouse == null ? "" : basicStorehouse.getStorehouseName());
                        taskHistory.setOrgId(orgId);
                        taskHistorys.add(taskHistory);
                    }
                }
            } else if (StringUtils.isNotBlank(cfCodes) && type.equals("7")) {
                //数量结果获取
                List<String> cfs = Arrays.asList(cfCodes.split(","));
                List<TJctable> byCodes = quantityService.getByCodes(cfs);
                if (byCodes != null && byCodes.size() > 0) {
                    List<String> tcfs = byCodes.stream().map(t -> t.getvCfCode()).collect(Collectors.toList());
                    List<String> wss = byCodes.stream().map(t -> t.getvWsSrc()).collect(Collectors.toList());
                    List<String> cfcodes = byCodes.stream().map(t -> t.getvRemark()).collect(Collectors.toList());
                    for (int i = 0; i < tcfs.size(); i++) {
                        String cf = tcfs.get(i);//设备code
                        String ws = wss.get(i);
                        String cfcode = cfcodes.get(i); //仓房code
                        String s = monitorWarningService.getmeasureweight(cfcode, cf, tTimingTask.gettUpdatePerson(), orgId, ws);
                        BasicStorehouse basicStorehouse = basicStorehouseService.queryOrgNameOrCode(orgId, cfcode);
                        TTimingTaskHistory taskHistory = saveTaskHistory(tTimingTask, "", s, "数量", basicStorehouse == null ? "" : basicStorehouse.getStorehouseName());
                        taskHistory.setOrgId(orgId);
                        taskHistorys.add(taskHistory);
                    }
                }
            }
            tTimingTaskHistoryMapper.insertBatch(taskHistorys);
        } catch (Exception e) {
            logger.info("检测任务执行中断");
        }
        logger.info("检测任务执行结束");
    }

    private TTimingTaskHistory saveTaskHistory(TTimingTask tTimingTask, String kdname, String s, String type, String cfName) {
        TTimingTaskHistory taskHistory = new TTimingTaskHistory();
        taskHistory.setId(UuidUtils.getCode());
        taskHistory.settId(tTimingTask.gettId());
        taskHistory.settUpdateTime(DateUtils.getDate());
        taskHistory.settDetectionDesc(tTimingTask.gettDetectionDesc());
        taskHistory.settDetectionCron(tTimingTask.gettDetectionCron());
        taskHistory.setvCfCode(cfName.equals("") ? kdname : cfName);
        taskHistory.settCategory(tTimingTask.gettCategory());
        String remark = "";
        if (s.contains("7E")) {
            String substring = s.substring(s.length() - 2, s.length());
            if ("00".equals(substring))
                remark = cfName.equals("") ? kdname + type + "执行" + TypeEnum.S_NUL.getDesc() : cfName + "号仓" + type + "执行" + TypeEnum.S_NUL.getDesc();// 失败
            else if ("01".equals(substring))
                remark = cfName.equals("") ? kdname + type + "执行" + TypeEnum.S_SOH.getDesc() : cfName + "号仓" + type + "执行" + TypeEnum.S_SOH.getDesc();// 成功
            else if ("02".equals(substring))
                remark = cfName.equals("") ? kdname + type + "执行" + TypeEnum.S_STX.getDesc() : cfName + "号仓" + type + "执行" + TypeEnum.S_STX.getDesc();// 设备通讯异常
            else if ("03".equals(substring))
                remark = cfName.equals("") ? kdname + type + "执行" + TypeEnum.S_ETX.getDesc() : cfName + "号仓" + type + "执行" + TypeEnum.S_ETX.getDesc();// 设备故障
            else if ("04".equals(substring))
                remark = cfName.equals("") ? kdname + type + "执行" + TypeEnum.S_EOT.getDesc() : cfName + "号仓" + type + "执行" + TypeEnum.S_EOT.getDesc();// 未知原因
            else if ("05".equals(substring))
                remark = cfName.equals("") ? kdname + type + "执行" + TypeEnum.S_2D_SOH.getDesc() : cfName + "号仓" + type + "执行" + TypeEnum.S_2D_SOH.getDesc();// 本地模式,无法远程控制
        } else if (type.equals("数量")) {
            remark = s;
        } else {
            remark = type + "检测失败";// 其它错误
        }
        taskHistory.settRemark(remark);
        return taskHistory;
    }

}

