package com.usky.fire.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
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.PatrolInspectionPersonnel;
import com.usky.fire.domain.PatrolInspectionPlanSchedule;
import com.usky.fire.mapper.PatrolInspectionPersonnelMapper;
import com.usky.fire.service.PatrolInspectionAreaService;
import com.usky.fire.service.PatrolInspectionPersonnelService;
import com.usky.fire.service.PatrolInspectionPlanScheduleService;
import com.usky.fire.service.util.OnlineMethod;
import com.usky.fire.service.vo.DataCountVo;
import com.usky.fire.service.vo.PatrolInspectionAreaVo;
import com.usky.fire.service.vo.PatrolInspectionPersonnelVo;
import com.usky.system.RemoteUserService;
import com.usky.system.domain.SysUser;
import com.usky.system.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 巡检人员表 服务实现类
 * </p>
 *
 * @author JCB
 * @since 2022-07-26
 */
@Service
public class PatrolInspectionPersonnelServiceImpl extends AbstractCrudService<PatrolInspectionPersonnelMapper, PatrolInspectionPersonnel> implements PatrolInspectionPersonnelService {

    @Autowired
    private PatrolInspectionPlanScheduleService planScheduleService;

    @Autowired
    private PatrolInspectionAreaService patrolInspectionAreaService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public void addPatrolInspectionPersonnel(PatrolInspectionPersonnel patrolInspectionPersonnel) {
        LambdaQueryWrapper<PatrolInspectionPersonnel> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionPersonnel::getTenantId, SecurityUtils.getTenantId())
//                .eq(PatrolInspectionPersonnel::getAreaId, patrolInspectionPersonnel.getAreaId())
                .eq(PatrolInspectionPersonnel::getUserId, patrolInspectionPersonnel.getUserId());
        int count = this.count(queryWrapper);
        if (count>0){
            throw new BusinessException("巡检人员只能绑定一个巡检区域");
        }
        patrolInspectionPersonnel.setCompanyId(0);
        patrolInspectionPersonnel.setTenantId(SecurityUtils.getTenantId());
        patrolInspectionPersonnel.setCreator(SecurityUtils.getUsername());
        patrolInspectionPersonnel.setEnable(1);
        patrolInspectionPersonnel.setCreateTime(LocalDateTime.now());
        this.save(patrolInspectionPersonnel);
    }

    @Override
    public void updatePatrolInspectionPersonnel(PatrolInspectionPersonnel patrolInspectionPersonnel) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionPersonnel> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionPersonnel::getEnable, 1)
                .eq(PatrolInspectionPersonnel::getUserId, patrolInspectionPersonnel.getUserId())
