package com.ozs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ozs.common.exception.ServiceException;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.bean.BeanUtils;
import com.ozs.common.utils.bean.BeanValidators;
import com.ozs.entity.BaseCameraManagement;
import com.ozs.entity.BaseDeviceDynamicManagement;
import com.ozs.entity.BaseRailwayManagement;
import com.ozs.entity.BaseUser;
import com.ozs.entity.vo.BaseCameraManagementHomeVo;
import com.ozs.entity.vo.BaseCameraManagementVo;
import com.ozs.entity.vo.BaseCameraManagementVos;
import com.ozs.mapper.*;
import com.ozs.service.BaseCameraManagementService;
import com.ozs.service.BaseRailwayManagementService;
import com.ozs.service.BaseUserService;
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.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 相机台账管理表 服务实现类
 * </p>
 *
 * @author ozs
 * @since 2023-02-17
 */
@Service
public class BaseCameraManagementServiceImpl extends ServiceImpl<BaseCameraManagementMapper, BaseCameraManagement> implements BaseCameraManagementService {
    public static final String PATTERN = "^[0-9]*$";
    @Autowired
    protected Validator validator;
    @Autowired
    BaseDeviceDynamicManagementMapper baseDeviceDynamicManagementMapper;
    @Resource
    private BaseCameraManagementMapper baseCameraManagementMapper;
    @Resource
    private BaseUserService baseUserService;
    @Resource
    private BaseUserMapper baseUserMapper;
    @Resource
    private MsgAlarmMapper msgAlarmMapper;
    @Autowired
    private BaseDeptMapper baseDeptMapper;
    @Autowired
    private BaseRailwayManagementService baseRailwayManagementService;

