package com.steerinfo.baseinfo.meterbasethread.service.impl;

import com.steerinfo.baseinfo.combaseinfo.mapper.ComBaseInfoMapper;
import com.steerinfo.baseinfo.constants.DbConstants;
import com.steerinfo.baseinfo.meterbasedatamigration.mapper.MeterBaseDataMigrationMapper;
import com.steerinfo.baseinfo.meterbasedatamigration.model.MeterBaseDataMigration;
import com.steerinfo.baseinfo.meterbasethread.mapper.MeterBaseThreadMapper;
import com.steerinfo.baseinfo.meterbasethread.model.MeterBaseThread;
import com.steerinfo.baseinfo.meterbasethread.service.IMeterBaseThreadService;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.util.StringUtils;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

    @Resource
    private MeterBaseThreadMapper meterBaseThreadMapper;

    @Resource
    private MeterBaseDataMigrationMapper meterBaseDataMigrationMapper;


    @Resource
    private ComBaseInfoMapper comBaseInfoMapper;


    @Override
    protected IBaseMapper<MeterBaseThread, String> getMapper() {
        return meterBaseThreadMapper;
    }

    @Override
    public String checkandadd(MeterBaseThread model)
    {
        String msg=check(model);
        if (StringUtils.isNotEmpty(msg)){
            return msg;
        }
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("threadName", model.getThreadName());
        List<MeterBaseThread> com=meterBaseThreadMapper.selectByParameters(obj);
        if (! com.isEmpty()){
            return "线程名称不允许重复！！";
        }
        String no=meterBaseThreadMapper.GetNewID();
        model.setThreadNo(new SimpleDateFormat("yyyyMMdd").format(new Date())+no);
        meterBaseThreadMapper.insert(model);
        return "";
    }

    @Override
    public String Recovery(List<MeterBaseThread> models)
    {
        try {
            if (models == null || models.size() < 1) {
                return "请传入参数!";
            }
            for (MeterBaseThread model:models) {
                model.setId(model.getId());
                model.setValueFlag("0");
                model.setUpdateManName(model.getUpdateManName());
                model.setUpdateManNo(model.getUpdateManNo());
                model.setUpdateTime(new Date());
                meterBaseThreadMapper.updateByPrimaryKey(model);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }

    @Override
    public String checkandupdate(String id,MeterBaseThread model)
    {
        String msg=check(model);
        if (StringUtils.isNotEmpty(msg)){
            return msg;
        }
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("threadName", model.getThreadName());
        obj.put("threadNo", id);
        List<MeterBaseThread> com=meterBaseThreadMapper.selectForUpdate(obj);
        if (! com.isEmpty()){
            return "线程名称不允许重复！！";
        }
        meterBaseThreadMapper.updateByPrimaryKey(model);
        return "";
    }

    @Override
    public String abolish(List<MeterBaseThread> models)
    {
        try {
            if (models == null || models.size() < 1) {
                return "请传入参数!";
            }
            for (MeterBaseThread model:models) {
                model.setId(model.getId());
                model.setValueFlag("1");
                model.setUpdateManName(model.getUpdateManName());
                model.setUpdateManNo(model.getUpdateManNo());
                model.setUpdateTime(new Date());
                meterBaseThreadMapper.updateByPrimaryKey(model);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作异常，请联系管理员";
        }
        return "";
    }

    private String check (MeterBaseThread model){
        if (model == null){
            return "参数为空！";
        }
        if (StringUtils.isEmpty(model.getThreadName())){
            return "线程名称不能为空！！";
        }
        if (StringUtils.isEmpty(model.getThreadEffect())){
            return "线程作用不能为空！！";
        }
        if (model.getThreadEdition() == null){
            return "线程版本不能为空！！";
        }
        if (StringUtils.isEmpty(model.getThreadBelong())){
            return "线程归属不能为空！！";
        }
        if (model.getRefreshRate() == null){
            return "刷新频率不能为空！！";
        }
        if(StringUtils.isEmpty(model.getThreadNo())){
            model.setCreateTime(new Date());
            model.setValueFlag("0");//有效
        }else {
            model.setUpdateTime(new Date());
        }
        return "";
    }


    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
        String bigStr;
        try {
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            return false;//异常 说明包含非数字。
        }

        Matcher isNum = pattern.matcher(bigStr);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    //@Async
    //数据迁移的定时任务
    //@Scheduled(cron = "0/1 * * * * ?") //数据迁移定时任务
    @Transactional
    public void performMigration(){
        HashMap<String, Object> obj = new HashMap<>();
        obj.put("threadName","performMigration");
        List<MeterBaseThread> mbts = meterBaseThreadMapper.selectByParameters(obj);
        if (DbConstants.num >= mbts.get(0).getRefreshRate() ){
            HashMap<String, Object> obj1 = new HashMap<>();
            obj1.put("valueFlag","0");//有效
            List<MeterBaseDataMigration> mbdms = meterBaseDataMigrationMapper.selectByParameters(obj1);
            for (MeterBaseDataMigration mbdm : mbdms){
                String sql1= "select * from " + mbdm.getCountTypeNo() + " where " + mbdm.getRateValue() + " and rownum <=" + mbdm.getMigrationNum();
                HashMap<String, Object> obj2 = new HashMap<>();
                obj2.put("sql",sql1);
                List<HashMap> hms = comBaseInfoMapper.executeSqlData(obj2);
                ArrayList<String> ids = new ArrayList<>();
                for (HashMap hm : hms){
                    ids.add(hm.get(mbdm.getCountPk()).toString());
                }
                HashMap<String, Object> obj3 = new HashMap<>();
                obj3.put("countTypeNo",mbdm.getCountTypeNo());
                obj3.put("contrastTypeNo",mbdm.getContrastTypeNo());
                obj3.put("countPk",mbdm.getCountPk());
                obj3.put("list",ids);
                meterBaseDataMigrationMapper.insertMigration(obj3);
                meterBaseDataMigrationMapper.deleteMigration(obj3);
            }
            DbConstants.num = 0;
        }
        DbConstants.num++;
        //system.out.println("001");
    }
}