//                .eq(PatrolInspectionPersonnel::getAreaId, patrolInspectionPersonnel.getAreaId())
                .ne(PatrolInspectionPersonnel::getId,patrolInspectionPersonnel.getId())
                .eq(PatrolInspectionPersonnel::getTenantId, SecurityUtils.getTenantId());
        if ("00".equals(userType)) {
            queryWrapper.eq(PatrolInspectionPersonnel::getCreator, SecurityUtils.getUsername());
        }
        List<PatrolInspectionPersonnel> list = this.list(queryWrapper);
        if (list.size() > 0) {
            throw new BusinessException("巡检人员录入重复不可修改");
        }
        this.updateById(patrolInspectionPersonnel);
    }

    @Override
    public void delPatrolInspectionPersonnel(Integer id) {
        LambdaQueryWrapper<PatrolInspectionPlanSchedule> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionPlanSchedule::getPersonnelId, id);
        List<PatrolInspectionPlanSchedule> listOne = planScheduleService.list(queryWrapper);
        if (listOne.size() > 0) {
            throw new BusinessException("人员使用中不可删除");
        }
        this.removeById(id);
    }

    @Override
    public CommonPage<PatrolInspectionPersonnelVo> patrolInspectionPersonnelList(Integer areaId, Integer pageNum, Integer pageSize, Integer id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionPersonnel> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionPersonnel::getEnable, 1)
                .eq(PatrolInspectionPersonnel::getTenantId, SecurityUtils.getTenantId());
        if ("00".equals(userType)) {
            queryWrapper.eq(PatrolInspectionPersonnel::getCreator, SecurityUtils.getUsername());
        }
        if (id != 0 && id != null) {
            queryWrapper.eq(PatrolInspectionPersonnel::getId, id);
        }
        if (areaId != 0 && areaId != null) {
            queryWrapper.eq(PatrolInspectionPersonnel::getAreaId, areaId);
        }

        Integer total = this.count(queryWrapper);
        queryWrapper.orderByDesc(PatrolInspectionPersonnel::getId);
        if (pageNum != null && pageNum != 0 && pageSize != null && pageSize != 0) {
            Integer startFate = OnlineMethod.getStartFate(pageNum, pageSize);
            queryWrapper.last("limit " + startFate + "," + pageSize);
        }
        List<PatrolInspectionPersonnel> list = this.list(queryWrapper);
        List<PatrolInspectionPersonnelVo> list1 = new ArrayList<>();
        if (list.size() > 0) {
            ApiResult<List<SysUser>> userApi = remoteUserService.userList();
            List<SysUser> userList = userApi.getData();
            for (int i = 0; i < list.size(); i++) {
                PatrolInspectionPersonnelVo patrolInspectionPersonnelVo = new PatrolInspectionPersonnelVo();
                patrolInspectionPersonnelVo.setCreator(list.get(i).getCreator());
                patrolInspectionPersonnelVo.setCompanyId(list.get(i).getCompanyId());
                patrolInspectionPersonnelVo.setEnable(list.get(i).getEnable());
                patrolInspectionPersonnelVo.setCreateTime(list.get(i).getCreateTime());
                patrolInspectionPersonnelVo.setId(list.get(i).getId());
                patrolInspectionPersonnelVo.setTenantId(list.get(i).getTenantId());
                patrolInspectionPersonnelVo.setAreaId(list.get(i).getAreaId());
                patrolInspectionPersonnelVo.setUserId(list.get(i).getUserId());
                patrolInspectionPersonnelVo.setDocumentInfo(list.get(i).getDocumentInfo());
                patrolInspectionPersonnelVo.setNation(list.get(i).getNation());
                patrolInspectionPersonnelVo.setEduLevel(list.get(i).getEduLevel());
                patrolInspectionPersonnelVo.setRegisterResidence(list.get(i).getRegisterResidence());
                patrolInspectionPersonnelVo.setResidence(list.get(i).getResidence());
                patrolInspectionPersonnelVo.setPhysicsCard(list.get(i).getPhysicsCard());
                patrolInspectionPersonnelVo.setIdCard(list.get(i).getIdCard());
                patrolInspectionPersonnelVo.setFullName(list.get(i).getFullName());
                patrolInspectionPersonnelVo.setWhetherEmploy(list.get(i).getWhetherEmploy());
                patrolInspectionPersonnelVo.setBirthDate(list.get(i).getBirthDate());
                patrolInspectionPersonnelVo.setSex(list.get(i).getSex());
                patrolInspectionPersonnelVo.setPhoneNumber(list.get(i).getPhoneNumber());
                patrolInspectionPersonnelVo.setMainPosition(list.get(i).getMainPosition());
                patrolInspectionPersonnelVo.setServiceContent(list.get(i).getServiceContent());
                patrolInspectionPersonnelVo.setDispatchCompany(list.get(i).getDispatchCompany());
                patrolInspectionPersonnelVo.setSecurityCompany(list.get(i).getSecurityCompany());
                for (int j = 0; j < userList.size(); j++) {
                    if (list.get(i).getUserId().longValue() == userList.get(j).getUserId()) {
                        patrolInspectionPersonnelVo.setName(userList.get(j).getNickName());
                    }
                }
                list1.add(patrolInspectionPersonnelVo);
            }
        }
