package com.casic.missiles.modular.system.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.casic.missiles.modular.system.model.BusConcentrator;
import com.casic.missiles.core.common.service.ICommonPermissionService;
import com.casic.missiles.core.datascope.DataScope;
import com.casic.missiles.core.log.LogObjectHolder;
import com.casic.missiles.core.util.ToolUtil;
import com.casic.missiles.modular.system.constant.DeviceConst;
import com.casic.missiles.modular.system.dao.BusConcentratorMapper;
import com.casic.missiles.modular.system.model.Device;
import com.casic.missiles.modular.system.service.IBusConcentratorService;
import com.casic.missiles.modular.system.util.Utility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.Validator;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 集中器信息表 服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2019-06-03
 */
@Service
public class BusConcentratorServiceImpl extends ServiceImpl<BusConcentratorMapper, BusConcentrator> implements IBusConcentratorService {
    private static final Logger logger = LoggerFactory.getLogger(BusConcentratorServiceImpl.class);
    @Autowired
    private Validator validator;
    @Autowired
    private ICommonPermissionService commonPermissionService;

    @Override
    public boolean updateById(BusConcentrator entity) {
        BusConcentrator old = this.selectById(entity.getId());
        LogObjectHolder.me().set(old);
        if (!old.getLat().equals(entity.getLat()) || !old.getLng().equals(entity.getLng())) {
            loadPostion(entity);
        }
        return super.updateById(entity);
    }

    @Override
    public List<BusConcentrator> selectConcentratorPage(Page<BusConcentrator> page, DataScope dataScope, String keywords, String status) {
        return this.baseMapper.selectConcentratorPage(page, dataScope, keywords, status);
    }

    @Override
    public List<String> addDeviceBatch(List<BusConcentrator> results) {
        BeanPropertyBindingResult beanPropertyBindingResult = new BeanPropertyBindingResult(Device.class, "集中器导入校验");
        List<String> list = new ArrayList<>();
        if (!ToolUtil.isEmpty(results)) {
            final Integer[] index = {0};
            results.forEach(busConcentrator -> {
                validator.validate(busConcentrator, beanPropertyBindingResult);
                index[0]++;
                if (beanPropertyBindingResult.hasErrors()) {
                    List<FieldError> errors = beanPropertyBindingResult.getFieldErrors();
                    errors.forEach(error -> {
                                list.add(" 第" + index[0] + "行，".concat(error.getDefaultMessage()));
                                return;
                            }
                    );
                    return;
                }
                if (new Long(0L).equals(busConcentrator.getDeptid())) {
                    busConcentrator.setDeptid(commonPermissionService.getCurrLoginUser().getDeptId());
                } else {
                    if (ToolUtil.isEmpty(commonPermissionService.getDeptName(busConcentrator.getDeptid()))) {
                        list.add(" 第" + index[0] + "行，权属单位不存在");
                        return;
                    }
                }

                if (ToolUtil.isNotEmpty(busConcentrator.getSetupdateFormat())) {
                    try {
                        busConcentrator.setSetupdate(new SimpleDateFormat("yyyy-MM-dd").parse(busConcentrator.getSetupdateFormat()));
                    } catch (Exception e) {
                        list.add(" 第" + index[0] + "行，时间格式不正确");
                        return;
                    }
                } else {
                    busConcentrator.setSetupdate(new Date());
                }

                //地图坐标转换
                loadPostion(busConcentrator);
                busConcentrator.setValid(DeviceConst.YES);
                busConcentrator.setTs(new Date());
                busConcentrator.setStatus(DeviceConst.NO);
            });
            if (ToolUtil.isNotEmpty(list)) {
                return list;
            }
            this.insertBatch(results);
        }

        return list;
    }

    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        if (ToolUtil.isNotEmpty(ids)) {
            ids.forEach(id -> {
                this.baseMapper.deleteById(id);
            });

        }
    }

    @Override
    public boolean insert(BusConcentrator entity) {
        if (!ToolUtil.isOneEmpty(entity.getLat(), entity.getLng())) {
            loadPostion(entity);
        }
        entity.setStatus(DeviceConst.NO);
        entity.setValid(DeviceConst.YES);
        entity.setTs(new Date());
        return super.insert(entity);
    }

    void loadPostion(BusConcentrator entity) {
        if (!ToolUtil.isOneEmpty(entity.getLat(), entity.getLng())) {
            Map<String, Object> baiduCoordinate = Utility.convertBaiduAPI(entity.getLng(), entity.getLat());
            Map<String, Object> gaodeCoordinate = Utility.convertGaodeAPI(entity.getLng(), entity.getLat());
            if (ToolUtil.isOneEmpty(baiduCoordinate, gaodeCoordinate)) {
                logger.error("{}坐标转换失败!", entity.getConcencode());
                return;
            }
            entity.setLatBaidu(baiduCoordinate.get("x").toString());
            entity.setLngBaidu(baiduCoordinate.get("y").toString());
            entity.setLatGaode(gaodeCoordinate.get("x").toString());
            entity.setLngGaode(gaodeCoordinate.get("y").toString());
        }
    }
}
