package com.mvc.service.taizhang;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.BaseConstant;
import com.mvc.constant.DeviceType;
import com.mvc.dao.TAicbqCfgMapper;
import com.mvc.entity.TAicbqCfg;
import com.mvc.entity.TAicbqCfgExample;
import com.mvc.model.*;
import com.mvc.service.TServerCfgService;
import com.mvc.service.copy.TCheckDetailService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Transactional
public class TAicbqCfgService {

    @Resource
    private TAicbqCfgMapper tAicbqCfgMapper;

    @Resource
    private TCheckDetailService tCheckDetailService;

    @Resource
    private DeviceAccService deviceAccService;

    @Resource
    private TServerCfgService serverCfgService;

    public Map<String, Object> findAllTAicbqCfg(TAicbqCfgModel queryModel) {
        Map<String, Object> resMap = new HashMap<>();
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPage(), queryModel.getRows());

        TAicbqCfgExample example = new TAicbqCfgExample();
        TAicbqCfgExample.Criteria criteria = example.createCriteria();

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(queryModel.getDeviceSn())) {
            if (queryModel.getDeviceSn().length() == BaseConstant.LENGTH_DEVICE_SN) {
                criteria.andDeviceSnEqualTo(queryModel.getDeviceSn());
            } else {
                criteria.andDeviceSnLike(StringUtil.getLikeFormat(queryModel.getDeviceSn()));
            }
        }
        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(queryModel.getStationCode())) {
            if (queryModel.getStationCode().length() == BaseConstant.LENGTH_STATION_CODE) {
                criteria.andStationCodeEqualTo(queryModel.getStationCode());
            } else {
                criteria.andStationCodeLike(StringUtil.getLikeFormat(queryModel.getStationCode()));
            }
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(queryModel.getDataFrom()) &&
                !queryModel.getDataFrom().equals("9")) {
            criteria.andDataFromEqualTo(queryModel.getDataFrom());
        }

        if (queryModel.getCreateTimeStart() != null) {
            criteria.andCreateTimeGreaterThan(queryModel.getCreateTimeStart());
        }

        if (queryModel.getCreateTimeEnd() != null) {
            criteria.andCreateTimeLessThan(queryModel.getCreateTimeEnd());
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(queryModel.getUseFlag()) &&
                !queryModel.getUseFlag().equals("9")) {
            criteria.andUseFlagEqualTo(queryModel.getUseFlag());
        }

        if (StringUtils.isNotEmpty(queryModel.getDeviceType())) {
            criteria.andDeviceTypeEqualTo(queryModel.getDeviceType());
        }

        example.setOrderByClause("CREATE_TIME desc");
        List<TAicbqCfg> TAicbqCfgs = tAicbqCfgMapper.selectByExample(example);
        List<TAicbqCfgModel> resList = new ArrayList<>();
        for (TAicbqCfg TAicbqCfg : TAicbqCfgs) {
            TAicbqCfgModel model = new TAicbqCfgModel();
            BeanUtils.copyProperties(TAicbqCfg, model);
            getOecByPgManualConfig(model);
            getWITaskSpecdate(model);
            getLogUploadRules(model);
            getImageConfig(model);
            resList.add(model);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

/*    public Map<String,Object> findAllTAicbqCfg(Integer page, Integer rows) {
        Map<String, Object> resMap=new HashMap<>();
        Page<Object> pageObject = PageHelper.startPage(page, rows);
        List<TAicbqCfg> TAicbqCfgs = tAicbqCfgMapper.selectByExample(null);
        List<TAicbqCfgModel> resList=new ArrayList<>();
        for(TAicbqCfg TAicbqCfg:TAicbqCfgs){
            TAicbqCfgModel model = new TAicbqCfgModel();
            BeanUtils.copyProperties(TAicbqCfg,model);
            resList.add(model);
        }
        resMap.put("total",pageObject.getTotal());
        resMap.put("list",resList);
        return resMap;
    }*/

    public TAicbqCfgModel saveTAicbqCfg(TAicbqCfgModel model) {
        model.setCreateTime(new Date());
        model.setCfgId(StringUtil.getUuid());
        TAicbqCfg TAicbqCfg = new TAicbqCfg();
        BeanUtils.copyProperties(model, TAicbqCfg);
        int insert = tAicbqCfgMapper.insert(TAicbqCfg);
        model.setId(TAicbqCfg.getId());
        return model;
    }

    public TAicbqCfgModel updateTAicbqCfg(TAicbqCfgModel model) {
        TAicbqCfg TAicbqCfg = tAicbqCfgMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, TAicbqCfg);
        int i = tAicbqCfgMapper.updateByPrimaryKey(TAicbqCfg);
        return model;
    }

    public int deleteTAicbqCfg(int id) {
        int i = tAicbqCfgMapper.deleteByPrimaryKey(id);
        return i;
    }

    public List<TAicbqCfgModel> findTAicbqCfg(String deviceSn, String stationCode, String useFlag) {
        List<TAicbqCfgModel> resModels = new ArrayList<>();
        TAicbqCfgExample example = new TAicbqCfgExample();
        TAicbqCfgExample.Criteria criteria = example.createCriteria();
        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(deviceSn)) {
            criteria.andDeviceSnEqualTo(deviceSn);
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(stationCode)) {
            criteria.andStationCodeEqualTo(stationCode);
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(useFlag)) {
            criteria.andUseFlagEqualTo(useFlag);
        }
        example.setOrderByClause("CREATE_TIME desc");
        List<TAicbqCfg> tAicbqCfgs = tAicbqCfgMapper.selectByExample(example);
        for (TAicbqCfg taicbqCfg : tAicbqCfgs) {
            TAicbqCfgModel model = new TAicbqCfgModel();
            BeanUtils.copyProperties(taicbqCfg, model);
            getOecByPgManualConfig(model);
            getWITaskSpecdate(model);
            getLogUploadRules(model);
            getImageConfig(model);
            resModels.add(model);
        }
        return resModels;
    }

    public TAicbqCfgModel findTAicbqCfgModel(String deviceSn, String stationCode, String useFlag) {
        TAicbqCfgModel resModel = new TAicbqCfgModel();
        TAicbqCfgExample example = new TAicbqCfgExample();
        TAicbqCfgExample.Criteria criteria = example.createCriteria();
        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(deviceSn)) {
            criteria.andDeviceSnEqualTo(deviceSn);
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(stationCode)) {
            criteria.andStationCodeEqualTo(stationCode);
        }

        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(useFlag)) {
            criteria.andUseFlagEqualTo(useFlag);
        }
        example.setOrderByClause("CREATE_TIME desc");
        List<TAicbqCfg> tAicbqCfgs = tAicbqCfgMapper.selectByExample(example);
        if (tAicbqCfgs.size() > 0) {
            BeanUtils.copyProperties(tAicbqCfgs.get(0), resModel);
        }
        return resModel;
    }

    //存入一条新配置，并把之前的配置改为失效
    public TAicbqCfgModel saveTAicbqCfgAndupdate(TAicbqCfgModel model) {
        String deviceSn = model.getDeviceSn();
        TAicbqCfgExample example = new TAicbqCfgExample();
        TAicbqCfgExample.Criteria criteria = example.createCriteria();
        if (!io.netty.util.internal.StringUtil.isNullOrEmpty(model.getDeviceSn())) {
            criteria.andDeviceSnEqualTo(deviceSn);
        } else {
            criteria.andStationCodeEqualTo(model.getStationCode());
        }

        criteria.andUseFlagEqualTo("1");
        List<TAicbqCfg> tAicbqCfgsList = tAicbqCfgMapper.selectByExample(example);
        //把以有配置至为失效，并增加新配置
        for (TAicbqCfg cfg : tAicbqCfgsList) {
            cfg.setUseFlag("0");
            cfg.setInvalidTime(new Date());
            tAicbqCfgMapper.updateByPrimaryKey(cfg);
        }
        model.setUseFlag("1");
        //model.setTaskDownId(StringUtil.getUuid());
        model.setCfgId(StringUtil.getUuid());
        model.setCreateTime(new Date());
        TAicbqCfg newcfg = new TAicbqCfg();

        //配置表中的设备类型使用台账中的,因为各种表的协议未统一,有的有类型有的没有 2024-01-10 guozhao
        DeviceAccModel accModel = deviceAccService.findDeviceAccBysn(model.getDeviceSn());
        if (accModel != null) {
            model.setDeviceType(accModel.getDeviceType());
        }

        BeanUtils.copyProperties(model, newcfg);
        tAicbqCfgMapper.insert(newcfg);
        model.setId(newcfg.getId());
        return model;
    }

    //将数据库中存储的24位坐标串,转换到对象中的6个坐标点
    private TAicbqCfgModel getOecByPgManualConfig(TAicbqCfgModel model) {
        if (StringUtils.isNotEmpty(model.getPgManualConfig()) && model.getPgManualConfig().length() == 24) {
            String pgManualConfigCol = "";
            for (int i = 0; i < model.getPgManualConfig().length(); i += 4) {
                String temp = model.getPgManualConfig().substring(i, i + 4);
                if (i == 0) {
                    model.setOriginx(Integer.parseInt(temp));
                    pgManualConfigCol += (temp + ",");
                } else if (i == 4) {
                    model.setOriginy(Integer.parseInt(temp));
                    pgManualConfigCol += (temp + " | ");
                } else if (i == 8) {
                    model.setEndx(Integer.parseInt(temp));
                    pgManualConfigCol += (temp + ",");
                } else if (i == 12) {
                    model.setEndy(Integer.parseInt(temp));
                    pgManualConfigCol += (temp + " | ");
                } else if (i == 16) {
                    model.setCenterx(Integer.parseInt(temp));
                    pgManualConfigCol += (temp + ",");
                } else if (i == 20) {
                    model.setCentery(Integer.parseInt(temp));
                    pgManualConfigCol += (temp);
                }
            }
            model.setPgManualConfigCol(pgManualConfigCol);
        }
        return model;
    }

    //大图上传规则---一个字段分割到前台所需要的多个字段
    private void getWITaskSpecdate(TAicbqCfgModel model) {
        if (StringUtils.isNotEmpty(model.getWiTaskSpecdateFlag()) && model.getWiTaskSpecdateFlag().length() == 12) {
            String msg = model.getWiTaskSpecdateFlag();
            //model.setWiTaskSpecdateEnable(Integer.parseInt(msg.substring(0,2))+"");

            //容错处理防止flag出现无效数据,导致出错 2023-07-28 guozhao
            if (StringUtil.isInteger(msg.substring(0, 2))) {
                int value = Integer.valueOf(msg.substring(0, 2));
                model.setWiTaskSpecdateEnable(value == 0 || value == 1 ? String.valueOf(value) : "0");
            } else {//无效数据
                model.setWiTaskSpecdateEnable("0");
            }

            Date date = DateUtil.parseTimeStr(msg.substring(2, 8), "yyMMdd");
            String wiTaskSpecdateDate = DateUtil.formateDate(date, "yyyyMMdd");
            model.setWiTaskSpecdateDate(wiTaskSpecdateDate);
            model.setWiTaskSpecdateDays(Integer.parseInt(msg.substring(8, 10)));
            model.setWiTaskSpecdateTimes(Integer.parseInt(msg.substring(10)));
        }
    }

    //日志上传规则---为前台将一个字段侵害到多个属性中
    private void getLogUploadRules(TAicbqCfgModel model) {
        if (StringUtils.isNotEmpty(model.getLogUploadRules()) && model.getLogUploadRules().length() == 16) {
            String msg = model.getLogUploadRules();
            //model.setLogUploadEnable(Integer.parseInt(msg.substring(0,2))+"");

            //容错处理防止flag出现无效数据,导致出错 2023-07-28 guozhao
            if (StringUtil.isInteger(msg.substring(0, 2))) {
                int value = Integer.valueOf(msg.substring(0, 2));
                model.setLogUploadEnable(value == 0 || value == 1 ? String.valueOf(value) : "0");
            } else {//无效数据
                model.setLogUploadEnable("0");
            }

            Date date = DateUtil.parseTimeStr(msg.substring(2, 8), "yyMMdd");
            String logUploadDate = DateUtil.formateDate(date, "yyyyMMdd");
            model.setLogUploadDate(logUploadDate);

            model.setLogUploadDays(Integer.parseInt(msg.substring(8, 10)));
            model.setLogUploadTimes(Integer.parseInt(msg.substring(10, 12)));
            model.setLogUploadMcuLevel(Integer.parseInt(msg.substring(12, 14)));
            model.setLogUploadAiLevel(Integer.parseInt(msg.substring(14)));
        }
    }

    //坐标人工配置值---为前台将一个字段分割到多个中
    private void getImageConfig(TAicbqCfgModel model) {
        if (StringUtils.isEmpty(model.getImageConfig()) || model.getImageConfig().length() != 24) return;
        String imageConfig = model.getImageConfig();
        //容错处理防止flag出现无效数据,导致出错 2023-07-28 guozhao
        if (StringUtil.isInteger(imageConfig.substring(0, 2))) {
            int value = Integer.valueOf(imageConfig.substring(0, 2));
            model.setImageConfigFlag(value == 0 || value == 1 ? String.valueOf(value) : "0");
        } else {//无效数据
            model.setImageConfigFlag("0");
        }
        int sign = Integer.valueOf(imageConfig.substring(2, 4)) == 0 ? -1 : 1;
        model.setImageLeanAngle(sign * Integer.valueOf(imageConfig.substring(4, 8)));
        model.setImageNumRegionXMin(Integer.valueOf(imageConfig.substring(8, 12)));
        model.setImageNumRegionYMin(Integer.valueOf(imageConfig.substring(12, 16)));
        model.setImageNumRegionXMax(Integer.valueOf(imageConfig.substring(16, 20)));
        model.setImageNumRegionYMax(Integer.valueOf(imageConfig.substring(20)));

    }

    /**
     * 校验拷机设备的采样间隔
     *
     * @param checkModel
     * @return
     */
    public String checkSampleIntervalByCheckDetails(TCheckModel checkModel) {
        List<TCheckDetailModel> detailModels = checkModel.getDetailList();
        if (detailModels == null) {
            detailModels = tCheckDetailService.findDetailsByCheckId(checkModel.getCheckId());
        }
        String err = "";  //间隔不正确的SN串
        String noCfg = "";//没有有效配置的SN串
        for (TCheckDetailModel detailModel : detailModels) {
            TAicbqCfgExample example = new TAicbqCfgExample();
            TAicbqCfgExample.Criteria criteria = example.createCriteria();
            criteria.andDeviceSnEqualTo(detailModel.getDeviceSn());
            criteria.andUseFlagEqualTo("1");
            criteria.andCreateTimeGreaterThanOrEqualTo(checkModel.getStartTime());//配置回执的入库时间应该大于拷机计划的开始时间
            example.setOrderByClause("CREATE_TIME desc");
            List<TAicbqCfg> tAicbqCfgs = tAicbqCfgMapper.selectByExample(example);
            if (tAicbqCfgs == null || tAicbqCfgs.size() == 0) {
                noCfg += detailModel.getDeviceSn();
                noCfg += ",";
            } else {
                if (tAicbqCfgs.get(0).getSampleInterval() != checkModel.getCheckIntverl()) {
                    err += detailModel.getDeviceSn();
                    err += ",";
                }
            }
        }

        if (StringUtils.isEmpty(err) && StringUtils.isEmpty(noCfg)) {
            return "所有设备的上传间隔均正确";
        } else {
            String msg = "";
            if (StringUtils.isNotEmpty(err)) {
                err = err.substring(0, err.length() - 1);
                msg = "上传间隔不正确的设备：" + err + ";";
            }
            if (StringUtils.isNotEmpty(noCfg)) {
                noCfg = noCfg.substring(0, noCfg.length() - 1);
                msg += ("没有配置信息的设备:" + noCfg);
            }
            return msg;
        }
    }

    /**
     * 根据设备sn查询AI抄表器参数配置
     * 注意:为了减少改动量,此方法内根据将服务侧设备合并配置到常规配置中了
     *
     * @param deviceSn
     * @return
     */
    public List<TAicbqCfgModel> findTAicbqCfgModelByDeviceSn(String deviceSn) {
        List<TAicbqCfgModel> resList = new ArrayList<>();
        DeviceAccModel deviceAccModel = deviceAccService.findDeviceAccBysn(deviceSn);
        TAicbqCfgModel cfgModel = findTAicbqCfgModel(deviceSn, "", "1");

        DeviceType deviceType = deviceAccModel == null ? null : DeviceType.findDeviceTypeByCode(deviceAccModel.getDeviceType());
        //服务器侧识的设备合并配置
        if (deviceType != null && deviceType == DeviceType.SERVER_SIDE) {
            TServerCfgModel serverCfgModel = serverCfgService.findTServerCfgModelByDeviceSn(deviceSn);
            if (serverCfgModel != null) {
                BeanUtils.copyProperties(serverCfgModel, cfgModel);
            }
        }
        if (cfgModel != null) {
            resList.add(cfgModel);
        }

        return resList;
    }
}
