package com.mvc.service.extend;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.BaseConstant;
import com.mvc.constant.DeviceType;
import com.mvc.dao.StationAccMapper;
import com.mvc.dao.TAireadMapper;
import com.mvc.dao.TIdentEnquiriesMapper;
import com.mvc.entity.*;
import com.mvc.model.*;

import java.math.RoundingMode;

import com.mvc.model.extend.TIdentEnquiriesModel;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.taizhang.TAicbqCfgService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class TIdentEnquiriesService {
    private static Logger log = LoggerFactory.getLogger(TIdentEnquiriesService.class);

    @Resource
    private TIdentEnquiriesMapper tIdentEnquiriesMapper;

    @Resource
    private TAireadMapper aireadMapper;

    @Resource
    private TAireadService aireadService;

    @Resource
    private StationAccMapper stationAccMapper;

    @Resource
    private TAicbqCfgService aicbqCfgService;

    public static Date lastGenerateTime = new Date(0L);

    /**
     * 查询记录
     *
     * @param queryModel
     * @return
     */
    public ResPageModel findAllTIdentEnquiries(TIdentEnquiriesModel queryModel) {
        TIdentEnquiriesExample example = new TIdentEnquiriesExample();
        TIdentEnquiriesExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotEmpty(queryModel.getDeviceSn())) {
            criteria.andDeviceSnEqualTo(queryModel.getDeviceSn());
        }
        if (StringUtils.isNotEmpty(queryModel.getUnitCode())) {
            criteria.andUnitCodeEqualTo(queryModel.getUnitCode());
        }
        if (StringUtils.isNotEmpty(queryModel.getStationCode())) {
            criteria.andStationCodeEqualTo(queryModel.getStationCode());
        }
        if (StringUtils.isNotEmpty(queryModel.getDeviceType())) {
            criteria.andDeviceTypeEqualTo(queryModel.getDeviceType());
        }
        if (StringUtils.isNotEmpty(queryModel.getAiVersion())) {
            criteria.andAiVersionLike(StringUtil.getLikeFormat(queryModel.getAiVersion()));
        }
        if (StringUtils.isNotEmpty(queryModel.getEnableNoconfigManualConfig()) && queryModel.getEnableNoconfigManualConfig().equals("1")) {
            criteria.andEnableNoconfigManualConfigEqualTo("1");
        }

        List<TAireadModel> resList = new ArrayList<>();

        Page<Object> pageObject = PageHelper.startPage(queryModel.getPageNum(), queryModel.getPageSize());
        List<TIdentEnquiries> TIdentEnquiriess = tIdentEnquiriesMapper.selectByExample(example);

        for (TIdentEnquiries identEnquiries : TIdentEnquiriess) {
            TAiread airead = aireadMapper.selectByPrimaryKey(identEnquiries.getId());
            if (airead == null) {
                continue;
            }
            TAireadModel aireadModel = new TAireadModel();
            BeanUtils.copyProperties(airead, aireadModel);
            aireadModel.setStationName(identEnquiries.getStationName());

            //**特殊处理:展示数据是使用的TAireadModel,为不影响前端数据绑定,因此借用以下两个字段(本功能仅供指定人员使用)
            aireadModel.setGoodFlag(String.format("%.2f", identEnquiries.getAccuracyRate()) + " %");//**借用展示准确率
            aireadModel.setRevTime(identEnquiries.getCreateTime());//**借用展示生成时间

            resList.add(aireadModel);
        }

        ResPageModel resPageModel = new ResPageModel(resList, pageObject);
        return resPageModel;
    }

    /**
     * 生成识别查询数据
     */
    @Async
    public void generateIdentEnquiriesData() {
        log.info("开始生成识别情况查询数据");
        //首先清空表
        deleteAllIdentEnquiriesData();
        lastGenerateTime = new Date();
        List<StationAcc> accModels = stationAccMapper.selectByExample(null);
        for (StationAcc stationAcc : accModels) {
            TIdentEnquiries identEnquiries = new TIdentEnquiries();
            //补充站点信息
            identEnquiries.setStationCode(stationAcc.getStationCode());
            identEnquiries.setStationName(stationAcc.getStationName());
            identEnquiries.setUnitCode(stationAcc.getUnitCode());
            identEnquiries.setDeviceType(stationAcc.getDeviceType());

            //补充读数信息
            TAireadModel lstModel = aireadService.findLatesTAireadByStationCode(stationAcc.getStationCode());
            //没有数据或可信直接跳过
            if (lstModel == null || isBelievable(lstModel)) {
                continue;
            }

            //原始值和结果值都没有值的情况(去掉服务侧识别的,燃气表等)(加上类型,是为了防止漏掉边缘侧识别时拍的是非表盘而不上传数值)
            if (lstModel.getIdentValue() == null && lstModel.getRawValue() == null && stationAcc.getDeviceType().equals(DeviceType.GAS_METER.getCode())) {
                continue;
            }

            //超过半年无数据的,不处理
            long days = DateUtil.daysBetween(lstModel.getSampleTime(), lastGenerateTime);
            if (days > 180) {
                continue;
            }

            identEnquiries.setId(lstModel.getId());
            identEnquiries.setDeviceSn(lstModel.getDeviceSn());
            identEnquiries.setAiVersion(lstModel.getAiVersion());

            int flag = 0;
            //识别标识(1,2,7,8或91,92等)
            if (lstModel.getSzsbz() != null) {
                String[] tsxx = lstModel.getSzsbz().split(",");
                if (tsxx.length >= 12) {
                    flag = tsxx[11].equals("-") ? 88 : Integer.parseInt(tsxx[11]);

                }
            }
            identEnquiries.setIdentFlag(flag);

            //配置相关
            TAicbqCfgModel cfgModel = aicbqCfgService.findTAicbqCfgModel(lstModel.getDeviceSn(), "", BaseConstant.VALID_FLAG);
            if (cfgModel != null) {
                identEnquiries.setAicbqCfgId(cfgModel.getId());
                //防止旧表空值
                String enable = StringUtils.isEmpty(cfgModel.getEnableNoconfigManualConfig()) ? "0" : "1";
                identEnquiries.setEnableNoconfigManualConfig(enable);
            }

            //准确率
            List<TAireadModel> aireadModels = getAireadList(stationAcc.getStationCode());
            if (aireadModels != null && aireadModels.size() > 0) {
                int num = 0;
                for (TAireadModel temp : aireadModels) {
                    if (isBelievable(temp)) {
                        num++;
                    }
                }
                double rate = (double) num / aireadModels.size() * 100;
                identEnquiries.setAccuracyRate(new BigDecimal(rate).setScale(2, RoundingMode.HALF_UP).doubleValue());
            }
            identEnquiries.setCreateTime(lastGenerateTime);
            tIdentEnquiriesMapper.insert(identEnquiries);
        }
        log.info("结束生成识别情况查询数据");
    }

    private List<TAireadModel> getAireadList(String stationCode) {
        TAireadModel queryModel = new TAireadModel();
        queryModel.setPage(1);
        queryModel.setRows(500);
        queryModel.setStationCode(stationCode);
        Map<String, Object> map = aireadService.findAllTAireadByCondition(queryModel);
        return (map != null && map.containsKey("list")) ? (List<TAireadModel>) map.get("list") : null;
    }

    private boolean isBelievable(TAireadModel aireadModel) {
        if (aireadModel == null || aireadModel.getSzsbz() == null) {
            return false;
        }
        String[] tsxx = aireadModel.getSzsbz().split(",");
        boolean isGood = false;                                   //数据是否有效
        if (tsxx.length == 12) {
            //新版本MCU程序
            isGood = BaseConstant.IDENT_GOOD_FLAG.contains(tsxx[11]);
        }//长度不是12的,有可能是老版本的MCU程序,数量应该比较少,暂时也加入审核里
        return isGood;
    }

    private int deleteAllIdentEnquiriesData() {
        TIdentEnquiriesExample example = new TIdentEnquiriesExample();
        example.createCriteria().andIdGreaterThan(0);
        return tIdentEnquiriesMapper.deleteByExample(example);
    }

    public TIdentEnquiriesModel saveTIdentEnquiries(TIdentEnquiriesModel model) {
        model.setCreateTime(new Date());
        TIdentEnquiries TIdentEnquiries = new TIdentEnquiries();
        BeanUtils.copyProperties(model, TIdentEnquiries);
        tIdentEnquiriesMapper.insert(TIdentEnquiries);
        model.setId(TIdentEnquiries.getId());
        return model;
    }

    public TIdentEnquiriesModel updateTIdentEnquiries(TIdentEnquiriesModel model) {
        TIdentEnquiries TIdentEnquiries = tIdentEnquiriesMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, TIdentEnquiries);
        int i = tIdentEnquiriesMapper.updateByPrimaryKey(TIdentEnquiries);
        return model;
    }

    public int deleteTIdentEnquiries(int id) {
        int i = tIdentEnquiriesMapper.deleteByPrimaryKey(id);
        return i;
    }

    /**
     * 校验生成间隔(两次必须在1分钟内)
     *
     * @return
     */
    public boolean verifyGenerationInterval() {
        Date now = new Date();
        return DateUtil.getMinsbetweenTime(lastGenerateTime, now) > 1;

        /*TIdentEnquiriesExample example = new TIdentEnquiriesExample();
        example.setOrderByClause("CREATE_TIME");

        PageHelper.startPage(1, 1);

        List<TIdentEnquiries> list = tIdentEnquiriesMapper.selectByExample(example);
        if (list.size() > 0) {
            TIdentEnquiries identEnquiries = list.get(0);
            return DateUtil.getMinsbetweenTime(identEnquiries.getCreateTime(), now) > 1;
        }
        return true;*/
    }
}
