package com.ozs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.utils.bean.BeanValidators;
import com.ozs.entity.BaseRailwayManagement;
import com.ozs.mapper.BaseRailwayManagementMapper;
import com.ozs.service.BaseRailwayManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 线路管理表 服务实现类
 * </p>
 *
 * @author ozs
 * @since 2023-02-17
 */
@Service
public class BaseRailwayManagementServiceImpl extends ServiceImpl<BaseRailwayManagementMapper, BaseRailwayManagement> implements BaseRailwayManagementService {
    public static final String PATTERN = "^(\\d+.\\d{1,3}|\\d+)$";
    @Resource
    BaseRailwayManagementMapper baseRailwayManagementMapper;
    @Autowired
    protected Validator validator;

    /**
     * 导出线路管理表信息
     *
     * @param accountManageList 线路管理表信息列表
     * @param updateSupport     是否更新支持，如果已存在，则进行更新数据
     * @return
     */
    @Override
    public String importBaseLineManagement(List<BaseRailwayManagement> accountManageList, boolean updateSupport, String userId) {
        if (com.ozs.common.utils.StringUtils.isNull(accountManageList) || accountManageList.size() == 0) {
            throw new ServiceException("导入线路管理信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseRailwayManagement railwayManagement : accountManageList) {
            try {
                LambdaQueryWrapper<BaseRailwayManagement> wrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
                if (!ObjectUtils.isEmpty(railwayManagement.getRailwayName())) {
                    wrapper.eq(BaseRailwayManagement::getRailwayName, railwayManagement.getRailwayName());
                }
                BaseRailwayManagement railwayManagement1 = baseRailwayManagementMapper.selectOne(wrapper);
                if (ObjectUtils.isEmpty(railwayManagement1)) {
                    // 判断相机编码是否存在
                    LambdaQueryWrapper<BaseRailwayManagement> lw = new LambdaQueryWrapper<BaseRailwayManagement>();
                    if (!ObjectUtils.isEmpty(railwayManagement.getRailwayCode())) {
                        lw.eq(BaseRailwayManagement::getRailwayCode, railwayManagement.getRailwayCode());
                    }
                    BaseRailwayManagement baseLineManagement = baseRailwayManagementMapper.selectOne(lw);
                    if (ObjectUtils.isEmpty(baseLineManagement)) {
                        if (!railwayManagement.getInitialMileageBD().toString().matches(PATTERN) || !railwayManagement.getEndMileageBD().toString().matches(PATTERN)) {
                            failureNum++;
                            failureMsg.append(failureNum + "、线路编码: " + railwayManagement.getRailwayCode() + "的数据,里程位置填写格式不正确,请填写数字或小数");
                        }else {
                            railwayManagement.setInitialMileage(railwayManagement.getInitialMileageBD().multiply(new BigDecimal("1000")).intValue());
                            railwayManagement.setEndMileage(railwayManagement.getEndMileageBD().multiply(new BigDecimal("1000")).intValue());
                            BeanValidators.validateWithException(validator, railwayManagement);
                            railwayManagement.setUpdateBy(userId);
                            railwayManagement.setCreateBy(userId);
                            baseRailwayManagementMapper.insert(railwayManagement);
                            successNum++;
                            successMsg.append(successNum + "、线路编码 " + railwayManagement.getRailwayCode() + " 导入成功");
                        }
                    } else if (updateSupport) {
                        BeanValidators.validateWithException(validator, railwayManagement);
                        railwayManagement.setUpdateBy(userId);
                        baseRailwayManagementMapper.update(railwayManagement, lw);
                        successNum++;
                        successMsg.append(successNum + "、线路编码 " + railwayManagement.getRailwayCode() + " 更新成功");
                    } else {
                        failureNum++;
                        failureMsg.append(failureNum + "、线路编码 " + railwayManagement.getRailwayCode() + " 已存在");
                    }
                } else {
                    failureNum++;
                    failureMsg.append( failureNum + "、线路名称 " + railwayManagement.getRailwayName() + " 已存在");
                }
            } catch (Exception e) {
                String msg=null;
                failureNum++;
                if (ObjectUtils.isEmpty(railwayManagement)) {
                    msg = "导入的文档格式不正确";
                }else {
                    msg = failureNum + "、线路编码 " + railwayManagement.getRailwayCode() + " 导入失败：";
                }
                failureMsg.append(msg);
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条。");
        }
        return successMsg.toString();
    }

    @Override
    public String getCameraNameByCameraCode(String cameraCode) {
        return baseRailwayManagementMapper.getCameraNameByCameraCode(cameraCode);
    }
}
