package com.steerinfo.meterwork.meterworkstockonline.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.meterwork.constants.DbConstants;
import com.steerinfo.meterwork.dto.StorageCollectModel;
import com.steerinfo.meterwork.except.MarkerMetException;
import com.steerinfo.meterwork.meterworkstockonline.mapper.MeterWorkStockOnlineMapper;
import com.steerinfo.meterwork.meterworkstockonline.model.MeterWorkStockOnline;
import com.steerinfo.meterwork.meterworkstockonline.service.IMeterWorkStockOnlineService;
import com.steerinfo.meterwork.meterworkstorageonline.mapper.MeterWorkStorageOnlineMapper;
import com.steerinfo.util.StringUtils;
import com.steerinfo.util.TestClient2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * MeterWorkStockOnline服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2020-11-18 04:16
 * 类描述
 * 修订历史：
 * 日期：2020-11-18
 * 作者：generator
 * 参考：
 * 描述：MeterWorkStockOnline服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "meterWorkStockOnlineService")
public class MeterWorkStockOnlineServiceImpl extends BaseServiceImpl<MeterWorkStockOnline, String> implements IMeterWorkStockOnlineService {

    @Resource
    private MeterWorkStockOnlineMapper meterWorkStockOnlineMapper;

    @Autowired
    private MeterWorkStorageOnlineMapper meterWorkStorageOnlineMapper;

    @Override
    protected IBaseMapper<MeterWorkStockOnline, String> getMapper() {
        return meterWorkStockOnlineMapper;
    }


