package com.mvc.service.taizhang;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.BaseConstant;
import com.mvc.constant.OperationStatus;
import com.mvc.constant.QueryUserType;
import com.mvc.dao.StationAccMapper;
import com.mvc.entity.StationAcc;
import com.mvc.entity.StationAccExample;
import com.mvc.entity.TAffiliatedunit;
import com.mvc.interceptor.JwtInterceptor;
import com.mvc.model.*;
import com.mvc.model.biz.TMaintenanceRecordsV2Model;
import com.mvc.model.iotcard.TIotcardInfoModel;
import com.mvc.othermodel.GroupAndStationTree;
import com.mvc.service.TAffiliatedunitService;
//import com.mvc.service.TMaintenanceRecordsV2Service;
import com.mvc.service.TMaintenanceRecordsV2Service;
import com.mvc.service.TUsingunitGroupService;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.copy.TServerReadService;
import com.mvc.service.dic.DicGeneralService;
import com.mvc.service.dic.DicSequenceStationService;
import com.mvc.service.iotcard.IotCardService;
//import com.mvc.utils.ChineseToEn;
import com.mvc.utils.DateUtil;
import com.mvc.utils.NumberUtil;
import com.mvc.utils.PinyinUtil;
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 org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class StationAccService {
    /**
     * 大事记 2024-03-27 guozhao
     * 将相关查询条件stationCode统一改为userDefinedCode
     * userDefinedCode 作为用户定义的编码,stationCode作为设备中设置的编码
     */

    @Resource
    private StationAccMapper stationAccMapper;

    @Resource
    private StationGroupService stationGroupService;

    @Resource
    private DeviceAccService deviceAccService;

    @Resource
    private TAffiliatedunitService tAffiliatedunitService;

    @Resource
    private TUsingunitGroupService tUsingunitGroupService;

    @Resource
    private CustomUserService customUserService;

    @Resource
    private TAireadService tAireadService;

    @Resource
    private TTaskDownService tTaskDownService;

    @Resource
    private TServerReadService tServerReadService;

    @Resource
    private DicGeneralService dicGeneralService;

    @Resource
    private IotCardService iotCardService;

    @Resource
    private DicSequenceStationService dicSequenceStationService;

    @Resource
    private TaskRemoteCfgService taskRemoteCfgService;

    @Resource
    private TMaintenanceRecordsV2Service maintenanceRecordsV2Service;

    public Map<String, Object> findAllStationAcc(Integer page, Integer rows) {
        Map<String, Object> resMap = new HashMap<>();
        Page<Object> pageObject = PageHelper.startPage(page, rows);
        List<StationAcc> StationAccs = stationAccMapper.selectByExample(null);
        List<StationAccModel> resList = new ArrayList<>();
        for (StationAcc StationAcc : StationAccs) {
            StationAccModel model = new StationAccModel();
            BeanUtils.copyProperties(StationAcc, model);
            //添加遥测站分组名称
            if (model.getGroupCode() != null) {
                StationGroupModel stationGroup = stationGroupService.findStationGroupBygroupCode(model.getGroupCode());
                if (stationGroup != null) {
                    model.setGroupName(stationGroup.getGroupName());
/*                    TCustomrModel tCustomrModel = tCustomrService.findTCustomrByCustomId(stationGroup.getCustomerId());
                    if(tCustomrModel!=null){
                        model.setOtherName(tCustomrModel.getOtherName());
                    }*/
                }
            }
            resList.add(model);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    /**
     * 获取所有记录
     *
     * @return
     */
    public List<StationAcc> findAllStationAcc() {
        return stationAccMapper.selectByExample(null);
    }

    public List<StationAccModel> findStationListByGroupcode(String groupCode) {
        List<StationAccModel> resList = new ArrayList<>();
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andGroupCodeEqualTo(groupCode);
        List<StationAcc> findlist = stationAccMapper.selectByExample(example);
        for (int i = 0; i < findlist.size(); i++) {
            StationAcc stationAcc = findlist.get(i);
            StationAccModel model = new StationAccModel();
            BeanUtils.copyProperties(stationAcc, model);
            resList.add(model);
        }
        return resList;
    }

    public Map<String, Object> saveStationAcc(StationAccModel model) {
        //判断stationcode是否存在
        Map<String, Object> resMap = new HashMap<>();

        String stationCode = model.getUserDefinedCode();
        if (model.getMeterId().equals("1")) {
            if (StringUtils.isEmpty(model.getUserDefinedCode())) {
                resMap.put("error", "接入水务系统时,站点编码不能为空");
                return resMap;
            }
            if (model.getUserDefinedCode().length() != BaseConstant.LENGTH_STATION_CODE) {
                resMap.put("error", "接入水务系统时,站点编码长度应为10位");
                return resMap;
            }
            model.setStationCode(stationCode);
        } else {
            //非水务系统可为空,系统生成StationCode,UserDefinedCode=StationCode
            stationCode = dicSequenceStationService.generatorNextCode();
            model.setStationCode(stationCode);
            if (StringUtils.isEmpty(model.getUserDefinedCode())) {
                model.setUserDefinedCode(stationCode);
            }
        }

        if (StringUtils.isEmpty(stationCode) || stationCode.length() != 10 || !NumberUtil.isNumberic(stationCode)) {
            resMap.put("error", "遥测站代码不合法");
            return resMap;
        }

        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andStationCodeEqualTo(model.getStationCode());
        List<StationAcc> stationAccs = stationAccMapper.selectByExample(example);
        if (stationAccs.size() > 0) {
            resMap.put("error", "遥测站代码已经存在");
            return resMap;
        }

        if (StringUtils.isNotEmpty(model.getStationName())) {
            model.setStationPy(PinyinUtil.getPinYinHeadChar(model.getStationName(), true));
        }
        if (StringUtils.isEmpty(model.getDeviceSetupFlag())) {
            model.setDeviceSetupFlag("0");
        }
        model.setCreateTime(new Date());
        model.setReviewFlag(StringUtils.isNotEmpty(model.getReviewFlag()) ? model.getReviewFlag() : "0");
        StationAcc StationAcc = new StationAcc();
        BeanUtils.copyProperties(model, StationAcc);
        int insert = stationAccMapper.insert(StationAcc);
        if (StringUtils.isNotEmpty(model.getDeviceSn()) && insert > 0) {
            addTaskDown(StationAcc);
        }
        model.setId(StationAcc.getId());
        resMap.put("res", model);

        return resMap;
    }

    public Map<String, Object> updateStationAcc(StationAccModel model) {
        //水务系统,用户改了自定义编码,要同步更新StationCode 2024-04-15 guozhao
        StationAcc stationAcc = stationAccMapper.selectByPrimaryKey(model.getId());
        //判model.getMeterId()==null是为了防止有旧数据没有MeterId 2024-04-17 guozhao
        if (model.getUserDefinedCode() != null) {
            if (model.getMeterId() == null || (model.getMeterId().equals("1"))) {
                model.setStationCode(model.getUserDefinedCode());
            }
        }
        //站名发生改变
        if(!stationAcc.getStationName().equals(model.getStationName())){
            model.setStationPy(PinyinUtil.getPinYinHeadChar(model.getStationName(), true));
        }

        Map<String, Object> resMap = new HashMap<>();
        //判断stationcode是否存在
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andStationCodeEqualTo(model.getStationCode());
        List<StationAcc> stationAccs = stationAccMapper.selectByExample(example);
        if (stationAccs.size() > 0 && !(model.getId().intValue() == stationAccs.get(0).getId().intValue())) {
            resMap.put("error", "遥测站代码已经存在");
            return resMap;
        }

        BeanUtils.copyProperties(model, stationAcc);
        int i = stationAccMapper.updateByPrimaryKey(stationAcc);
        resMap.put("res", model);

        return resMap;
    }

    public int deleteStationAcc(int id) {
        //先把设备台账的遥测站码置控
        StationAcc stationAcc = stationAccMapper.selectByPrimaryKey(id);
        if (StringUtils.isNotEmpty(stationAcc.getDeviceSn())) {
            DeviceAccModel deviceAccModel = deviceAccService.findDeviceAccBysn(stationAcc.getDeviceSn());
            //如果没有台账此处会报错(加判断,应该在加遥测站时,控制一下有没有设备台账) 2022-07-06 guozhao
            if (deviceAccModel != null) {
                deviceAccModel.setStationCode(null);
                deviceAccService.updateDeviceAcc(deviceAccModel);
            }
        }
        int i = stationAccMapper.deleteByPrimaryKey(id);

        //刷新静态列表
        StationAccModel model = new StationAccModel();
        model.setId(id);

        return i;
    }

    /**
     * 根据设备SN获取站信息
     *
     * @param deviceSn
     * @return author gz 2022-6-21
     */
    public StationAccModel findStationAccByDeviceSn(String deviceSn) {
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andDeviceSnEqualTo(deviceSn);
        List<StationAcc> findlist = stationAccMapper.selectByExample(example);
        if (findlist != null && findlist.size() > 0) {
            StationAccModel model = new StationAccModel();
            BeanUtils.copyProperties(findlist.get(0), model);
            return model;
        }
        return null;
    }

    /**
     * 根据stationCode获取对象
     *
     * @param stationCode
     * @return
     */
    public StationAccModel findStationAccByStationCode(String stationCode) {
        if (StringUtils.isEmpty(stationCode)) return null;
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andStationCodeEqualTo(stationCode);

        return findModelByExample(example);
    }

    /**
     * 根据userDefinedCode获取对象
     * 此方法不严谨,不同unitCode下可能存在相同的情况(后续考虑) 2022-07-06 guozhao
     *
     * @param userDefinedCode
     * @return
     */
    public StationAccModel findStationAccByUserDefinedCode(String userDefinedCode) {
        if (StringUtils.isEmpty(userDefinedCode)) return null;
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andUserDefinedCodeEqualTo(userDefinedCode);

        return findModelByExample(example);
    }

    /**
     * 根据userDefinedCode和unitCode获取对象
     *
     * @param userDefinedCode
     * @return
     */
    public StationAccModel findStationAccByUserDefinedCode(String userDefinedCode, String unitCode) {
        if (StringUtils.isEmpty(userDefinedCode)) return null;
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andUserDefinedCodeEqualTo(userDefinedCode);
        if (StringUtils.isNotEmpty(unitCode)) {
            criteria.andUnitCodeEqualTo(unitCode);
        }

        return findModelByExample(example);
    }

    /**
     * 根据example获取Model
     *
     * @param example
     * @return
     */
    private StationAccModel findModelByExample(StationAccExample example) {
        StationAccModel model = null;
        List<StationAcc> findlist = stationAccMapper.selectByExample(example);
        if (findlist != null && findlist.size() > 0) {
            model = new StationAccModel();
            BeanUtils.copyProperties(findlist.get(0), model);
        }
        return model;
    }

    public List<StationAccModel> findStationaccModelsByExample(StationAccExample example) {
        List<StationAccModel> resList = new ArrayList<>();
        List<StationAcc> findlist = stationAccMapper.selectByExample(example);
        for (StationAcc acc : findlist) {
            StationAccModel model = new StationAccModel();
            BeanUtils.copyProperties(acc, model);
            resList.add(model);
        }
        return resList;
    }

    /**
     * 根据stationCodes获取Map
     *
     * @param stationCodes （code1,code2）
     * @return
     */
    public Map<String, StationAccModel> findStationAccMapByStationCodes(String stationCodes) {
        if (StringUtils.isEmpty(stationCodes)) return null;
        //返回MAP是为了使用时不需要遍例
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();

        List<String> codes = Arrays.asList(stationCodes.split(","));
        if (codes == null || codes.size() == 0) return null;
        criteria.andStationCodeIn(codes);

        Map<String, StationAccModel> accModelMap = new HashMap<>();
        List<StationAcc> findlist = stationAccMapper.selectByExample(example);
        for (StationAcc acc : findlist) {
            StationAccModel model = new StationAccModel();
            BeanUtils.copyProperties(acc, model);
            accModelMap.put(acc.getStationCode(), model);
        }

        return accModelMap;
    }

    //按条件查询遥测站台账
    public Map<String, Object> findByCondition(StationAccModel model) {
        Map<String, Object> resMap = new HashMap<>();
        List<StationAccModel> res = new ArrayList<>();
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotEmpty(model.getUserDefinedCode())) {//根据用户自定义代码查询
            if (model.getUserDefinedCode().length() == BaseConstant.LENGTH_STATION_CODE) {
                criteria.andUserDefinedCodeEqualTo(model.getUserDefinedCode());
            } else {
                criteria.andUserDefinedCodeLike('%' + model.getUserDefinedCode() + "%");
            }
        }
        if (StringUtils.isNotEmpty(model.getStationCode())) {//根据站代码模糊查询
            if (model.getStationCode().length() == BaseConstant.LENGTH_STATION_CODE) {
                criteria.andStationCodeEqualTo(model.getStationCode());
            } else {
                criteria.andStationCodeLike('%' + model.getStationCode() + "%");
            }
        }
        if (StringUtils.isNotEmpty(model.getStationName())) {//遥测站名称(传过来的是字母则按拼音查询)
            if (StringUtil.is_alpha(model.getStationName())) {
                criteria.andStationPyLike("%" + model.getStationName() + "%");
            } else {
                criteria.andStationNameLike("%" + model.getStationName() + "%");
            }
        }
        if (StringUtils.isNotEmpty(model.getStationPy())) {//遥测站名称拼音首字母
            criteria.andStationPyLike(StringUtil.getLikeFormat(model.getStationPy()));
        }
        if (StringUtils.isNotEmpty(model.getDeviceSn())) {//设备sn
            if (model.getDeviceSn().length() == BaseConstant.LENGTH_DEVICE_SN) {
                criteria.andDeviceSnEqualTo(model.getDeviceSn());
            } else {
                criteria.andDeviceSnLike(StringUtil.getLikeFormat(model.getDeviceSn()));
            }
        }
        if (StringUtils.isNotEmpty(model.getDeviceSetupFlag())) {//安装标志
            criteria.andDeviceSetupFlagEqualTo(model.getDeviceSetupFlag());
        }
        if (StringUtils.isNotEmpty(model.getUseFlag())) {//在用标记
            criteria.andUseFlagEqualTo(model.getUseFlag());
        }
        if (StringUtils.isNotEmpty(model.getUnitCode())) {
            criteria.andUnitCodeEqualTo(model.getUnitCode());//使用单位 2022-07-29 guozhao
        }
        if (StringUtils.isNotEmpty(model.getVisUnitCodes())) {
            criteria.andVisUnitCodesLike("%" + model.getVisUnitCodes() + "%");
        }
        if (StringUtils.isNotEmpty(model.getReviewFlag())) {
            criteria.andReviewFlagEqualTo(model.getReviewFlag());   //供生成审核数据时使用
        }

        if (StringUtils.isNotEmpty(model.getIotCardDuedate())) {//卡到期日小于当前
            criteria.andIotCardDuedateLessThanOrEqualTo(model.getIotCardDuedate());
        }

        if (model.getIotCardRemaingprs() != null) {//余额小于此值
            criteria.andIotCardRemaingprsLessThanOrEqualTo(model.getIotCardRemaingprs());
        }

        if (StringUtils.isNotEmpty(model.getIotCardWorkingcondition())) {//卡状态
            criteria.andIotCardWorkingconditionEqualTo(model.getIotCardWorkingcondition());
        }

        if (StringUtils.isNotEmpty(model.getDeviceType())) {//设备类型
            criteria.andDeviceTypeEqualTo(model.getDeviceType());
        }

        //非内部用户要过滤本单位的遥测站点
        if (StringUtils.isNotEmpty(model.getCreateUnitCode())) {
            TAffiliatedunitModel pModel = tAffiliatedunitService.findTAffiliatedunit(model.getCreateUnitCode());
            //异常情况,单位被删除等... 2024-04-07 guozhao
            if (pModel == null || pModel.getUnitType() == null) {
                criteria.andCreateUnitCodeIsNull();
                criteria.andCreateUnitCodeIsNotNull();
            } else if (pModel.getUnitType().equals("4")) {
                criteria.andUnitCodeEqualTo(pModel.getUnitCode());                              //用水户,只看自己的水表
            } else {
                if (StringUtils.isNotEmpty(pModel.getCreateUnitFalg()) && pModel.getCreateUnitFalg().equals("1")) {
                    criteria.andCreateUnitCodeEqualTo(model.getCreateUnitCode());               //创建用水户的单位,只看自己创建的
                } else {
                    criteria.andVisUnitCodesLike("%" + model.getCreateUnitCode() + "%");  //非用水记也非创建单位,只看自己
                }
            }
        }

        example.setOrderByClause("ID DESC");
        Page<Object> pageObject = PageHelper.startPage(model.getPage(), model.getRows());
        List<StationAcc> findlist = stationAccMapper.selectByExample(example);
        for (int i = 0; i < findlist.size(); i++) {
            StationAccModel m = new StationAccModel();
            BeanUtils.copyProperties(findlist.get(i), m);

            if (StringUtils.isNotEmpty(m.getUnitCode())) {
                TAffiliatedunitModel unitModel = tAffiliatedunitService.findTAffiliatedunit(m.getUnitCode());
                if (unitModel != null) {
                    m.setUnitName(unitModel.getUnitName());
                }
            }
            res.add(m);
        }

        resMap.put("total", pageObject.getTotal());
        resMap.put("list", res);
        return resMap;
    }

    public List<GroupAndStationTree> findStationTreeByUserId(String userId) {
        CustomUserModel model = customUserService.findCustomUserModelByUserId(userId);
        return findStationTreeByUserModel(model);
    }

    /**
     * 根据关联单位查询列表
     *
     * @param unitCode
     * @return
     */
    public List<StationAccModel> findStationAccByUnitCode(String unitCode) {
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andUnitCodeEqualTo(unitCode);
        example.setOrderByClause("DEVICE_TYPE,CAST(regexp_substr(STATION_NAME, '[0-9]+') AS UNSIGNED),STATION_NAME");//名称优化先按数字排
        List<StationAccModel> res = selectByExample(example);
        return res;
    }

    /**
     * 取全部树
     *
     * @return
     */
    public List<GroupAndStationTree> findAllStationTree() {
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andUnitCodeIsNotNull();
        example.setOrderByClause("DEVICE_TYPE,CAST(regexp_substr(STATION_NAME, '[0-9]+') AS UNSIGNED),STATION_NAME");
        List<StationAcc> list = stationAccMapper.selectByExample(example);
        return findStationTreeByStationAccList(list);
    }

    public List<GroupAndStationTree> findStationTreeByUserModel(CustomUserModel userModel) {
        return findStationTreeByUnitCode(userModel.getUnitCode());
    }

    public List<GroupAndStationTree> findStationTreeByUnitCode(String unitCode) {
        TAffiliatedunitModel userUnitModel = tAffiliatedunitService.findTAffiliatedunit(unitCode);

        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        if (userUnitModel.getUnitType().equals("4")) {
            criteria.andUnitCodeEqualTo(unitCode);
        } else {
            criteria.andVisUnitCodesLike("%" + unitCode + "%");
        }
        example.setOrderByClause("DEVICE_TYPE,CAST(regexp_substr(STATION_NAME, '[0-9]+') AS UNSIGNED),STATION_NAME");
        List<StationAcc> list = stationAccMapper.selectByExample(example);
        return findStationTreeByStationAccList(list);
    }

    public List<GroupAndStationTree> findStationTreeByStationAccList(List<StationAcc> list) {
        if (list == null || list.size() == 0) return null;
        List<GroupAndStationTree> resList = new ArrayList<>();
        Map<String, List<StationAcc>> map = list.stream().filter(item -> StringUtils.isNotBlank(item.getUnitCode()))
                .collect(Collectors.groupingBy(t -> t.getUnitCode()));

        Map<String, TAffiliatedunit> affiliatedunitMap = tAffiliatedunitService.findAllAffiliatedunitMap();
        for (String key : map.keySet()) {
            ////TAffiliatedunitModel unitModel = tAffiliatedunitService.findTAffiliatedunit(key);//循环查效率太低
            if (!affiliatedunitMap.containsKey(key)) {
                continue;
            }
            TAffiliatedunit unitModel = affiliatedunitMap.get(key);

            List<StationAcc> values = map.get(key);

            //用户无下级
            GroupAndStationTree tree = new GroupAndStationTree();
            tree.setId(key);
            int num = values == null ? 0 : values.size();
            tree.setCode(unitModel.getUnitCode());
            tree.setLabel(unitModel.getUnitName() + "[" + num + "]");
            tree.setType("0");
            tree.setParentcode("0");
            tree.setLabelpy(unitModel.getUnitNamePy());
            //tree.setData(map.get(key));
            resList.add(tree);

            //List<StationAcc> noGroupCodes=new ArrayList<>();            //没有子分组的设备列表
            List<TUsingunitGroupModel> groups = tUsingunitGroupService.findTUsingunitGroupByUnitCode(unitModel.getUnitCode());
            if (groups != null && groups.size() > 0) {
                //用户有下级(测试先处理一级)
                for (TUsingunitGroupModel groupModel : groups) {
                    GroupAndStationTree treeGroup = new GroupAndStationTree();
                    treeGroup.setId(groupModel.getGroupCode());
                    treeGroup.setCode(groupModel.getGroupCode());
                    //treeGroup.setData(groupModel);
                    treeGroup.setLabel(groupModel.getGroupName());
                    treeGroup.setType("1");
                    treeGroup.setParentcode(unitModel.getUnitCode());
                    treeGroup.setParentname(unitModel.getUnitName());
                    resList.add(treeGroup);

                    //先加载子分组
                    resList.addAll(recursionChild(groupModel, values));

                    //再加载站点
                    Iterator<StationAcc> iterator = values.iterator();
                    while (iterator.hasNext()) {
                        StationAcc acc = iterator.next();
                        if (groupModel.getStationCodes() != null && groupModel.getStationCodes().contains(acc.getStationCode())) {
                            GroupAndStationTree treeAcc2 = new GroupAndStationTree();
                            treeAcc2.setId(acc.getStationCode());
                            treeAcc2.setCode(acc.getStationCode());
                            treeAcc2.setLabel(acc.getStationName());
                            treeAcc2.setLabelpy(acc.getStationPy());
                            treeAcc2.setType("2");
                            //treeAcc2.setData(acc);
                            treeAcc2.setParentcode(groupModel.getGroupCode());
                            treeAcc2.setParentname(groupModel.getGroupName());
                            treeAcc2.setDeviceType(StringUtils.isEmpty(acc.getDeviceType()) ? "1" : acc.getDeviceType());
                            treeAcc2.setLabelpy(acc.getStationPy());
                            resList.add(treeAcc2);
                            iterator.remove();
                        }
                    }
                }
            }


            for (StationAcc acc : values) {
                GroupAndStationTree treeAcc = new GroupAndStationTree();
                treeAcc.setId(acc.getStationCode());
                treeAcc.setCode(acc.getStationCode());
                treeAcc.setLabel(acc.getStationName());
                treeAcc.setLabelpy(acc.getStationPy());
                treeAcc.setType("2");
                treeAcc.setDeviceType(StringUtils.isEmpty(acc.getDeviceType()) ? "1" : acc.getDeviceType());
                //treeAcc.setData(acc);
                treeAcc.setParentcode(unitModel.getUnitCode());
                treeAcc.setParentname(unitModel.getUnitName());
                resList.add(treeAcc);
            }
        }

        //resList = resList.stream().sorted(Comparator.comparing(GroupAndStationTree::getCode, Comparator.nullsFirst(String::compareTo))).collect(Collectors.toList());
        return resList;
    }

    //上面只处理了一级,下面开始使用递归处理多级
    private List<GroupAndStationTree> recursionChild(TUsingunitGroupModel parentModel, List<StationAcc> values) {
        List<GroupAndStationTree> resList = new ArrayList<>();
        List<TUsingunitGroupModel> groups = tUsingunitGroupService.findTUsingunitGroupByUnitCode(parentModel.getGroupCode());
        if (groups != null && groups.size() > 0) {
            //用户有下级(测试先处理一级)
            for (TUsingunitGroupModel groupModel : groups) {
                GroupAndStationTree treeGroup = new GroupAndStationTree();
                treeGroup.setId(groupModel.getGroupCode());
                treeGroup.setCode(groupModel.getGroupCode());
                //treeGroup.setData(groupModel);
                treeGroup.setLabel(groupModel.getGroupName());
                treeGroup.setType("1");
                treeGroup.setParentcode(parentModel.getGroupCode());
                treeGroup.setParentname(parentModel.getGroupName());
                resList.add(treeGroup);

                Iterator<StationAcc> iterator = values.iterator();
                while (iterator.hasNext()) {
                    StationAcc acc = iterator.next();
                    if (groupModel.getStationCodes() != null && groupModel.getStationCodes().contains(acc.getStationCode())) {
                        GroupAndStationTree treeAcc2 = new GroupAndStationTree();
                        treeAcc2.setId(acc.getStationCode());
                        treeAcc2.setCode(acc.getStationCode());
                        treeAcc2.setLabel(acc.getStationName());
                        treeAcc2.setLabelpy(acc.getStationPy());
                        treeAcc2.setType("2");
                        //treeAcc2.setData(acc);
                        treeAcc2.setDeviceType(StringUtils.isEmpty(acc.getDeviceType()) ? "1" : acc.getDeviceType());
                        treeAcc2.setParentcode(groupModel.getGroupCode());
                        treeAcc2.setParentname(groupModel.getGroupName());
                        resList.add(treeAcc2);
                        iterator.remove();
                    }
                }

                List<GroupAndStationTree> childList = recursionChild(groupModel, values);
                if (childList != null && childList.size() > 0) {
                    resList.addAll(childList);
                }
            }
        }

        //parent本身带设备
        Iterator<StationAcc> iterator = values.iterator();
        while (iterator.hasNext()) {
            StationAcc acc = iterator.next();
            if (parentModel.getStationCodes() != null && parentModel.getStationCodes().contains(acc.getStationCode())) {
                GroupAndStationTree treeAcc2 = new GroupAndStationTree();
                treeAcc2.setId(acc.getStationCode());
                treeAcc2.setCode(acc.getStationCode());
                treeAcc2.setLabel(acc.getStationName());
                treeAcc2.setLabelpy(acc.getStationPy());
                treeAcc2.setType("2");
                treeAcc2.setDeviceType(StringUtils.isEmpty(acc.getDeviceType()) ? "1" : acc.getDeviceType());
                //treeAcc2.setData(acc);
                treeAcc2.setParentcode(parentModel.getGroupCode());
                treeAcc2.setParentname(parentModel.getGroupName());
                resList.add(treeAcc2);
                iterator.remove();
            }
        }

        return resList;
    }

    /**
     * 批量更新VisUnitCodes(站台归属模块使用)
     *
     * @param model
     * @return
     */
    public int updateVisUnitCodes(StationAccUpdataModel model) {
        if (model == null) return 0;
        int size = 0;

        List<String> stationCodes = model.getStationCodes().stream().filter(s -> s.length() < 12).collect(Collectors.toList());
        //查出该单位原来的授权站点
        List<GroupAndStationTree> trees = findStationTreeByUnitCode(model.getVisUnitCode());
        trees = trees == null ? new ArrayList<>() : trees.stream().filter(s -> s.getType().equals("2")).collect(Collectors.toList());
        List<String> treeStringList = new ArrayList<>();
        List<String> delList = new ArrayList<>();
        for (GroupAndStationTree tree : trees) {
            treeStringList.add(tree.getCode());
            delList.add(tree.getCode());
        }

        delList.removeAll(stationCodes);

        List<String> addList = stationCodes;
        addList.removeAll(treeStringList);              //新增加的站点

        for (String acc : delList) {
            if (StringUtils.isEmpty(acc) || acc.length() > 12) continue;         //前台会传给非站点的节点
            StationAccExample example = new StationAccExample();
            StationAccExample.Criteria criteria = example.createCriteria();
            criteria.andStationCodeEqualTo(acc);
            List<StationAcc> list = stationAccMapper.selectByExample(example);
            if (list != null && list.size() > 0) {
                StationAcc entity = list.get(0);
                String[] arr = entity.getVisUnitCodes().split(",");
                ArrayList<String> arrayList = new ArrayList<>(arr.length);
                Collections.addAll(arrayList, arr);
                if (arrayList.contains(model.getVisUnitCode())) {
                    arrayList.remove(model.getVisUnitCode());
                    entity.setVisUnitCodes(StringUtils.join(arrayList, ","));
                    stationAccMapper.updateByPrimaryKey(entity);
                    size++;
                }
            }
        }

        for (String acc : addList) {
            if (StringUtils.isEmpty(acc) || acc.length() > 12) continue;
            StationAccExample example = new StationAccExample();
            StationAccExample.Criteria criteria = example.createCriteria();
            criteria.andStationCodeEqualTo(acc);
            List<StationAcc> list = stationAccMapper.selectByExample(example);
            if (list != null && list.size() > 0) {
                StationAcc entity = list.get(0);
                String[] arr = entity.getVisUnitCodes().split(",");
                ArrayList<String> arrayList = new ArrayList<>(arr.length);
                Collections.addAll(arrayList, arr);
                if (!arrayList.contains(model.getVisUnitCode())) {
                    arrayList.add(model.getVisUnitCode());
                    entity.setVisUnitCodes(StringUtils.join(arrayList, ","));
                    int i = stationAccMapper.updateByPrimaryKey(entity);
                    size++;
                }
            }
        }
        return size;
    }

    /**
     * 判断当前选的站点归属是否相同,相同则返回归属unit串
     *
     * @param model
     * @return
     */
    public List<String> checkSameVisUnitCodes(StationAccUpdataModel model) {
        String unitCodes = "";
        for (String acc : model.getStationCodes()) {
            if (StringUtils.isEmpty(acc)) continue;
            StationAccExample example = new StationAccExample();
            StationAccExample.Criteria criteria = example.createCriteria();
            criteria.andStationCodeEqualTo(acc);
            List<StationAcc> list = stationAccMapper.selectByExample(example);
            if (list != null && list.size() > 0) {
                StationAcc entity = list.get(0);
                if (StringUtils.isEmpty(unitCodes)) {
                    unitCodes = entity.getVisUnitCodes();
                } else {
                    if (!unitCodes.equals(entity.getVisUnitCodes())) {
                        return null;
                    }
                }
            }
        }

        if (StringUtils.isNotEmpty(unitCodes)) {
            return Arrays.asList(unitCodes.split(","));
        }
        return null;
    }

    /**
     * 添加召测配置的记录(新保存的站台,自动召测配置)
     *
     * @param accModel
     */
    private void addTaskDown(StationAcc accModel) {
        if (accModel.getDeviceSetupFlag().equals("1") && StringUtils.isNotEmpty(accModel.getDeviceSn())) {
            TTaskDownModel model = new TTaskDownModel();
            model.setDeviceSn(accModel.getDeviceSn());
            model.setStationCode(accModel.getStationCode());
            model.setCreateMan("站点安装");
            model.setTaskType("3");
            model.setTaskLevel(1);
            if (!tTaskDownService.existTTaskDownSameLevel(model)) {
                tTaskDownService.saveTTaskDown(model);
            }
        }
    }

    /**
     * 根据单位代码获取可查看的所有遥测站点
     *
     * @param unitCode
     * @return
     */
    public List<StationAccModel> findAllStationAccListByUnitCode(String unitCode) {
        List<StationAccModel> res = new ArrayList<>();
        TAffiliatedunitModel userUnitModel = tAffiliatedunitService.findTAffiliatedunit(unitCode);

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

        if (userUnitModel == null || StringUtils.isEmpty(userUnitModel.getUnitType())) return res;

        if (userUnitModel.getUnitType().equals("4")) {
            criteria.andUnitCodeEqualTo(unitCode);
        } else {
            criteria.andVisUnitCodesLike("%" + unitCode + "%");
        }

        List<StationAcc> list = stationAccMapper.selectByExample(example);
        for (StationAcc stationAcc : list) {
            StationAccModel model = new StationAccModel();
            BeanUtils.copyProperties(stationAcc, model);
            res.add(model);
        }
        return res;
    }

    /**
     * 根据单位代码分页获取可查看的所有遥测站点
     *
     * @param unitCode
     * @return
     */
    public Map<String, Object> findAllStationAccListByUnitCode(String unitCode, String stationName, Integer page, Integer rows) {
        Map<String, Object> resMap = new HashMap<>();

        List<StationAccModel> resList = new ArrayList<>();
        TAffiliatedunitModel userUnitModel = tAffiliatedunitService.findTAffiliatedunit(unitCode);

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

        if (userUnitModel == null || StringUtils.isEmpty(userUnitModel.getUnitType())) return resMap;

        if (userUnitModel.getUnitType().equals("4")) {
            criteria.andUnitCodeEqualTo(unitCode);
        } else {
            criteria.andVisUnitCodesLike("%" + unitCode + "%");
        }
        if (StringUtils.isNotEmpty(stationName)) {
            criteria.andStationNameLike(StringUtil.getLikeFormat(stationName));
        }

        example.setOrderByClause("ID DESC");
        Page<Object> pageObject = PageHelper.startPage(page, rows);
        List<StationAcc> list = stationAccMapper.selectByExample(example);
        for (StationAcc stationAcc : list) {
            StationAccModel model = new StationAccModel();
            BeanUtils.copyProperties(stationAcc, model);
            resList.add(model);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    /**
     * 小程序接口开始
     *************************************************************************************************************/
    //根据站代码获取全部可查看的用水户
    public List<TAffiliatedunitModel> findTAffiliatedunitsByUnitCode(String unitCode) {
        List<TAffiliatedunitModel> res = new ArrayList<>();
        TAffiliatedunitModel userUnitModel = tAffiliatedunitService.findTAffiliatedunit(unitCode);

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

        if (!unitCode.equals(BaseConstant.SPECIAL_UNIT_CODE)) {       //小程序特殊处理,内部用户看全部用水户 2022-08-27 guozhao
            if (userUnitModel == null || StringUtils.isEmpty(userUnitModel.getUnitType())) return res;
            if (userUnitModel.getUnitType().equals("4")) {
                criteria.andUnitCodeEqualTo(unitCode);
            } else {
                criteria.andVisUnitCodesLike("%" + unitCode + "%");
            }
        }

        List<StationAcc> list = stationAccMapper.selectByExample(example);
        if (list != null) {
            Map<String, List<StationAcc>> map = list.stream().filter(item -> StringUtils.isNotBlank(item.getUnitCode()))
                    .collect(Collectors.groupingBy(t -> t.getUnitCode()));

            for (String key : map.keySet()) {
                TAffiliatedunitModel unitModel = tAffiliatedunitService.findTAffiliatedunit(key);
                if (unitModel != null) {
                    //绑定这个单位拥有的设备类型 2022-09-24 guozhao
                    Map<String, List<StationAcc>> typeMap = list.stream().filter(item -> StringUtils.isNotBlank(item.getDeviceType()) && StringUtils.isNotBlank(item.getUnitCode()) && item.getUnitCode().equals(key))
                            .collect(Collectors.groupingBy(t -> t.getDeviceType()));

                    List<DicGeneralModel> dicGeneralModelList = new ArrayList<>();
                    for (String type : typeMap.keySet()) {
                        DicGeneralModel dicGeneralModel = dicGeneralService.findADicGeneralModelByDicTypeAndKey("2", type);
                        if (dicGeneralModel != null) {
                            dicGeneralModel.setDeviceLableName(getDeviceLabelName(dicGeneralModel.getDicKey()));
                            dicGeneralModelList.add(dicGeneralModel);
                        }
                    }
                    unitModel.setDicGeneralList(dicGeneralModelList);
                    res.add(unitModel);
                }
            }
        }
        res = res.stream().sorted(Comparator.comparing(TAffiliatedunitModel::getUnitName, Comparator.nullsFirst(String::compareTo))).collect(Collectors.toList());
        return res;
    }

    //根据站代码下属的所有站点-含最新读数
    public Map<String, Object> findStationAccsByUnitCode(String unitCode, String deviceType, boolean isFiltered, Integer page, Integer rows) {
        Map<String, Object> resMap = new HashMap<>();
        List<StationAccModel> resList = new ArrayList<>();
        TAffiliatedunitModel userUnitModel = tAffiliatedunitService.findTAffiliatedunit(unitCode);

        long total = 0;

        if (userUnitModel != null && StringUtils.isNotEmpty(userUnitModel.getUnitType())) {
            Page<Object> pageObject = PageHelper.startPage(page, rows);
            StationAccExample example = new StationAccExample();
            StationAccExample.Criteria criteria = example.createCriteria();
            if (userUnitModel.getUnitType().equals("4")) {
                criteria.andUnitCodeEqualTo(unitCode);
            } else {
                criteria.andVisUnitCodesLike("%" + unitCode + "%");
            }
            if (StringUtils.isNotEmpty(deviceType)) {
                criteria.andDeviceTypeEqualTo(deviceType);
            }
            example.setOrderByClause("DEVICE_TYPE,CAST(regexp_substr(STATION_NAME, '[0-9]+') AS UNSIGNED),STATION_NAME");
            List<StationAcc> list = stationAccMapper.selectByExample(example);
            if (list != null && list.size() > 0) {
                for (StationAcc acc : list) {
                    StationAccModel model = new StationAccModel();
                    BeanUtils.copyProperties(acc, model);
                    TAireadModel aireadModel = null;
                    if (isFiltered) {
                        aireadModel = tAireadService.findReviewedAiReadModel(model.getStationCode(), isFiltered);
                    } else {
                        aireadModel = tAireadService.findLatesTAireadByStationCode(model.getStationCode());
                    }
                    model.settAireadModel(aireadModel);
                    if (aireadModel != null && StringUtils.isNotEmpty(aireadModel.getDeviceType()) && aireadModel.getDeviceType().equals("1")) {
                        List<TServerReadModel> serverReadModels = tServerReadService.findTServerReadByAiReadid(aireadModel.getAireadId());
                        if (serverReadModels != null && serverReadModels.size() > 0) {
                            aireadModel.setServersmallJpgUrl(serverReadModels.get(0).getSmallJpgUrl());
                        }

                    }
                    if (aireadModel != null) {
                        aireadModel.setDeviceUnitName(tAireadService.getDeviceUnitName(model));
                    }

                    resList.add(model);
                }
            }
            total = pageObject.getTotal();
        } else {
            System.out.println("站代码未匹配到单位对象或单位类型为空:findStationAccsByUnitCode__unitCode:" + unitCode);
        }

        resMap.put("total", total);
        resMap.put("list", resList);
        return resMap;
    }

    /**
     * 小程序接口结束
     *************************************************************************************************************/

    public List<YslModel> findYslByStationCodeAndTime(String unitCode, String time) {
        int month = Integer.valueOf(time.substring(4, 6));
        List<YslModel> resList = new ArrayList<>();
        List<StationAccModel> accList = findAllStationAccListByUnitCode(unitCode);
        for (int i = 0; i < accList.size(); i++) {
            StationAccModel acc = accList.get(i);
            YslModel yslModel = new YslModel();

            TAffiliatedunitModel unitModel = tAffiliatedunitService.findTAffiliatedunit(acc.getUnitCode());
            if (unitModel != null) {
                yslModel.setUnitname(unitModel.getUnitName());
            }

            yslModel.setStationCode(acc.getStationCode());
            yslModel.setStationName(acc.getStationName());
            TAireadModel tairead = tAireadService.findDataByMonth(acc.getStationCode(), time, "0");
            if (tairead != null) {
                yslModel.setResultValue(tairead.getResultValue());
                yslModel.setSmallJpgUrl(tairead.getSmallJpgUrl());
                yslModel.setSampleTime(tairead.getSampleTime());
            }
            resList.add(yslModel);
        }
        return resList;
    }

    /**
     * 根据站点名称获取站信息
     *
     * @param stationName
     * @return author gz 2022-6-21
     */
    public StationAccModel findStationAccByStationName(String stationName) {
        if (StringUtils.isEmpty(stationName)) {
            return null;
        }

        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andStationNameEqualTo(stationName);
        List<StationAcc> findlist = stationAccMapper.selectByExample(example);
        if (findlist != null && findlist.size() > 0) {
            StationAccModel model = new StationAccModel();
            BeanUtils.copyProperties(findlist.get(0), model);
            return model;
        }
        return null;
    }

    /**
     * 根据设备类型从通用字典中获取当前显示设备读数名称(累计水量还是压强)
     *
     * @param deviceType
     * @return
     */
    private String getDeviceLabelName(String deviceType) {
        if (StringUtils.isNotEmpty(deviceType)) {
            DicGeneralModel dicModel = dicGeneralService.findADicGeneralModelByDicTypeAndKey("12", deviceType);
            return dicModel == null ? "当前读数" : dicModel.getDicValue();
        }
        return "当前读数";
    }

    /**
     * 更新站点安装状态userDefinedCode
     *
     * @param setupModel
     * @return
     */
    public StationAccModel updateSetupStatus(TSetupModel setupModel) {
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andStationCodeEqualTo(setupModel.getStationCode());
        List<StationAcc> findlist = stationAccMapper.selectByExample(example);
        if (findlist != null && findlist.size() > 0) {
            StationAcc acc = findlist.get(0);
            acc.setDeviceSn(setupModel.getDeviceSn());
            acc.setDeviceSetupFlag("1");
            acc.setDeviceSetupMan(setupModel.getSetupMan());
            acc.setDeviceSetupDate(setupModel.getSetupTime());
            acc.setStationLon(setupModel.getStationLon());
            acc.setStationLat(setupModel.getStationLat());
            acc.setStationContacts(setupModel.getStationContact());
            acc.setUseFlag("1");   //状态变为启用
            acc.setReviewFlag("1");//默认打开审核
            stationAccMapper.updateByPrimaryKey(acc);
        }
        return null;
    }

    /**
     * 更新物联网卡信息
     *
     * @param stationCode
     * @param infoModel
     */
    public void updateIotCardInfo(String stationCode, TIotcardInfoModel infoModel) {
        if (StringUtils.isEmpty(stationCode) || infoModel == null) return;
        StationAccModel accModel = findStationAccByStationCode(stationCode);
        if (accModel == null) return;//没有台账

        //数据没有发生任何变化,不更新数据库
        if (StringUtils.isNotEmpty(accModel.getIotCardDuedate()) &&
                accModel.getIotCardDuedate().equals(infoModel.getDuedate()) &&
                accModel.getIotCardWorkingcondition().equals(infoModel.getWorkingcondition()) &&
                accModel.getIotCardRemaingprs().compareTo(infoModel.getRemaingprs()) == 0) {
            return;
        }

        accModel.setIotCardWorkingcondition(infoModel.getWorkingcondition());
        accModel.setIotCardDuedate(infoModel.getDuedate());
        accModel.setIotCardRemaingprs(infoModel.getRemaingprs());
        updateStationAcc(accModel);
    }

    /**
     * 从TIotCard表更新物联网卡信息
     */
    public void updateIotCardInfo() {
        List<StationAcc> list = stationAccMapper.selectByExample(null);
        for (StationAcc stationAcc : list) {
            TAireadModel aireadModel = tAireadService.findLatesTAireadByStationCode(stationAcc.getStationCode());
            if (aireadModel == null || StringUtils.isEmpty(aireadModel.getCcid())) continue;

            TIotcardInfoModel iotcardInfoModel = iotCardService.queryLocalCardInfoByCCID(aireadModel.getCcid());
            if (iotcardInfoModel == null) continue;

            //数据没有发生任何变化,不更新数据库
            if (StringUtils.isNotEmpty(stationAcc.getIotCardDuedate()) &&
                    stationAcc.getIotCardDuedate().equals(iotcardInfoModel.getDuedate()) &&
                    stationAcc.getIotCardWorkingcondition().equals(iotcardInfoModel.getWorkingcondition()) &&
                    stationAcc.getIotCardRemaingprs().compareTo(iotcardInfoModel.getRemaingprs()) == 0) {
                continue;
            }

            stationAcc.setIotCardWorkingcondition(iotcardInfoModel.getWorkingcondition());
            stationAcc.setIotCardDuedate(iotcardInfoModel.getDuedate());
            stationAcc.setIotCardRemaingprs(iotcardInfoModel.getRemaingprs());
            stationAccMapper.updateByPrimaryKey(stationAcc);
        }
    }

    /** ---- 2024版APP使用的方法  2024-09-30 guozhao---- */
    /**
     * 安装设备到站点
     *
     * @param model
     */
    public StationAccModel installDeviceToSite(StationAccModel model) {
        StationAcc acc = stationAccMapper.selectByPrimaryKey(model.getId());
        acc.setDeviceSn(model.getDeviceSn());
        if (StringUtils.isNoneEmpty(model.getStationName()) && !acc.getStationName().equals(model.getStationName())) {//更新站名
            acc.setStationName(model.getStationName());
            acc.setStationPy(PinyinUtil.getPinYinHeadChar(model.getStationName(), true));
        }
        acc.setStationName(model.getStationName());
        acc.setDeviceSetupFlag(BaseConstant.VALID_FLAG);
        acc.setDeviceSetupDate(new Date());
        acc.setDeviceSetupMan(model.getDeviceSetupMan());
        acc.setMemo(model.getMemo());
        acc.setReviewFlag(BaseConstant.VALID_FLAG);
        acc.setUseFlag(BaseConstant.VALID_FLAG);
        if (model.getStationLon() != null) {
            acc.setStationLon(model.getStationLon());
            acc.setStationLat(model.getStationLat());
        }

        //远程配置
        TaskRemoteCfgModel taskRemoteCfgModel = new TaskRemoteCfgModel();

        taskRemoteCfgModel.setMaxDiscreteDuration(BaseConstant.MAX_DISCRETE_DURATION);//默认最大离散时长
        taskRemoteCfgModel.setFinishedFlag(BaseConstant.INVALID_FLAG);
        taskRemoteCfgModel.setDeviceSn(model.getDeviceSn());
        taskRemoteCfgModel.setStationCode(model.getStationCode());
        taskRemoteCfgModel.setCreateMan(model.getDeviceSetupMan());

        //全配置模式新增(同时修改间隔为60分钟) 2025-03-06 guozhao
        taskRemoteCfgModel.setSampleInterval(getSampleInterval(model.getDeviceSn()));
        taskRemoteCfgModel.setOperationStatus(OperationStatus.INSTALLED.getFlag());

        TaskRemoteCfgModel result = taskRemoteCfgService.saveTaskRemoteCfg(taskRemoteCfgModel);

        TMaintenanceRecordsV2Model maintenanceRecordsV2Model = new TMaintenanceRecordsV2Model(model, null, result);
        maintenanceRecordsV2Model = maintenanceRecordsV2Service.saveTMaintenanceRecordsV2(maintenanceRecordsV2Model);

        //在站点台账中记录运维表ID 2025-05-07 guozhao
        if (maintenanceRecordsV2Model != null && maintenanceRecordsV2Model.getId() != null) {
            acc.setSetupId(maintenanceRecordsV2Model.getId() + "");
        }
        //1更新台账
        stationAccMapper.updateByPrimaryKey(acc);

        return model;
    }

    /**
     * 替换设备
     *
     * @param model
     */
    public StationAccModel replaceDeviceToSite(StationAccModel model) {
        StationAcc acc = stationAccMapper.selectByPrimaryKey(model.getId());
        if (StringUtils.isNoneEmpty(model.getStationName()) && !acc.getStationName().equals(model.getStationName())) {//更新站名
            acc.setStationName(model.getStationName());
            acc.setStationPy(PinyinUtil.getPinYinHeadChar(model.getStationName(), true));
        }
        acc.setStationLon(model.getStationLon());
        acc.setStationLat(model.getStationLat());
        acc.setStationContacts(model.getStationContacts());
        acc.setDeviceSn(model.getDeviceSn());
        acc.setDeviceSetupFlag(BaseConstant.VALID_FLAG);
        acc.setDeviceSetupDate(new Date());
        acc.setDeviceSetupMan(model.getDeviceSetupMan());
        acc.setMemo(model.getMemo());

        TaskRemoteCfgModel oldCfgResModel = null;
        TaskRemoteCfgModel newCfgResModel = null;
        //2远程配置
        //2.1 改旧设备,去绑定,改间隔
        if (StringUtils.isNotEmpty(model.getOldDeviceSn())) {
            TaskRemoteCfgModel oldCfgModel = new TaskRemoteCfgModel();
            oldCfgModel.setDeviceSn(model.getOldDeviceSn());
            //使用全0会导致较多ID重复,会出现入库覆盖
            //oldCfgModel.setStationCode(BaseConstant.DEFAULT_STATION_CODE);
            oldCfgModel.setStationCode(model.getOldDeviceSn().substring(1));
            oldCfgModel.setSampleInterval(BaseConstant.MAX_SAMPLE_INTERVAL);
            oldCfgModel.setFinishedFlag(BaseConstant.INVALID_FLAG);
            oldCfgModel.setCreateMan(model.getDeviceSetupMan());
            oldCfgResModel = taskRemoteCfgService.saveTaskRemoteCfg(oldCfgModel);
        }
        //2.2 改新设备,绑定
        TaskRemoteCfgModel newCfgModel = new TaskRemoteCfgModel();
        newCfgModel.setDeviceSn(model.getDeviceSn());
        newCfgModel.setStationCode(model.getStationCode());
        //newCfgModel.setSampleInterval(BaseConstant.DEFAULT_SAMPLE_INTERVAL);//防止新设备里面的参数不是1440
        newCfgModel.setMaxDiscreteDuration(BaseConstant.MAX_DISCRETE_DURATION);
        newCfgModel.setFinishedFlag(BaseConstant.INVALID_FLAG);
        newCfgModel.setCreateMan(model.getDeviceSetupMan());

        //全配置模式新增(同时修改间隔为60分钟) 2025-03-06 guozhao
        newCfgModel.setSampleInterval(getSampleInterval(model.getDeviceSn()));
        newCfgModel.setOperationStatus(OperationStatus.INSTALLED.getFlag());
        newCfgResModel = taskRemoteCfgService.saveTaskRemoteCfg(newCfgModel);

        TMaintenanceRecordsV2Model maintenanceRecordsV2Model = new TMaintenanceRecordsV2Model(model, oldCfgResModel, newCfgResModel);
        maintenanceRecordsV2Model = maintenanceRecordsV2Service.saveTMaintenanceRecordsV2(maintenanceRecordsV2Model);
        //在站点台账中记录运维表ID 2025-05-07 guozhao
        if (maintenanceRecordsV2Model != null && maintenanceRecordsV2Model.getId() != null) {
            acc.setSetupId(maintenanceRecordsV2Model.getId() + "");
        }
        //1更新台账
        stationAccMapper.updateByPrimaryKey(acc);

        return model;
    }

    //获取设备采样间隔(设备如果支持投运状态管理,则使用60分钟,不支持,则使用1440),**等等再启用吧,模型还在训练中...
    private int getSampleInterval(String deviceSn) {
        TAireadModel aireadModel = tAireadService.findLatestTAireadByDeviceSn(deviceSn);
        if (aireadModel != null && aireadModel.getOperationStatus() != null) {
            return BaseConstant.PRE_COMMISSION_SAMPLE_INTERVAL;
        }
        return BaseConstant.DEFAULT_SAMPLE_INTERVAL;
    }

    //停用设备
    public StationAccModel deactivateDeviceToSite(StationAccModel model) {
        StationAcc acc = stationAccMapper.selectByPrimaryKey(model.getId());
        acc.setDeviceSn("");
        acc.setDeviceSetupFlag(BaseConstant.INVALID_FLAG);
        acc.setDeviceSetupDate(new Date());
        acc.setDeviceSetupMan(model.getDeviceSetupMan());
        acc.setReviewFlag(BaseConstant.INVALID_FLAG);
        acc.setUseFlag(BaseConstant.INVALID_FLAG);
        //1更新台账
        if (stationAccMapper.updateByPrimaryKey(acc) > 0) {
            //2远程配置
            TaskRemoteCfgModel CfgModel = new TaskRemoteCfgModel();
            CfgModel.setDeviceSn(model.getDeviceSn());
            //newCfgModel.setStationCode(BaseConstant.DEFAULT_STATION_CODE);
            CfgModel.setStationCode(model.getDeviceSn().substring(1));
            CfgModel.setSampleInterval(BaseConstant.MAX_SAMPLE_INTERVAL);
            CfgModel.setFinishedFlag(BaseConstant.INVALID_FLAG);
            CfgModel.setCreateMan(model.getDeviceSetupMan());

            taskRemoteCfgService.saveTaskRemoteCfg(CfgModel);
        }
        return model;
    }

    //根据站代码下属的所有站点-含最新读数
    public Map<String, Object> findStationAccForApp(StationAccModel accModel) {
        Map<String, Object> resMap = new HashMap<>();
        List<StationAccModel> resList = new ArrayList<>();

        long total = 0;

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

        if (StringUtils.isNotEmpty(accModel.getStationCode())) {
            String stationCode = accModel.getStationCode().trim();
            if (StringUtils.isNumeric(stationCode)) {//纯数字按站码查询
                if (stationCode.length() == BaseConstant.LENGTH_STATION_CODE) {
                    criteria.andStationCodeEqualTo(stationCode);
                } else {
                    criteria.andStationCodeLike(StringUtil.getLikeFormat(stationCode));
                }
            } else if (StringUtil.isLetterDigit(stationCode)) {//字母数字按拼音首字母
                criteria.andStationPyLike(StringUtil.getLikeFormat(stationCode.toUpperCase()));
            } else {//汉字
                criteria.andStationNameLike(StringUtil.getLikeFormat(stationCode));
            }
        }
        boolean isValid = false;
        if (accModel.getUnitCode() != null && accModel.getUnitCode().equals(BaseConstant.SPECIAL_UNIT_CODE)) {//内部用户
            isValid = true;
        } else if (StringUtils.isNotEmpty(accModel.getUnitCode())) {
            TAffiliatedunitModel userUnitModel = tAffiliatedunitService.findTAffiliatedunit(accModel.getUnitCode());
            if (userUnitModel != null && StringUtils.isNotEmpty(userUnitModel.getUnitType())) {
                if (userUnitModel.getUnitType().equals("4")) {
                    criteria.andUnitCodeEqualTo(accModel.getUnitCode());
                } else {
                    criteria.andVisUnitCodesLike(StringUtil.getLikeFormat(accModel.getUnitCode()));
                }
                if (StringUtils.isNotEmpty(accModel.getDeviceType())) {
                    criteria.andDeviceTypeEqualTo(accModel.getDeviceType());
                }
                isValid = true;
            }

        }//else {} //前台没给单位代码

        if (isValid) {
            Page<Object> pageObject = PageHelper.startPage(accModel.getPage(), accModel.getRows());
            example.setOrderByClause("DEVICE_TYPE,CAST(regexp_substr(STATION_NAME, '[0-9]+') AS UNSIGNED),STATION_NAME");
            List<StationAcc> list = stationAccMapper.selectByExample(example);
            if (list != null && list.size() > 0) {
                for (StationAcc acc : list) {
                    StationAccModel model = new StationAccModel();
                    BeanUtils.copyProperties(acc, model);
                    TAireadModel aireadModel = tAireadService.findLatesTAireadByStationCode(model.getStationCode());
                    model.settAireadModel(aireadModel);
                    if (aireadModel != null && StringUtils.isNotEmpty(aireadModel.getDeviceType()) && aireadModel.getDeviceType().equals("1")) {
                        List<TServerReadModel> serverReadModels = tServerReadService.findTServerReadByAiReadid(aireadModel.getAireadId());
                        if (serverReadModels != null && serverReadModels.size() > 0) {
                            aireadModel.setServersmallJpgUrl(serverReadModels.get(0).getSmallJpgUrl());
                        }
                    }
                    if (aireadModel != null) {
                        aireadModel.setDeviceUnitName(tAireadService.getDeviceUnitName(model));
                    }

                    resList.add(model);
                }
            }
            total = pageObject.getTotal();
        }

        resMap.put("total", total);
        resMap.put("list", resList);
        return resMap;
    }

    /**
     * 根据单位结构ID查询站点列表
     *
     * @param unitStructureId
     * @return
     */
    public List<StationAccModel> findStationAccByUnitCode(Integer unitStructureId) {
        StationAccExample example = new StationAccExample();
        StationAccExample.Criteria criteria = example.createCriteria();
        criteria.andUnitStructureIdEqualTo(unitStructureId);
        example.setOrderByClause("DEVICE_TYPE,CAST(regexp_substr(STATION_NAME, '[0-9]+') AS UNSIGNED),STATION_NAME");//名称优化先按数字排
        List<StationAccModel> res = selectByExample(example);
        return res;
    }

    private List<StationAccModel> selectByExample(StationAccExample example) {
        List<StationAcc> list = stationAccMapper.selectByExample(example);
        List<StationAccModel> res = new ArrayList<>();
        for (StationAcc acc : list) {
            StationAccModel model = new StationAccModel();
            BeanUtils.copyProperties(acc, model);
            res.add(model);
        }
        return res;
    }

    /**
     * 检查设备是否可用
     *
     * @param model
     * @param isReplace
     * @return
     */
    public String checkDeviceAvailability(StationAccModel model, boolean isReplace) {
        if (StringUtils.isEmpty(model.getDeviceSn())) {
            return "设备SN不能为空";
        }
        DeviceAccModel deviceAccModel = deviceAccService.findDeviceAccBysn(model.getDeviceSn());
        if (deviceAccModel == null) {
            return "新设备未在台账中登记,请联系供货商!";
        }

        TaskRemoteCfgModel cfgModel = taskRemoteCfgService.findUnfinishedTaskByDeviceSn(model.getDeviceSn());
        if (cfgModel != null) {
            return String.format("设备[%s]存在未执行任务\r\n由[%s]于[%s]创建", model.getDeviceSn(), cfgModel.getCreateMan(), DateUtil.formateDate(cfgModel.getCreateTime(), DateUtil.PATTERN_DATA_NORMAL));
        }

        TAireadModel aireadModel = tAireadService.findLatestTAireadByDeviceSn(model.getDeviceSn());
        if (aireadModel != null && aireadModel.getVoltage() != null && aireadModel.getVoltage().compareTo(BigDecimal.valueOf(3.3)) <= 0) {
            return String.format("设备[%s]电压过低,请更换设备!", model.getDeviceSn());
        }

        //此SN已被安装至其它站点
        StationAccModel stationAccModel = findStationAccByDeviceSn(model.getDeviceSn());
        if (stationAccModel != null) {
            return String.format("设备[%s]已被安装至站点\n[%s]", model.getDeviceSn(), stationAccModel.getStationName());
        }

        if (isReplace) {//更换
            if (StringUtils.isEmpty(model.getOldDeviceSn())) {
                return "旧设备SN不能为空";
            }
            DeviceAccModel oldDeviceAccModel = deviceAccService.findDeviceAccBysn(model.getOldDeviceSn());
            if (oldDeviceAccModel == null) {
                return "旧设备未在台账中登记,请检查编码是否正确";
            }

            TaskRemoteCfgModel OldCfgModel = taskRemoteCfgService.findUnfinishedTaskByDeviceSn(model.getDeviceSn());
            if (OldCfgModel != null) {
                return String.format("设备[%s]存在未执行任务\r\n由[%s]于[%s]创建", model.getDeviceSn(), OldCfgModel.getCreateMan(), DateUtil.formateDate(OldCfgModel.getCreateTime(), DateUtil.PATTERN_DATA_NORMAL));
            }
        }
        return null;
    }
}
