package com.usky.fire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.datascope.context.DataScopeContextHolder;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.fire.domain.PatrolInspectionArea;
import com.usky.fire.domain.PatrolInspectionSite;
import com.usky.fire.mapper.PatrolInspectionAreaMapper;
import com.usky.fire.mapper.PatrolInspectionSiteMapper;
import com.usky.fire.service.BaseCompanyService;
import com.usky.fire.service.PatrolInspectionAreaService;
import com.usky.fire.service.vo.PatrolInspectionAreaVo;
import com.usky.system.RemoteDeptService;
import com.usky.system.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author JCB
 * @since 2022-07-12
 */
@Service
public class PatrolInspectionAreaServiceImpl extends AbstractCrudService<PatrolInspectionAreaMapper, PatrolInspectionArea> implements PatrolInspectionAreaService {

    @Autowired
    private BaseCompanyService baseCompanyService;

    @Autowired
    private RemoteDeptService remoteDeptService;

    @Autowired
    private PatrolInspectionSiteMapper patrolInspectionSiteMapper;

    /**
     * 巡查自检-巡检区域-新增
     *
     * @param patrolInspectionAreaVo
     */
    @Override
    @Transactional
    public void addPatrolInspectionArea(PatrolInspectionAreaVo patrolInspectionAreaVo) {
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionArea::getEnable, 1)
                .eq(PatrolInspectionArea::getDeptId, patrolInspectionAreaVo.getDeptId())
                .eq(PatrolInspectionArea::getAreaName, patrolInspectionAreaVo.getAreaName());
        List<PatrolInspectionArea> list = this.list(queryWrapper);
        if (list.size() > 0) {
            throw new BusinessException("区域不可以重复");
        }
        PatrolInspectionArea patrolInspectionArea = new PatrolInspectionArea();
        patrolInspectionArea.setAreaName(patrolInspectionAreaVo.getAreaName());
        patrolInspectionArea.setAreaFid(0);
        patrolInspectionArea.setDeptId(patrolInspectionAreaVo.getDeptId());
        patrolInspectionArea.setCreator(SecurityUtils.getUsername());
        patrolInspectionArea.setCreateTime(LocalDateTime.now());
        patrolInspectionArea.setEnable(1);
        patrolInspectionArea.setTenantId(SecurityUtils.getTenantId());
        this.save(patrolInspectionArea);
        Integer areaFid = patrolInspectionArea.getId();
        for (int i = 0; i < patrolInspectionAreaVo.getAreaNameArray().length; i++) {
            LambdaQueryWrapper<PatrolInspectionArea> queryWrapperOne = Wrappers.lambdaQuery();
            queryWrapperOne.eq(PatrolInspectionArea::getEnable, 1)
                    .eq(PatrolInspectionArea::getAreaName, patrolInspectionAreaVo.getAreaNameArray()[i])
                    .eq(PatrolInspectionArea::getAreaFid, areaFid);
            List<PatrolInspectionArea> list1 = this.list(queryWrapperOne);
            if (list1.size() > 0) {
                throw new BusinessException(patrolInspectionAreaVo.getAreaNameArray()[i] + "重复，子区域不可以重复");
            }
            PatrolInspectionArea patrolInspectionAreaZ = new PatrolInspectionArea();
            patrolInspectionAreaZ.setAreaName(patrolInspectionAreaVo.getAreaNameArray()[i]);
            patrolInspectionAreaZ.setAreaFid(areaFid);
            patrolInspectionAreaZ.setDeptId(patrolInspectionAreaVo.getDeptId());
            patrolInspectionAreaZ.setCreator(SecurityUtils.getUsername());
            patrolInspectionAreaZ.setCreateTime(LocalDateTime.now());
            patrolInspectionAreaZ.setEnable(1);
            patrolInspectionAreaZ.setTenantId(SecurityUtils.getTenantId());
            this.save(patrolInspectionAreaZ);
        }
    }

    @Override
    public void addPatrolInspectionAreaSon(PatrolInspectionArea patrolInspectionArea) {
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionArea::getEnable, 1)
                .eq(PatrolInspectionArea::getId, patrolInspectionArea.getAreaFid());
        List<PatrolInspectionArea> list = this.list(queryWrapper);
        if (list.size() <= 0) {
            throw new BusinessException("父级ID不存在");
        }
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapperOne = Wrappers.lambdaQuery();
        queryWrapperOne.eq(PatrolInspectionArea::getEnable, 1)
                .eq(PatrolInspectionArea::getAreaFid, patrolInspectionArea.getAreaFid())
                .eq(PatrolInspectionArea::getAreaName, patrolInspectionArea.getAreaName());
        List<PatrolInspectionArea> list2 = this.list(queryWrapperOne);
        if (list2.size() > 0) {
            throw new BusinessException("区域名称不可重复");
        }
        patrolInspectionArea.setDeptId(list.get(0).getDeptId());
        patrolInspectionArea.setCreator(SecurityUtils.getUsername());
        patrolInspectionArea.setCreateTime(LocalDateTime.now());
        patrolInspectionArea.setEnable(1);
        patrolInspectionArea.setTenantId(SecurityUtils.getTenantId());
        this.save(patrolInspectionArea);
    }

    /**
     * 巡查自检-巡检区域-编辑
     *
     * @param patrolInspectionArea
     */
    @Override
    @Transactional
    public void updatePatrolInspectionArea(PatrolInspectionArea patrolInspectionArea) {
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapperOne = Wrappers.lambdaQuery();
        queryWrapperOne.select(PatrolInspectionArea::getAreaFid)
                .eq(PatrolInspectionArea::getId, patrolInspectionArea.getId())
                .eq(PatrolInspectionArea::getEnable, 1);
        PatrolInspectionArea patrolInspectionAreaMap = this.getOne(queryWrapperOne);
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapperTwo = Wrappers.lambdaQuery();
        queryWrapperTwo.select(PatrolInspectionArea::getAreaFid)
                .eq(PatrolInspectionArea::getAreaFid, patrolInspectionAreaMap.getAreaFid())
                .eq(PatrolInspectionArea::getAreaName, patrolInspectionArea.getAreaName())
                .eq(PatrolInspectionArea::getEnable, 1)
                .ne(PatrolInspectionArea::getId,patrolInspectionArea.getId());
        List<PatrolInspectionArea> list1 = this.list(queryWrapperTwo);
        if (list1.size() > 0) {
            throw new BusinessException(patrolInspectionArea.getAreaName() + "重复，区域不可以重复");
        }
        this.updateById(patrolInspectionArea);
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionArea::getAreaFid, patrolInspectionArea.getId())
                .eq(PatrolInspectionArea::getEnable, 1);
        List<PatrolInspectionArea> list = this.list(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            PatrolInspectionArea patrolInspectionAreaSon = new PatrolInspectionArea();
            patrolInspectionAreaSon.setId(list.get(i).getId());
            patrolInspectionAreaSon.setDeptId(patrolInspectionArea.getDeptId());
            this.updateById(patrolInspectionAreaSon);
        }
    }

    /**
     * 巡查自检-巡检区域-删除
     *
     * @param id 区域ID
     */
    @Override
    @Transactional
    public void delPatrolInspectionArea(Integer id) {
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionArea::getEnable, 1).eq(PatrolInspectionArea::getAreaFid, id);
        List<PatrolInspectionArea> patrolInspectionArealist = this.list(queryWrapper);
        List<Integer> areaIdList = new ArrayList<>();
        int siteNum = 0;
        if (null != patrolInspectionArealist && !patrolInspectionArealist.isEmpty()) {
            for (int j = 0; j < patrolInspectionArealist.size(); j++) {
                areaIdList.add(patrolInspectionArealist.get(j).getId());
            }
            areaIdList.add(id);
            siteNum = patrolInspectionSiteMapper.selectSiteCount(areaIdList);
        }
        if (siteNum>0){
            throw new BusinessException("区域下有绑定的点位，请解绑后再删除！");
        }else {
            for (int i = 0; i < patrolInspectionArealist.size(); i++) {
                PatrolInspectionArea patrolInspectionAreaz = new PatrolInspectionArea();
                patrolInspectionAreaz.setId(patrolInspectionArealist.get(i).getId());
                patrolInspectionAreaz.setEnable(0);
                this.updateById(patrolInspectionAreaz);
            }
            PatrolInspectionArea patrolInspectionArea = new PatrolInspectionArea();
            patrolInspectionArea.setId(id);
            patrolInspectionArea.setEnable(0);
            this.updateById(patrolInspectionArea);
        }
    }

    /**
     * 巡查自检-巡检区域-列表查詢
     *
     * @param id       区域ID
     * @param areaName 区域名称
     * @return
     */
    @Override
    @DataScope
    public List<PatrolInspectionArea> patrolInspectionAreaList(Integer id, String areaName) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionArea::getEnable, 1)
                .eq(PatrolInspectionArea::getTenantId, SecurityUtils.getTenantId())
                .apply(Objects.nonNull(DataScopeContextHolder.getDataScopeSql()),DataScopeContextHolder.getDataScopeSql());
        if ("00".equals(userType)) {
            queryWrapper.eq(PatrolInspectionArea::getCreator, SecurityUtils.getUsername());
        }
        if (id != null && id != 0) {
            queryWrapper.eq(PatrolInspectionArea::getId, id);
        }
        if (!"".equals(areaName) && areaName != null) {
            queryWrapper.like(PatrolInspectionArea::getAreaName, areaName);
        }
        queryWrapper.orderByDesc(PatrolInspectionArea::getId);
        List<PatrolInspectionArea> list = this.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Map<String, Object>> deptList = remoteDeptService.getDeptList(SecurityUtils.getTenantId());
            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < deptList.size(); j++) {
                    if (list.get(i).getDeptId().equals(deptList.get(j).get("dept_id"))) {
                        list.get(i).setCompanyName(deptList.get(j).get("dept_name").toString());
                    }
                }
            }
        }
        return list;
    }


    /**
     * 巡查自检-巡检区域-一级区域下拉框
     *
     * @return
     */
    @Override
    public List<PatrolInspectionArea> patrolInspectionAreaSelect(Integer areaFid) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionArea::getTenantId, SecurityUtils.getTenantId())
                .eq(PatrolInspectionArea::getEnable, 1)
                .eq(PatrolInspectionArea::getAreaFid, areaFid);
        if ("00".equals(userType)) {
            queryWrapper.eq(PatrolInspectionArea::getCreator, SecurityUtils.getUsername());
        }
        queryWrapper.orderByDesc(PatrolInspectionArea::getId);
        return this.list(queryWrapper);
    }

    @Override
    public List<Integer> areaIdList(Integer deptId){
        LambdaQueryWrapper<PatrolInspectionArea> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionArea::getDeptId, deptId)
                .eq(PatrolInspectionArea::getEnable, 1);
        List<PatrolInspectionArea> list = this.list(queryWrapper);
        List<Integer> areaIdList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            areaIdList.add(list.get(i).getId());
        }
        return areaIdList;
    }
}
