package com.huatek.busi.service.impl;

import java.util.List;

import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.entity.BusiGeneratorSensor;
import com.huatek.busi.mapper.BusiGeneratorSensorMapper;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.frame.base.util.BusinessConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huatek.busi.dao.IecPointsConfDao;
import com.huatek.busi.dto.IecPointsConfDto;
import com.huatek.busi.entity.BusiSiteTree;
import com.huatek.busi.entity.IecPointsConf;
import com.huatek.busi.mapper.IecPointsConfMapper;
import com.huatek.busi.service.BusiSiteTreeService;
import com.huatek.busi.service.IecPointsConfService;
import com.huatek.busi.vo.IecPointsConfVo;
import com.huatek.frame.base.util.BeanUtils;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.util.date.TimeUtil;

/**
 * IEC104-业务点表配置表 ServiceImpl
 *
 * @author anker_cheng
 * @date 2019-8-1 16:15:50
 */
@Component
@Service(interfaceClass = IecPointsConfService.class)
@Transactional(rollbackFor = Exception.class)
public class IecPointsConfServiceImpl implements IecPointsConfService {
    @Autowired
    private IecPointsConfMapper iecPointsConfMapper;
    @Autowired
    private IecPointsConfDao iecPointsConfDao;

    @Reference(check = false)
    private BusiSiteTreeService busiSiteTreeService;

    @Autowired
    private BusiGeneratorSensorMapper busiGeneratorSensorMapper;



    @Override
    public PageInfo<IecPointsConfVo> findIecPointsConfPage(IecPointsConfDto iecPointsConfDto){
        return PageHelper.startPage(iecPointsConfDto.getPage(), iecPointsConfDto.getLimit())
        		.doSelectPageInfo(() -> iecPointsConfMapper.selectIecPointsConfPage(iecPointsConfDto));
    }

    @Override
    public int addIecPointsConf(IecPointsConfDto iecPointsConfDto){
        return saveOrUdpate(iecPointsConfDto);
    }

    @Override
    public IecPointsConfVo findIecPointsConfVo(String id){
        return iecPointsConfMapper.findIecPointsConfVo(id);
    }

    @Override
    public int updateIecPointsConf(IecPointsConfDto iecPointsConfDto) {
        return saveOrUdpate(iecPointsConfDto);
    }

    private synchronized int saveOrUdpate(IecPointsConfDto iecPointsConfDto) {
        if(StringUtils.isEmpty(iecPointsConfDto.getSiteTreeId())) {
            throw new OwlException("设备编码未必填");
        }
        BusiSiteTree busiSiteTree = busiSiteTreeService.findByPK(iecPointsConfDto.getSiteTreeId());
        if(busiSiteTree == null) {
            throw new OwlException("站点设备树节点不存在：" + iecPointsConfDto.getSiteTreeId());
        }
        String tablename = "";
        if(SiteConstants.SiteTreeEnum.GEN_EQM.getValue().equals(busiSiteTree.getEquipmentType())) {
            if (ObjectUtils.isEmpty(iecPointsConfDto.getMainEquipmentType())) {
                throw new OwlException("主设备类型不存在" + iecPointsConfDto.getMainEquipmentType());
            }
            if (ObjectUtils.isEmpty(iecPointsConfDto.getSubTreeId())) {
                throw new OwlException("站点子树不存在" + iecPointsConfDto.getSubTreeId());
            }
            if (ObjectUtils.isEmpty(iecPointsConfDto.getSubEquipmentType())) {
                throw new OwlException("监测装置类型不存在" + iecPointsConfDto.getSubEquipmentType());
            }
            if (SiteConstants.GeneratorTreeEnum.ZD_EQM.getValue().equals(iecPointsConfDto.getSubEquipmentType())) {
                tablename = "busi_generator_ampl";
            } else if (SiteConstants.GeneratorTreeEnum.YL_EQM.getValue().equals(iecPointsConfDto.getSubEquipmentType())) {
                tablename = "busi_generator_pressure";
            } else if (SiteConstants.GeneratorTreeEnum.JF_EQM.getValue().equals(iecPointsConfDto.getSubEquipmentType())) {
                tablename = "busi_generator_pd";
                iecPointsConfDto.setGtype(BusinessConstants.GeneratorAmplTypeEnum.jf.getValue());
            } else {
                throw new OwlException("监测类型不支持：" + iecPointsConfDto.getSubEquipmentType());
            }
            if (ObjectUtils.isEmpty(iecPointsConfDto.getSensorId())) {
                throw new OwlException("sensorId不存在" + iecPointsConfDto.getSensorId());
            }
            if (ObjectUtils.isEmpty(iecPointsConfDto.getSensorCode())) {
                throw new OwlException("sensor编码不存在" + iecPointsConfDto.getSensorCode());
            }
            if (ObjectUtils.isEmpty(iecPointsConfDto.getFiled())) {
                throw new OwlException("绑定字段不存在");
            }
            if (ObjectUtils.isEmpty(iecPointsConfDto.getFiledDesc())) {
                throw new OwlException("绑定字段注释不存在");
            }
            if(ObjectUtils.isEmpty(iecPointsConfDto.getGtype())) {
                throw new OwlException("装置类别不存在");
            }
            // sensorId为唯一判断，sensorCode，AmplType为冗余字段，校验sensorId和冗余字段是否一致
            BusiSensorVo sensorVo = busiGeneratorSensorMapper.getBusiSensorVoById(iecPointsConfDto.getSensorId());
            if (ObjectUtils.isEmpty(sensorVo)) {
                throw new OwlException("传感器不存在");
            } else {
                if (!iecPointsConfDto.getSensorCode().equals(sensorVo.getSensorCode())) {
                    throw new OwlException("请求参数不正确，请检查请求参数或重新勾选进行配置");
                }
                if (SiteConstants.GeneratorTreeEnum.ZD_EQM.getValue().equals(iecPointsConfDto.getSubEquipmentType()) ||
                        SiteConstants.GeneratorTreeEnum.YL_EQM.getValue().equals(iecPointsConfDto.getSubEquipmentType())) {
                    if (!iecPointsConfDto.getGtype().equals(sensorVo.getAmplType())) {
                        throw new OwlException("请求参数不正确，请检查请求参数或重新勾选进行配置");
                    }
                }
            }
        }
        Integer sadr = iecPointsConfMapper.checksadr(iecPointsConfDto.getId(), busiSiteTree.getSiteId(),
            iecPointsConfDto.getSadr().intValue());
        if (sadr != null) {
            throw new OwlException("信息体地址已存在：" + sadr);
        }
        IecPointsConf iecPointsConf = new IecPointsConf();
        BeanUtils.copyPropertiesWithIgnoreNull(iecPointsConfDto, iecPointsConf);
        if (!ObjectUtils.isEmpty(tablename)) {
            iecPointsConf.setTablename(tablename);
        }
        iecPointsConf.setDTime(TimeUtil.getLocalDateTime());
        iecPointsConf.setState("1");
        iecPointsConf.setSiteId(busiSiteTree.getSiteId());
        return iecPointsConfDao.saveOrUpate(iecPointsConf);
    }

    @Override
    public int deleteIecPointsConf(List<String> ids){
        int count = 0;
        if(ids == null || ids.size() == 0) {
            return count;
        }
        for(String id : ids) {
            count += iecPointsConfDao.del(id);
        }
        return count;
    }
}