package com.chinaitop.depot.intelligent.grainNumberMonitor.service.impl;

import com.chinaitop.depot.intelligent.grainNumberMonitor.mapper.TNumberWarningHistoryMapper;
import com.chinaitop.depot.intelligent.grainNumberMonitor.mapper.TNumberWarningMapper;
import com.chinaitop.depot.intelligent.grainNumberMonitor.model.TNumberWarning;
import com.chinaitop.depot.intelligent.grainNumberMonitor.model.TNumberWarningExample;
import com.chinaitop.depot.intelligent.grainNumberMonitor.model.TNumberWarningHistory;
import com.chinaitop.depot.intelligent.grainNumberMonitor.model.TNumberWarningHistoryExample;
import com.chinaitop.depot.intelligent.grainNumberMonitor.service.MonitorWarningService;
import com.chinaitop.depot.intelligent.utils.DateUtils;
import com.chinaitop.depot.intelligent.utils.UuidUtils;
import com.chinaitop.depot.intelligent.wsClientJc.jc3.MyWebServiceSoap;
import com.unissoft.model.ResponseEntity;
import com.unissoft.model.SendEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qingsong.han
 * @description: 数量检测分析预警
 * @create 2019-02-22 16:01
 */
@Service
public class MonitorWarningServiceImpl implements MonitorWarningService {

    @Value("${num_version3}")
    private String num_version3 = ":20013";

    @Resource
    private TNumberWarningMapper numberWarningMapper;

    @Resource
    private TNumberWarningHistoryMapper numberWarningHistoryMapper;

    @Resource
    private UuidUtils uUidUtils;

