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

import com.steerinfo.framework.controller.RESTfulResult;
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.meterworkmonitor.mapper.MeterWorkMonitorMapper;
import com.steerinfo.meterwork.meterworkmonitor.model.MeterWorkMonitor;
import com.steerinfo.meterwork.meterworkmonitor.service.IMeterWorkMonitorService;
import com.steerinfo.meterwork.meterworkonline.mapper.MeterWorkOnlineMapper;
import com.steerinfo.meterwork.meterworkonline.model.MeterWorkOnline;
import com.steerinfo.util.FieldsCollector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.*;

/**
 * MeterWorkMonitor服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2020-11-06 03:27
 * 类描述
 * 修订历史：
 * 日期：2020-11-06
 * 作者：generator
 * 参考：
 * 描述：MeterWorkMonitor服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "meterWorkMonitorService")
@Component
@EnableAsync        //开启多线程
public class MeterWorkMonitorServiceImpl extends BaseServiceImpl<MeterWorkMonitor, String> implements IMeterWorkMonitorService {

    @Resource
    private MeterWorkMonitorMapper meterWorkMonitorMapper;

    @Resource
    private MeterWorkOnlineMapper meterWorkOnlineMapper;

    @Override
    protected IBaseMapper<MeterWorkMonitor, String> getMapper() {
        return meterWorkMonitorMapper;
    }

    @Override
    public RESTfulResult doQueryWf(MeterWorkMonitor oci) {
        RESTfulResult rm = new RESTfulResult();
        try {
            rm.setCode("200");
            PageHelper.startPage(0, 1);
            Map<String, Object> map = FieldsCollector.beanToMap(oci);
            List<MeterWorkMonitor> rows = meterWorkMonitorMapper.selectByParameters(map);
            PageList pageInfo = new PageList(rows);
            rm.setData(pageInfo);
        } catch (Exception ex) {
            rm.setCode("500");
            rm.setMessage("查询失败：" + ex.getMessage());
        }
        return rm;
    }

    @Override
    @Transactional
    public String doUpdateWf(MeterWorkMonitor model) {
        try {
            meterWorkMonitorMapper.updateByPrimaryKeySelective(model);
            return model.getPointNo();
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return null;
        }
    }

    @Autowired
    DataSource dataSource;

    @Async
//    @Scheduled(cron = "0/1 * * * * ?") //派位程序定时任务，业务代码打包时启用
    @Override
    public void AutomaticAllocation() {
        long startTime = System.currentTimeMillis();
        //1、随机派位
        RandomAssign();
        //update METER_WORK_MONITOR set IS_TAKE_OVER = '0',USER_NO= ''  where 在线时间>= 40)
        meterWorkMonitorMapper.batchUpdateForNotOnLine();

        //update METER_WORK_STORAGE_ONLINE set WORK_FLAG= '0' where 在线时间>= 40
        meterWorkOnlineMapper.batchUpdateForNotOnLine();

        meterWorkOnlineMapper.batchUpdateForNotWork();

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

    @Override
    public RESTfulResult weightByCarNo(String rfidCar) {
        RESTfulResult rm = new RESTfulResult();
        rm.setFailed();
        try{
            HashMap<String, Object> map = new HashMap();
            map.put("rfidCar", rfidCar);
            map.put("photoCar", rfidCar);
            map.put("scanCar", rfidCar);
            map.put("editCar", rfidCar);
            List<MeterWorkMonitor> models = meterWorkMonitorMapper.weightByCarNo(map);
            if(models.size() >= 1) {
                rm.setSucceed();
                rm.setData(models.get(0));
                rm.setMessage("操作成功！！");
                rm.setCode("200");
            }else {
                rm.setMessage("根据车号未查询到相应重量信息,请确认！！");
            }
            return rm;
        }catch(Exception e) {
            e.printStackTrace();
            rm.setMessage("操作异常，请确认！！>>>" + e.getMessage());
            return rm;
        }
    }


    private void RandomAssign() {
        List<MeterWorkMonitor> list2 = meterWorkMonitorMapper.selectForAss();
        if (list2.size() > 0) {
            //2、取最后在线时间与当前时间差不超过10s且状态为未接管的数据
            HashMap<String, Object> obj1 = new HashMap<>();
            obj1.put("duration", 20);//时长
            obj1.put("workFlag", "0");
            List<MeterWorkOnline> list1 = meterWorkOnlineMapper.selectFor(obj1);
            if (list1.size() > 0){
                ArrayList<String> ids = new ArrayList<>();
                for (MeterWorkMonitor list : list2) {
                    Random rand = new Random();
                    int randNum = rand.nextInt(list1.size());
                    //为监控表赋值
                    list.setUserNo(list1.get(randNum).getUserId());
                    //
                    ids.add(list1.get(randNum).getUserId());
                    list1.remove(list1.get(randNum));
                    //
                    list.setIsTakeOver("2");
                }
                meterWorkMonitorMapper.UpdateUserNo(list2);
                meterWorkOnlineMapper.batchUpdateForId(ids);
            }
        }
    }
}