    /**
     * 相机台账管理表导入
     *
     * @param accountManageList 相机台账列表
     * @param updateSupport     是否更新支持，如果已存在，则进行更新数据
     * @return
     */
    @Override
    public String importBaseAccountManagement(List<BaseCameraManagementVos> accountManageList, boolean updateSupport, String userId) {
        if (StringUtils.isNull(accountManageList) || accountManageList.size() == 0) {
            throw new ServiceException("导入相机台账列表信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BaseCameraManagementVos cameraManagementVos : accountManageList) {
            try {
                BaseCameraManagement accountManagement = new BaseCameraManagement();
                BeanUtils.copyProperties(cameraManagementVos, accountManagement);
                // 判断相机编码是否存在
                LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
                if (!ObjectUtils.isEmpty(accountManagement.getCameraCode())) {
                    lw.eq(BaseCameraManagement::getCameraCode, accountManagement.getCameraCode());
                }
                BaseCameraManagement baseAccountManagement = baseCameraManagementMapper.selectOne(lw);
                if (ObjectUtils.isEmpty(baseAccountManagement)) {
                    BeanValidators.validateWithException(validator, accountManagement);
                    accountManagement.setUpdateBy(userId);
                    accountManagement.setCreateBy(userId);
                    Long deptId = baseDeptMapper.selectDeptByDeptName(accountManagement.getDeptName());
                    log.debug(accountManagement.getDeptName() + "主键id:" + deptId);
                    if (!ObjectUtils.isEmpty(deptId)) {
                        accountManagement.setDeptId(deptId);
                        LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
                        if (!ObjectUtils.isEmpty(accountManagement.getRailwayName())) {
                            queryWrapper.eq(BaseRailwayManagement::getRailwayName, accountManagement.getRailwayName());
                        }
                        BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
                        if (!ObjectUtils.isEmpty(baseRailwayManagement)) {
                            if (!accountManagement.getBeginMile().toString().matches(PATTERN) || !accountManagement.getInstallMile().toString().matches(PATTERN) || !accountManagement.getEndMile().toString().matches(PATTERN)) {
                                failureNum++;
                                failureMsg.append(failureNum + "、相机编码为: " + accountManagement.getCameraCode() + "的数据,里程位置填写格式不正确,请填写数字");
                            } else {
                                accountManagement.setRailwayCode(baseRailwayManagement.getRailwayCode());
                                accountManagement.setInstallMile(accountManagement.getInstallMile() * 1000);
                                accountManagement.setEndMile(accountManagement.getEndMile() * 1000);
                                accountManagement.setBeginMile(accountManagement.getBeginMile() * 1000);
                                if (accountManagement.getBeginMile() < accountManagement.getEndMile()) {
                                    baseCameraManagementMapper.insert(accountManagement);
                                    BaseDeviceDynamicManagement baseDeviceDynamicManagement = new BaseDeviceDynamicManagement();
                                    baseDeviceDynamicManagement.setCameraCode(accountManagement.getCameraCode());
                                    baseDeviceDynamicManagement.setUpdateBy(userId);
                                    baseDeviceDynamicManagement.setCreateBy(userId);
                                    baseDeviceDynamicManagementMapper.insert(baseDeviceDynamicManagement);
                                    successNum++;
                                    successMsg.append(successNum + "、相机编码 " + accountManagement.getCameraCode() + " 导入成功");
                                } else {
                                    failureNum++;
                                    failureMsg.append(failureNum + "、相机编码为: " + accountManagement.getCameraCode() + "的数据,监控范围开始里程位置不能大于监控范围结束里程位置");
                                }
                            }
                        } else {
                            failureNum++;
                            String msg = failureNum + "、相机所属线路名称 " + accountManagement.getRailwayName() + "不存在， 导入失败：";
                            failureMsg.append(msg);
                            log.error(msg);
                        }
                    } else {
                        failureNum++;
                        String msg = failureNum + "、相机所属工务段 " + accountManagement.getDeptName() + "不存在， 导入失败：";
                        failureMsg.append(msg);
                        log.error(msg);
                    }
                } else if (updateSupport) {
                    BeanValidators.validateWithException(validator, accountManagement);
                    accountManagement.setUpdateBy(userId);
                    Long deptId = baseDeptMapper.selectDeptByDeptName(accountManagement.getDeptName());
                    log.debug(accountManagement.getDeptName() + "主键id:" + deptId);
                    if (!ObjectUtils.isEmpty(deptId)) {
                        accountManagement.setDeptId(deptId);
                        baseCameraManagementMapper.update(accountManagement, lw);
                        LambdaQueryWrapper<BaseDeviceDynamicManagement> wrapper = new LambdaQueryWrapper<BaseDeviceDynamicManagement>();
                        if (!ObjectUtils.isEmpty(baseAccountManagement.getCameraCode())) {
                            wrapper.eq(BaseDeviceDynamicManagement::getCameraCode, baseAccountManagement.getCameraCode());
                        }
                        BaseDeviceDynamicManagement baseDeviceDynamicManagement = baseDeviceDynamicManagementMapper.selectOne(wrapper);
                        baseDeviceDynamicManagement.setCameraCode(accountManagement.getCameraCode());
                        baseDeviceDynamicManagement.setUpdateBy(userId);
                        baseDeviceDynamicManagementMapper.updateById(baseDeviceDynamicManagement);
                        successNum++;
                        successMsg.append(successNum + "、相机编码 " + accountManagement.getCameraCode() + " 更新成功");
                    } else {
                        failureNum++;
                        String msg = failureNum + "、相机所属工务段 " + accountManagement.getDeptName() + "不存在， 导入失败：";
                        failureMsg.append(msg);
                        log.error(msg);
                    }

                } else {
                    failureNum++;
                    failureMsg.append(failureNum + "、相机编码 " + accountManagement.getCameraCode() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、相机编码 " + cameraManagementVos.getCameraCode() + " 导入失败：";
                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();
    }

    /**
     * 获取相机列表+数据权限
     *
     * @return
     */
    @Override
    public List<BaseCameraManagementHomeVo> selectCameraAll(BaseCameraManagementVo baseCameraManagementVo) {
//        List<String> userIdList = getUserIds(userId);
//        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
//        if (!StringUtils.isEmpty(userIdList)) {
//            lw.in(BaseCameraManagement::getCreateBy, userIdList);
//        }
//        List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementMapper.selectList(lw);
        List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementMapper.selectCameraManagementList(baseCameraManagementVo);
        List<BaseCameraManagementHomeVo> allListVo = BeanUtils.entityListToVOList(baseCameraManagementList, BaseCameraManagementHomeVo.class);
        for (BaseCameraManagementHomeVo baseCameraManagementHomeVo : allListVo) {
            Integer isRelease = msgAlarmMapper.selectCameraCode(baseCameraManagementHomeVo.getCameraCode());
            baseCameraManagementHomeVo.setIsRelease(isRelease != null ? isRelease : 1);
        }
        return allListVo;
    }

    /**
     * 根据当前登陆用户ID 查询当前用户数据权限
     *
     * @param userId
     * @return
     */
   /* public List<String> getUserIds(String userId) {
        BaseUser baseUser = baseUserService.getUser(userId);
        if (StringUtils.isNull(baseUser) || StringUtils.isNull(baseUser.getDataPermission())
                || StringUtils.isNull(baseUser.getDeptId())) {
            return null;
        }
        // 数据权限 1：本人；2：本部门；3：本部门及下级部门；4：本人及本级部门；5：本人及本部门及下级部门；6：全部
        Integer dataPermission = baseUser.getDataPermission();
        Long deptId = baseUser.getDeptId();
        Set<String> set = new HashSet<>();
        if (1 == dataPermission) {
            set = baseUserMapper.getUserIdList(userId);
        } else if (2 == dataPermission) {
            set = baseUserMapper.getUserIdByDeptId(deptId);
        } else if (3 == dataPermission) {
            // 获取部门数据
            List<Long> deptList = baseUserMapper.getDeptId(deptId);
            // 获取用户列表
            set = baseUserMapper.getUserIdByDeptIds(deptList);
        } else if (4 == dataPermission) {
            set = baseUserMapper.getUserIdByDeptIdAndUserId(userId, deptId);
        } else if (5 == dataPermission) {
            // 获取本人
            Set<String> setUser = baseUserMapper.getUserIdListBy5(userId);
            // 获取部门数据
            List<Long> deptList5 = baseUserMapper.getDeptId(deptId);
            // 获取用户列表
            Set<String> setUsers = baseUserMapper.getUserIdByDeptIdsBy5(deptList5);
            set.addAll(setUser);
            set.addAll(setUsers);
        } else if (6 == dataPermission) {
            set = baseUserMapper.getUserIdList6();
        }
        List<String> list = new ArrayList<>(set);
        return list;
    }*/


    /**
     * 根据当前登陆用户ID 查询当前用户数据权限
     *
     * @param userId
     * @return
     */
    public List<String> getUserIdList(String userId) {
        BaseUser baseUser = baseUserService.getUser(userId);
        if (StringUtils.isNull(baseUser) || StringUtils.isNull(baseUser.getDataPermission())
                || StringUtils.isNull(baseUser.getDeptId())) {
            return null;
        }
        // 数据权限 1：本人；2：本部门；3：本部门及下级部门；4：本人及本级部门；5：本人及本部门及下级部门；6：全部
        Integer dataPermission = baseUser.getDataPermission();
        Long deptId = baseUser.getDeptId();
        Set<String> set = new HashSet<>();
        if (1 == dataPermission) {
            set = baseUserMapper.getUserIdList(userId);
        } else if (2 == dataPermission) {
            set = baseUserMapper.getUserIdByDeptId(deptId);
        } else if (3 == dataPermission) {
            // 获取部门数据
            List<Long> deptList = baseUserMapper.getDeptId(deptId);
            // 获取用户列表
            set = baseUserMapper.getUserIdByDeptIds(deptList);
        } else if (4 == dataPermission) {
            set = baseUserMapper.getUserIdByDeptIdAndUserId(userId, deptId);
        } else if (5 == dataPermission) {
            // 获取本人
            Set<String> setUser = baseUserMapper.getUserIdListBy5(userId);
            // 获取部门数据
            List<Long> deptList5 = baseUserMapper.getDeptId(deptId);
            // 获取用户列表
            Set<String> setUsers = baseUserMapper.getUserIdByDeptIdsBy5(deptList5);
            set.addAll(setUser);
            set.addAll(setUsers);
        } else if (6 == dataPermission) {
            set = baseUserMapper.getUserIdsList();
        }
        List<String> list = new ArrayList<>(set);
        return list;
    }

    @Override
    public IPage<BaseCameraManagement> queryPage(BaseCameraManagementVo baseCameraManagementVo) {
        int pageNum = Integer.parseInt(baseCameraManagementVo.getPageNum().toString());
        int pageSize = Integer.parseInt(baseCameraManagementVo.getPageSize().toString());
        com.github.pagehelper.Page<BaseCameraManagement> page = PageHelper.startPage(pageNum, pageSize)
                .doSelectPage(() -> baseCameraManagementMapper.selectCameraManagementList(baseCameraManagementVo));
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BaseCameraManagement> pageR =
                new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
        pageR.setRecords(page.getResult());
        pageR.setTotal(page.getTotal());
        return pageR;
    }

    @Override
    public List<BaseCameraManagement> baseCameraManagementList(BaseCameraManagementVo baseCameraManagementVo) {
        return baseCameraManagementMapper.selectCameraManagementList(baseCameraManagementVo);
    }
}