    @Override
    @Transactional
    public String doSaveWf(MeterWorkStockOnline model){
        if (model == null || StringUtils.isEmpty(model.getBaseSpotNo())) {
            throw new MarkerMetException(500, "参数不正确！！");
        }
        meterWorkStockOnlineMapper.updateByPrimaryKeyForNull(model);
        return model.getBaseSpotNo();
    }



//产线秤数据采集
//    @Scheduled(cron = "0/1 * * * * ?") //定时任务；产线秤数据采集
    public void collectWeight () throws ParseException {
        HashMap<String, Object> obj = new HashMap<>();
        List<MeterWorkStockOnline> list1 = meterWorkStockOnlineMapper.selectByParameters(obj);
        DbConstants.StorageList.clear();
        for (MeterWorkStockOnline list : list1) {
            String no = list.getPointNo();

            List ll = TestClient2.connectSelect(no);
            if (ll != null && ll.size() > 0){
                StorageCollectModel scm = new StorageCollectModel();

                ArrayList arr = (ArrayList) ll.get(0);

                scm.setPointid(list.getBaseSpotNo());
                //时间戳
                Long timeStamp = (Long)arr.get(6)*1000;  //获取时间戳
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));   // 时间戳转换成时间
                scm.setDatetime(sdf.parse(sd));
                //主副秤重量值
                String json= JSON.toJSONString(arr.get(14));
                JSONObject jsonobject = JSONObject.parseObject(json);
                for(String key : jsonobject.keySet()){
                    if(key.endsWith("Main")){
                        //主秤赋值
                        scm.setMainWgt(jsonobject.get(key).toString());
                    }else if (key.endsWith("Vice")){
                        //副秤赋值
                        scm.setViceWgt(jsonobject.get(key).toString());
                    }
                }
                //副秤稳定状态
                scm.setVoiceWeightStatus((int)arr.get(1));
                //主秤稳定状态
                scm.setMainWeightStatus((int)arr.get(1));
                if (StringUtils.isNotEmpty(scm.getMainWgt()) && StringUtils.isNotEmpty(scm.getViceWgt())){
                    DbConstants.StorageList.add(scm);
                }
            }
        }
    }

    //无用，产线秤用
    //@Scheduled(cron = "0/30 * * * * ?") //定时任务
    public void AutomaticUnlock () {
        long startTime = System.currentTimeMillis();
        //1、随机派位
        RandomAssign();

        meterWorkStockOnlineMapper.batchUpdateForNotOnLine();
        meterWorkStorageOnlineMapper.batchUpdateForNotOnLine();

        //4、再次随机派位
        RandomAssign();
        long endTime = System.currentTimeMillis();
        float excTime = (float) (endTime - startTime) / 1000;
        //system.out.println("====================================>执行时间：" + excTime + "s");
    }

    private void RandomAssign() {
        //1、判断需要派位的计量点
        List<String> pointids = new ArrayList<>();
        for(StorageCollectModel list : DbConstants.StorageList) {
            if (Integer.parseInt(list.getMainWgt()) >= 60){
                pointids.add(list.getPointid());
            }
        }
        //2、取得要派位的值
        List<MeterWorkStockOnline> list2 = meterWorkStockOnlineMapper.batchSelect(pointids);
        if (list2.size() > 0) {
            //2、取最后在线时间与当前时间差不超过10s且状态为未接管的数据
            HashMap<String, Object> obj1 = new HashMap<>();
            obj1.put("duration", 10);//时长
            obj1.put("workFlag", "0");
            List<MeterWorkStockOnline> list1 = meterWorkStorageOnlineMapper.selectFor(obj1);
            if (list1.size() > 0){
                ArrayList<String> ids = new ArrayList<>();
                for (MeterWorkStockOnline list : list2) {
                    Random rand = new Random();
                    int randNum = rand.nextInt(list1.size());
                    ids.add(list1.get(randNum).getUserId());
                    list1.remove(list1.get(randNum));
                }
                meterWorkStockOnlineMapper.batchUpdateSelective(list2);
                meterWorkStorageOnlineMapper.batchUpdateForId(ids);
            }
        }
    }

    @Override
    @Transactional
    public PageList<MeterWorkStockOnline> doQueryWf(HashMap parmas, Integer pageNum, Integer pageSize){
        //修改IP、ID为当前值的数据修改时间。
        HashMap<String, Object> obj1 = new HashMap<>();
        obj1.put("userIp", parmas.get("userIp").toString());
        obj1.put("userId", parmas.get("userId").toString());
        List<MeterWorkStockOnline> rows = meterWorkStockOnlineMapper.selectByParameters(obj1);
        if (rows != null || rows.size() > 0) {
            for (MeterWorkStockOnline row : rows) {
                row.setLastTime(new Date());
                meterWorkStockOnlineMapper.updateByPrimaryKeySelective(row);
            }
        }
        //查询符合要求
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("spotTypeNo", parmas.get("spotTypeNo").toString());
        PageHelper.startPage(pageNum, pageSize);
        List<MeterWorkStockOnline> list = meterWorkStockOnlineMapper.selectByParameters(obj);
        PageList pageInfo = new PageList(list);
        return pageInfo;
    }

    public static void main(String[] args) {
//        List ll = TestClient2.getConnecting();
//        ArrayList arr = (ArrayList) ll.get(0);
//        //system.out.println(arr);
//        //判断14的长度    以及CAR20WeightVice和
//        String json= JSON.toJSONString(arr.get(14));
//        //system.out.println(json);
//        JSONObject jsonobject = JSONObject.parseObject(json);
//        for(String key : jsonobject.keySet()){
//            if(key.endsWith("Main")){
//
//            }else if (key.endsWith("Vice")){
//
//            }
//        }
//        //system.out.println(jsonobject.get("CAR20WeightVice"));
//        //system.out.println(jsonobject.get("CAR20WeightMain"));
    }

}
//    @Override
//    @Transactional
//    public PageList<MeterWorkStockOnline> unlockWf(MeterWorkStockOnline model){
//        model.setWorkFlag("0");//未接管
//        model.setLastTime(new Date());//当前时间
//        meterWorkStockOnlineMapper.updateByPrimaryKeySelective(model);
//        MeterWorkStockOnline mwso = meterWorkStockOnlineMapper.selectByPrimaryKey(model.getBaseSpotNo());
//        PageHelper.startPage(1, 1);
//        List<MeterWorkStockOnline> rows = new ArrayList<>();
//        rows.add(mwso);
//        PageList pageInfo = new PageList(rows);
//        return pageInfo;
//    }
//
//    @Override
//    @Transactional
//    public PageList<MeterWorkStockOnline> lockWf(MeterWorkStockOnline model) {
//        List<MeterWorkStockOnline> rows = new ArrayList<>();
//        PageHelper.startPage(1, 1);
//        HashMap<String, Object> obj = new HashMap<>();
//        obj.put("baseSpotNo",model.getBaseSpotNo());
//        obj.put("userIp",model.getUserIp());
//        List<MeterWorkStockOnline> list1 = meterWorkStockOnlineMapper.selectByParameters(obj);
//        if (list1.size() > 0){
//            list1.get(0).setWorkFlag("1");
//            rows.add(list1.get(0));
//            meterWorkStockOnlineMapper.updateByPrimaryKeySelectiveNotWeightTime(list1.get(0));
//        }else{
//            model.setWorkFlag("1");//已接管
//            model.setLastTime(new Date());//当前时间
//            model.setWeightTime(null);
//            meterWorkStockOnlineMapper.updateByPrimaryKeySelectiveNotWeightTime(model);
//            MeterWorkStockOnline mwso = meterWorkStockOnlineMapper.selectByPrimaryKey(model.getBaseSpotNo());
//            rows.add(mwso);
//        }
//        PageList pageInfo = new PageList(rows);
//        return pageInfo;
//    }
//

//
//    @Override
//    @Transactional
//    public PageList<MeterWorkStockOnline> automaticLock(MeterWorkStockOnline model){
//        HashMap<String, Object> obj = new HashMap<>();
//        obj.put("weightFlag","1");//有变化
//        obj.put("workFlag","0");//未接管
//        obj.put("sql","order by WEIGHT_TIME asc");
//        List<MeterWorkStockOnline> rows = meterWorkStockOnlineMapper.selectByParameters(obj);
//        if (rows.size() <= 0 || rows ==  null){
//            return null;
//        }
//        rows.get(0).setBaseSpotNo(rows.get(0).getBaseSpotNo());
//        rows.get(0).setSpotTypeNo(rows.get(0).getSpotTypeNo());
//        rows.get(0).setLastTime(new Date());
//        rows.get(0).setWeightTime(null);
//        rows.get(0).setUserIp(model.getUserIp());
//        rows.get(0).setUserId(model.getUserId());
//        rows.get(0).setWorkFlag("1");//已接管
//        PageHelper.startPage(1, 1);
//        MeterWorkStockOnline row = meterWorkStockOnlineMapper.selectByPrimaryKey(rows.get(0).getBaseSpotNo());
//        List<MeterWorkStockOnline> list = new ArrayList<>();
//        list.add(row);
//        PageList pageInfo = new PageList(list);
//        meterWorkStockOnlineMapper.updateByPrimaryKeySelective(rows.get(0));
//        return pageInfo;
//    }