//        List<PatrolInspectionPersonnelVo> list2 = list1.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        return new CommonPage<>(list1, total, pageSize, pageNum);
    }


    @Override
    @DataScope
    public List<PatrolInspectionAreaVo> personnelLeftList() {
        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());
        }
        List<PatrolInspectionArea> patrolInspectionAreaList = patrolInspectionAreaService.list(queryWrapper);

        LambdaQueryWrapper<PatrolInspectionPersonnel> queryWrapperOne = Wrappers.lambdaQuery();
        queryWrapperOne.eq(PatrolInspectionPersonnel::getEnable, 1)
                .eq(PatrolInspectionPersonnel::getTenantId, SecurityUtils.getTenantId());
        if ("00".equals(userType)) {
            queryWrapperOne.eq(PatrolInspectionPersonnel::getCreator, SecurityUtils.getUsername());
        }
        List<PatrolInspectionPersonnel> list = this.list(queryWrapperOne);
        Map<Integer, List<PatrolInspectionPersonnel>> grouypByAreaId = list.stream().collect(
                Collectors.groupingBy(o -> o.getAreaId())
        );
        List<DataCountVo> dataCountVoList = new ArrayList<>();
        grouypByAreaId.forEach((k, v) -> {
            DataCountVo dataCountVo = new DataCountVo();
            dataCountVo.setListCount(v.size());
            dataCountVo.setId(k);
            dataCountVoList.add(dataCountVo);
        });
        List<PatrolInspectionAreaVo> patrolInspectionAreaVoList = new ArrayList<>();
        if (patrolInspectionAreaList.size() > 0) {
            for (int i = 0; i < patrolInspectionAreaList.size(); i++) {
                PatrolInspectionAreaVo patrolInspectionAreaVo = new PatrolInspectionAreaVo();
                patrolInspectionAreaVo.setId(patrolInspectionAreaList.get(i).getId());
                patrolInspectionAreaVo.setAreaName(patrolInspectionAreaList.get(i).getAreaName());
                patrolInspectionAreaVo.setAreaFid(patrolInspectionAreaList.get(i).getAreaFid());
                patrolInspectionAreaVo.setDeptId(patrolInspectionAreaList.get(i).getDeptId());
                patrolInspectionAreaVo.setTenantId(patrolInspectionAreaList.get(i).getTenantId());
                patrolInspectionAreaVo.setCreator(patrolInspectionAreaList.get(i).getCreator());
                patrolInspectionAreaVo.setCreateTime(patrolInspectionAreaList.get(i).getCreateTime());
                patrolInspectionAreaVo.setEnable(patrolInspectionAreaList.get(i).getEnable());
                patrolInspectionAreaVo.setPersonnelCount(0);
                for (int j = 0; j < dataCountVoList.size(); j++) {
                    if (patrolInspectionAreaList.get(i).getId() == dataCountVoList.get(j).getId()) {
                        patrolInspectionAreaVo.setPersonnelCount(dataCountVoList.get(j).getListCount());
                    }
                }
                patrolInspectionAreaVoList.add(patrolInspectionAreaVo);
            }
        }
        List<PatrolInspectionAreaVo> patrolInspectionAreaVoListOne = new ArrayList<>();
        if (patrolInspectionAreaVoList.size() > 0) {
            patrolInspectionAreaVoListOne = OnlineMethod.getChildPerms(patrolInspectionAreaVoList, 0);
        }
        return patrolInspectionAreaVoListOne;
    }

    /**
     * 签到状态更新
     */
    public void updateSignStatus(Integer status) {
        LambdaUpdateWrapper<PatrolInspectionPersonnel> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(PatrolInspectionPersonnel::getUserId, SecurityUtils.getUserId())
                .set(PatrolInspectionPersonnel::getOperateType, status);

        baseMapper.update(null, updateWrapper);
    }

    /**
     * 签到状态查询
     */
    public PatrolInspectionPersonnel getStatus(){
        LambdaQueryWrapper<PatrolInspectionPersonnel> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PatrolInspectionPersonnel::getUserId,SecurityUtils.getUserId())
                .last("LIMIT 1");
        return baseMapper.selectOne(wrapper);
    }


    @Override
    public List<PatrolInspectionPersonnelVo> patrolInspectionPersonnelSelect(Integer areaId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userType = null;
        if (loginUser != null && !"".equals(loginUser)) {
            userType = loginUser.getUserType();
        }
        LambdaQueryWrapper<PatrolInspectionPersonnel> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PatrolInspectionPersonnel::getEnable, 1)
                .eq(PatrolInspectionPersonnel::getTenantId, SecurityUtils.getTenantId());
        if ("00".equals(userType)) {
            queryWrapper.eq(PatrolInspectionPersonnel::getCreator, SecurityUtils.getUsername());
        }
        if (areaId != 0 && areaId != null) {
            queryWrapper.eq(PatrolInspectionPersonnel::getAreaId, areaId);
        }
        List<PatrolInspectionPersonnel> list = this.list(queryWrapper);
        List<PatrolInspectionPersonnelVo> list1 = new ArrayList<>();
        if (list.size() > 0) {
            ApiResult<List<SysUser>> userApi = remoteUserService.userList();
            List<SysUser> userList = userApi.getData();
            for (int i = 0; i < list.size(); i++) {
                PatrolInspectionPersonnelVo patrolInspectionPersonnelVo = new PatrolInspectionPersonnelVo();
                patrolInspectionPersonnelVo.setCreator(list.get(i).getCreator());
                patrolInspectionPersonnelVo.setCompanyId(list.get(i).getCompanyId());
                patrolInspectionPersonnelVo.setEnable(list.get(i).getEnable());
                patrolInspectionPersonnelVo.setCreateTime(list.get(i).getCreateTime());
                patrolInspectionPersonnelVo.setId(list.get(i).getId());
                patrolInspectionPersonnelVo.setTenantId(list.get(i).getTenantId());
                patrolInspectionPersonnelVo.setAreaId(list.get(i).getAreaId());
                patrolInspectionPersonnelVo.setUserId(list.get(i).getUserId());
                for (int j = 0; j < userList.size(); j++) {
                    if (list.get(i).getUserId().longValue() == userList.get(j).getUserId()) {
                        patrolInspectionPersonnelVo.setName(userList.get(j).getNickName());
                    }
                }
                list1.add(patrolInspectionPersonnelVo);
            }
        }
        return list1;
    }

}