    /**
     * 列表
     *
     * @param vcfcode
     * @return
     */
    @Override
    public List<Map<String, Object>> getList(String vcfcode) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(vcfcode))
            map.put("vcfcode", vcfcode);
        return numberWarningMapper.getThisAndSetList(map);
    }

    /**
     * 根据外键添加或更新数据
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(String cfcode, String devcode, String operator, String orgId, String[] num) {
        String cfcode1 = numberWarningMapper.getCfName(cfcode).get(0).get("cfcode").toString();
        TNumberWarning nw = new TNumberWarning();
        nw.setId(uUidUtils.getCodeId(orgId, "t_number_warning"));
        nw.setOrgId(orgId);
        nw.setVcfcode(cfcode1);
        nw.setVdevcode(devcode);
        nw.setMonitorNumber(num[0]);
        nw.settVolume(num[1]);
        nw.settError(num[2]);
        nw.setDepotType(num[3]);
        nw.setDepotLong(num[4]);
        nw.setDepotWide(num[5]);
        nw.setAvgHeightv(num[6]);
        nw.setOperator(operator);
        nw.setMonitorTime(DateUtils.getDate());
        TNumberWarningHistory nwh = new TNumberWarningHistory();
        nwh.setId(uUidUtils.getCodeId(orgId, "t_number_warning_history"));
        nwh.setOrgId(orgId);
        nwh.setVcfcode(cfcode1);
        nwh.setVdevcode(devcode);
        nwh.setMonitorNumber(num[0]);
        nwh.settVolume(num[1]);
        nwh.settError(num[2]);
        nwh.setDepotType(num[3]);
        nwh.setDepotLong(num[4]);
        nwh.setDepotWide(num[5]);
        nwh.setAvgHeightv(num[6]);
        nwh.setOperator(operator);
        nwh.setMonitorTime(DateUtils.getDate());
        TNumberWarningExample example = new TNumberWarningExample();
        TNumberWarningExample.Criteria criteria = example.createCriteria();
        criteria.andVcfcodeEqualTo(cfcode1);
        numberWarningMapper.deleteByExample(example);
        numberWarningMapper.insert(nw);
        numberWarningHistoryMapper.insert(nwh);
    }

    /**
     * 获取摄像头信息
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getVideoInfo() {
        return numberWarningMapper.getVideoInfo();
    }

    @Override
    public List<Map<String, Object>> getCfName(String cfname) {
        return numberWarningMapper.getCfName(cfname);
    }

    @Override
    public List<TNumberWarningHistory> getListHistory(String orgId, String vCfCode, String startTime, String endTime) {
        TNumberWarningHistoryExample example = new TNumberWarningHistoryExample();
        TNumberWarningHistoryExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(orgId)) {
            criteria.andOrgIdEqualTo(orgId);
        }
        if (StringUtils.isNotBlank(vCfCode)) {
            criteria.andVcfcodeEqualTo(vCfCode);
        }
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            criteria.andMonitorTimeBetween(DateUtils.stringToData(startTime + DateUtils.startTime), DateUtils.stringToData(endTime + DateUtils.endTime));
        }
        example.setOrderByClause("monitor_time desc");
        List<TNumberWarningHistory> tNumberWarningHistories = numberWarningHistoryMapper.selectByExample(example);
        return tNumberWarningHistories;
    }

    @Override
    public String getScanResult(String vcfcode, String ws) {
        try {
            if (StringUtils.isNotBlank(vcfcode) && StringUtils.isNotBlank(ws)) {
                if (ws.contains(num_version3)) {
                    MyWebServiceSoap myWebService3 = SendEntity.myWebService3();
                    String safetyShebei = myWebService3.getSafetyShebei();
                    if (!safetyShebei.contains((vcfcode + ":"))) {
                        return "设备不在线！";
                    }
                    //查看进度unsuc_socketconnect10.20.1.120:4001false
                    String measureFullStatus = myWebService3.getMeasureFullStatus(vcfcode);
                    if (measureFullStatus.contains("unsuc_socketconnect10.20")) {
                        return "请发检测指令！";
                    }
                    if (measureFullStatus.contains("suc_")) {
                        String[] s = measureFullStatus.split("_");
                        String s1 = s[s.length - 1];
                        String[] split = s1.split(",");
                        if (split[0].equals("0")) {
                            return "检测进行中！";
                        }
                        return "扫描共记" + split[1] + "点，正检测第" + split[0] + "个点";
                    } else {
                        return measureFullStatus;
                    }
                } else {
                    com.chinaitop.depot.intelligent.wsClientJc.jc2.MyWebServiceSoap webService2 = SendEntity.myWebService2();
                    String measureStatus = webService2.getMeasureStatus(vcfcode);
                    String onlineShebei = webService2.getOnlineShebei();
                    String[] split1 = onlineShebei.split(";unsuc_");
                    if (!split1[0].contains((vcfcode + ":"))) {
                        return "设备不在线！";
                    }
                    if (measureStatus.contains("suc_")) {
                        String[] s = measureStatus.split("_");
                        String s1 = s[s.length - 1];
                        String[] split = s1.split(",");
                        if (split[0].equals("0")) {
                            return "检测进行中！";
                        }
                        if (split.length > 2) {
                            return "请发检测指令！";
                        }
                        return "扫描共记" + split[1] + "点，正检测第" + split[0] + "个点";
                    } else {
                        return measureStatus;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "设备连接异常！";
        }
        return "仓房或地址不能为空！";
    }

    @Override
    public String getmeasureweight(String vcfcode, String devcode, String operator, String orgId, String ws) {
        try {
            if (StringUtils.isNotBlank(vcfcode) && StringUtils.isNotBlank(ws)) {
                if (ws.contains(num_version3)) {
                    MyWebServiceSoap myWebService3 = SendEntity.myWebService3();
                    String safetyShebei = myWebService3.getSafetyShebei();
                    if (!safetyShebei.contains((vcfcode + ":"))) {
                        return "设备不在线！";
                    }
                    //获取扫描结果unsuc_socketconnect10.20.1.120:4001false
                    String measureFullWeight = myWebService3.getMeasureFullWeight(vcfcode);
                    if (measureFullWeight.contains("unsuc_socketconnect10.20")) {
                        return "请发检测指令！";
                    }
                    if (measureFullWeight.contains("suc_getMeasureFullWeight_ERR")) {
                        return "数量检测进行中！";
                    }
                    if (measureFullWeight.contains("suc_")) {
                        String[] split = measureFullWeight.split("_");
                        String s = split[split.length - 1];
                        String[] split1 = s.split(",");
                        saveOrUpdate(vcfcode, devcode, operator, orgId, split1);
                        return "本次扫描结果为" + split1[0] + "吨！";
                    } else {
                        return measureFullWeight;
                    }
                } else {
                    com.chinaitop.depot.intelligent.wsClientJc.jc2.MyWebServiceSoap webService2 = SendEntity.myWebService2();
                    String onlineShebei = webService2.getOnlineShebei();
                    String[] split1 = onlineShebei.split(";unsuc_");
                    if (!split1[0].contains((vcfcode + ":"))) {
                        return "设备不在线！";
                    }
                    String scanWeight = webService2.getScanWeight(vcfcode);
                    if (scanWeight.contains("unsuc_socketconnect_")) {
                        return "请发检测指令！";
                    }
                    if (scanWeight.contains("suc_")) {
                        String[] s = scanWeight.split("_");
                        String s1 = s[s.length - 1];
                        String[] split = s1.split(",");
                        saveOrUpdate(vcfcode, devcode, operator, orgId, split);
                        return "本次扫描结果为" + split[0] + "吨！";
                    } else {
                        return scanWeight;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "设备连接异常！";
        }
        return "仓房或地址不能为空！";
    }

    @Override
    public String sendNumberMonitor(String vcfcode, String ws) {
        String msg = "";
        try {
            if (StringUtils.isNotBlank(vcfcode) && StringUtils.isNotBlank(ws)) {
                String[] split = vcfcode.split(",");
                String[] wsz = ws.split(",");
                for (int i = 0; i < split.length; i++) {
                    String vcf = split[i];
                    String cfz = getCfName(vcf).get(0).get("cfname").toString();
                    String w = wsz[i];
                    String cf = vcf + ":";
                    if (w.contains(num_version3)) {
                        MyWebServiceSoap myWebService3 = SendEntity.myWebService3();
                        //getSafetyShebei获取在线设备311:
                        String safetyShebei = myWebService3.getSafetyShebei();
                        if (safetyShebei.contains(cf)) {
                            //发送检测指令
                            String s = myWebService3.startFullMeasure(vcf);
                            if (s.contains("suc_")) {
                                msg += cfz + "检测开始;";
                            } else {
                                msg += cfz + "检测失败;";
                            }
                        } else {
                            msg += cfz + "设备不在线;";
                        }
                    } else {//1、.startScan(vcfcode);
                        com.chinaitop.depot.intelligent.wsClientJc.jc2.MyWebServiceSoap webService2 = SendEntity.myWebService2();
                        //获取在线设备
                        String onlineShebei = webService2.getOnlineShebei();
                        String[] split1 = onlineShebei.split(";unsuc_");
                        if (split1[0].contains(cf)) {
                            String s = webService2.startScan(vcf);
                            if (s.contains("suc_")) {
                                msg += cfz + "检测开始;";
                            } else {
                                msg += cfz + "检测失败;";
                            }
                        } else {
                            msg += cfz + "设备不在线;";
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "设备连接异常！";
        }
        return msg;
    }

    @Override
    public TNumberWarningHistory getTWarning(String orgId, String vCfCode) {
        List<TNumberWarningHistory> listHistory = this.getListHistory(orgId, vCfCode, null, null);
        if (listHistory.size() > 0) {
            return listHistory.get(0);
        }
        return null;
    }

}
