package com.zcxk.service;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zcxk.common.Reflections;
import com.zcxk.common.StringUtils;
import com.zcxk.dao.SceneMapper;
import com.zcxk.dto.AlarmDetailsDto;
import com.zcxk.entity.DeviceSceneEntity;
import com.zcxk.entity.SceneEntity;
import com.zcxk.entity.SceneImageEntity;
import com.zcxk.model.LoginUser;
import com.zcxk.util.OrgInfoUtil;
import com.zcxk.util.UserUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.google.common.collect.Lists.newArrayList;

/**
 * 场景信息Service接口
 *
 * @author: WYY
 * @date 2020-11-17 21:15
 */
@Service
public class SceneService extends ServiceImpl<SceneMapper, SceneEntity> {

    @Resource
    private SceneMapper sceneMapper;
    @Resource
    private SceneImageService sceneImageService;
    @Autowired
    private OrgInfoUtil orgInfoUtil;
    @Autowired
    private DeviceSceneService deviceSceneService;
    @Autowired
    private  AlarmDetailsService alarmDetailsService;

    /**
     * 自定义分页查询，含关联实体对像
     */
    public IPage<SceneEntity> findPage(IPage<SceneEntity> page, SceneEntity sceneEntity) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        sceneEntity.setTenantId(currentUser.getTenantId());
        sceneEntity.setProgramItems(currentUser.getProgramItemList());
        sceneEntity.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        sceneEntity.setPermissonType(currentUser.getPermissonType());
        //分页查询父级节点的信息
        Page<SceneEntity> sceneEntityPage = sceneMapper.findPage(page, sceneEntity);
        //查询子节点的信息
        List<SceneEntity> sceneEntities = newArrayList();
        for (SceneEntity item : sceneEntityPage.getRecords()) {
            sceneEntities.addAll(findByParentLike(item.getId()));
        }
        for (SceneEntity item : sceneEntities) {
            if (item.getCompanyOrgId() != null) {
                item.setCompanyOrgName(orgInfoUtil.getOrgName(item.getCompanyOrgId().intValue()));
            }
            if (item.getDeptOrgId() != null) {
                item.setDeptOrgName(orgInfoUtil.getOrgName(item.getDeptOrgId().intValue()));
            }
        }
        List<SceneEntity> sceneTree = getSceneTree(sceneEntities, Long.valueOf(0), 1);
        sceneEntityPage.setRecords(sceneTree);
        return sceneEntityPage;
    }

    public static List<SceneEntity> getSceneTree(List<SceneEntity> list, Long id, Integer leve) {
        List<SceneEntity> temList = newArrayList();
        if (list != null) {
            for (SceneEntity sceneEntity : list) {
                if (id.equals(sceneEntity.getParentSceneId())) {
                    List<SceneEntity> chidren = getSceneTree(list, sceneEntity.getId(), ++leve);
                    SceneEntity temMeanu = new SceneEntity();
                    BeanUtils.copyProperties(sceneEntity, temMeanu);
                    temMeanu.setChildren(chidren);
                    temList.add(temMeanu);
                    leve--;
                }
            }
        }
        if (temList.size() > 0) {
            return temList;
        } else {
            return null;
        }
    }

    /**
     * 查列表
     */
    public List<SceneEntity> findAllList(SceneEntity sceneEntity) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        sceneEntity.setTenantId(currentUser.getTenantId());
        sceneEntity.setProgramItems(currentUser.getProgramItemList());
        sceneEntity.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        sceneEntity.setPermissonType(currentUser.getPermissonType());
        List<SceneEntity> sceneEntities = sceneMapper.findList(sceneEntity);
        List<SceneEntity> sceneTree = getSceneTree(sceneEntities, Long.valueOf(0), 1);
        return sceneTree;
    }

    /**
     * 查列表
     */
    public List<SceneEntity> findList(SceneEntity sceneEntity) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        sceneEntity.setTenantId(currentUser.getTenantId());
        sceneEntity.setProgramItems(currentUser.getProgramItemList());
        sceneEntity.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        sceneEntity.setPermissonType(currentUser.getPermissonType());
        return sceneMapper.findList(sceneEntity);
    }

    /**
     * 批量删除
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delSceneByIds(Long[] ids) {
        return this.removeByIds(Arrays.asList(ids));

    }

    /**
     * 单个删除
     */
    public boolean delSceneById(Long id) {
        return this.removeById(id);
    }


    /**
     * 保存
     */
    public boolean addScene(SceneEntity scene) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        scene.setTenantId(currentUser.getTenantId());
        scene.setStatus(1);
        if (currentUser != null) {
            scene.setCreateBy(currentUser.getName());
            scene.setUpdateBy(currentUser.getName());
            scene.setDateUpdate(new Date());
            scene.setDateCreate(new Date());
        }
        if (scene.getDeptOrgId() != null && scene.getDeptOrgId() == 0) {
            scene.setDeptOrgId(null);
        }

        // 如果没有设置父节点，则代表为跟节点，有则获取父节点实体
        if (scene.getParentSceneId() == null || StringUtils.isBlank(scene.getParentSceneId().toString())) {
            scene.setParentSceneId(Long.valueOf(0));
        } else {
            scene.setParentSceneId(scene.getParentSceneId());
        }
        if (scene.getParentSceneId() == null) {
            scene.setParentSceneIds("0,");
        }
        //查询父节点信息
        SceneEntity sceneEntity = sceneMapper.findSceneById(scene.getParentSceneId());
        if (this.save(scene)) {
            Long id = scene.getId();
            // 设置新的父节点串
            if (sceneEntity != null) {
                scene.setParentSceneIds(sceneEntity.getParentSceneIds() + id + ",");
            } else {
                scene.setParentSceneIds("0," + id + ",");
            }
            sceneMapper.updateById(scene);

            //增加场景图片
            if (scene.getSceneImages() != null) {
                for (SceneImageEntity sceneImage : scene.getSceneImages()) {
                    sceneImage.setCreateBy(currentUser.getName());
                    sceneImage.setDateCreate(new Date());
                    sceneImage.setDateUpdate(new Date());
                    sceneImage.setSceneId(id);
                    sceneImage.setStatus(1);
                    sceneImage.setUpdateBy(currentUser.getName());
                }
                sceneImageService.saveBatch(scene.getSceneImages());
            }
            return true;
        }
        return false;
    }

    /**
     * 根据父级ID查询所有子节点及本身
     */
    public List<SceneEntity> findByParentLike(Long id) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        SceneEntity scene = new SceneEntity();
        if (id != null) {
            scene.setParentSceneIds("%," + id + ",%");
        }
        scene.setTenantId(currentUser.getTenantId());
        scene.setStatus(1);
        scene.setProgramItems(currentUser.getProgramItemList());
        scene.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        scene.setPermissonType(currentUser.getPermissonType());
        List<SceneEntity> list = sceneMapper.findByParentIdsLike(scene);
        return list;
    }

    /**
     * 根据父级ID查询所有子节点及本身
     */
    public List<Long> findByParentIdsLike(Long id) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        SceneEntity scene = new SceneEntity();
        if (id != null) {
            scene.setParentSceneIds("%," + id + ",%");
        }
        scene.setTenantId(currentUser.getTenantId());
        scene.setStatus(1);
        scene.setProgramItems(currentUser.getProgramItemList());
        scene.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        scene.setPermissonType(currentUser.getPermissonType());
        List<SceneEntity> list = sceneMapper.findByParentIdsLike(scene);
        List<Long> longs = newArrayList();
        for (SceneEntity item : list) {
            longs.add(item.getId());
        }
        return longs;
    }
    /**
     * 根据父级ID查询所有子节点及本身
     */
    public List<Long> findByParentIdsByCom(Long id) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        SceneEntity scene = new SceneEntity();
        scene.setTenantId(currentUser.getTenantId());
        scene.setStatus(1);
        scene.setCompanyOrgId(id);
        scene.setProgramItems(currentUser.getProgramItemList());
        scene.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        scene.setPermissonType(currentUser.getPermissonType());
        List<SceneEntity> list = sceneMapper.findByParentIdsLike(scene);
        List<Long> longs = newArrayList();
        for (SceneEntity item : list) {
            longs.add(item.getId());
        }
        return longs;
    }
    /**
     * 修改根居ID
     */
    public boolean updateSceneById(SceneEntity scene) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        scene.setUpdateBy(currentUser.getName());
        if (scene.getDeptOrgId() != null && scene.getDeptOrgId() == 0) {
            scene.setDeptOrgId(null);
        }
        // 获取修改前的parentIds，用于更新子节点的parentIds
        SceneEntity cScene = sceneMapper.findSceneById(scene.getId());
        String oldParentIds = cScene.getParentSceneIds();
        // 如果没有设置父节点，则代表为跟节点，有则获取父节点实体
        if (scene.getParentSceneId() == null || StringUtils.isBlank(scene.getParentSceneId().toString())) {
            scene.setParentSceneId(Long.valueOf(0));
        } else {
            scene.setParentSceneId(scene.getParentSceneId());
        }
        if (scene.getParentSceneId() == null) {
            scene.setParentSceneIds("0,");
        }
        //查询父节点信息
        SceneEntity sceneEntity = sceneMapper.findSceneById(scene.getParentSceneId());
        if (this.updateById(scene)) {
            // 设置新的父节点串
            if (sceneEntity != null) {
                scene.setParentSceneIds(sceneEntity.getParentSceneIds() + scene.getId() + ",");
            } else {
                scene.setParentSceneIds("0," + scene.getId() + ",");
            }
            sceneMapper.updateById(scene);
            // 更新子节点 parentIds
            Class<SceneEntity> entityClass = Reflections.getClassGenricType(getClass(), 1);
            SceneEntity o = null;
            try {
                o = entityClass.newInstance();
            } catch (Exception e) {

            }
            o.setParentSceneIds("%," + scene.getId() + ",%");
            List<SceneEntity> list = sceneMapper.findByParentIdsLike(o);
            for (SceneEntity e : list) {
                if (!e.getId().equals(scene.getId()) && e.getParentSceneId() != null && oldParentIds != null) {
                    e.setParentSceneIds(e.getParentSceneIds().replace(oldParentIds, scene.getParentSceneIds()));
                    e.setDeptOrgId(scene.getDeptOrgId());
                    e.setCompanyOrgId(scene.getCompanyOrgId());
                    sceneMapper.updateById(e);
                }
            }
            //删除之前的图片信息
            sceneImageService.updateBySceneId(scene.getId());
            //增加场景图片
            if (scene.getSceneImages() != null) {
                for (SceneImageEntity sceneImage : scene.getSceneImages()) {
                    sceneImage.setCreateBy(currentUser.getName());
                    sceneImage.setDateCreate(new Date());
                    sceneImage.setDateUpdate(new Date());
                    sceneImage.setSceneId(scene.getId());
                    sceneImage.setStatus(1);
                    sceneImage.setUpdateBy(currentUser.getName());
                }
                sceneImageService.saveBatch(scene.getSceneImages());
            }
            return true;
        }
        return false;
    }

    /**
     * 根居ID获取对象
     */
    public SceneEntity findSceneById(Long id) {
        SceneEntity sceneEntity = sceneMapper.findSceneById(id);
        SceneImageEntity sceneImageEntity = new SceneImageEntity();
        sceneImageEntity.setSceneId(id);
        List<SceneImageEntity> sceneImageEntities = sceneImageService.findList(sceneImageEntity);
        sceneEntity.setSceneImages(sceneImageEntities);
        return sceneEntity;
    }
    /**
     * 根居ID获取对象
     */
    public SceneEntity findSceneByIdForApp(Long id) {
        SceneEntity sceneEntity = sceneMapper.findSceneById(id);
        SceneImageEntity sceneImageEntity = new SceneImageEntity();
        sceneImageEntity.setSceneId(id);
        sceneImageEntity.setImageType(3L);
        List<SceneImageEntity> sceneImageEntities = sceneImageService.findList(sceneImageEntity);
        sceneEntity.setSceneImages(sceneImageEntities);
        return sceneEntity;
    }

    public List<SceneEntity> findBySceneTypeIds(Long[] Ids) {
        return sceneMapper.findBySceneTypeIds(Ids);
    }


    public List<SceneEntity> findByParentSceneIds(Long[] Ids) {
        return sceneMapper.findByParentSceneIds(Ids);
    }

    public List<SceneEntity> selectByTypeName(SceneEntity sceneEntity) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        sceneEntity.setTenantId(currentUser.getTenantId());
        sceneEntity.setProgramItems(currentUser.getProgramItemList());
        sceneEntity.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        sceneEntity.setPermissonType(currentUser.getPermissonType());
        return sceneMapper.selectByTypeName(sceneEntity);
    }

    public List<SceneEntity> findByParentId(Long id) {
        SceneEntity sceneEntity = new SceneEntity();
        LoginUser currentUser = UserUtil.getCurrentUser();
        sceneEntity.setTenantId(currentUser.getTenantId());
        sceneEntity.setProgramItems(currentUser.getProgramItemList());
        sceneEntity.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        sceneEntity.setPermissonType(currentUser.getPermissonType());
        if (id != null) {
            sceneEntity.setParentSceneIds("%," + id + ",%");
        }
        List<SceneEntity> sceneEntities = sceneMapper.findByParentId(sceneEntity);
        for (SceneEntity item : sceneEntities) {
            SceneImageEntity sceneImageEntity = new SceneImageEntity();
            sceneImageEntity.setSceneId(item.getId());
            List<SceneImageEntity> sceneImageEntities = sceneImageService.findList(sceneImageEntity);
            item.setSceneImages(sceneImageEntities);
        }

        List<SceneEntity> sceneTree = getSceneTree(sceneEntities, Long.valueOf(0), 1);
        return sceneTree;
    }
    public List<SceneEntity> findByParentIdForAPP(Long id) {
        SceneEntity sceneEntity = new SceneEntity();
        LoginUser currentUser = UserUtil.getCurrentUser();
        sceneEntity.setTenantId(currentUser.getTenantId());
        sceneEntity.setProgramItems(currentUser.getProgramItemList());
        sceneEntity.setUserType(currentUser.getType());
        //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
        sceneEntity.setPermissonType(currentUser.getPermissonType());
        if (id != null) {
            sceneEntity.setParentSceneIds("%," + id + ",%");
        }
        List<SceneEntity> sceneEntities = sceneMapper.findByParentId(sceneEntity);
        for (SceneEntity item : sceneEntities) {
            SceneImageEntity sceneImageEntity = new SceneImageEntity();
            sceneImageEntity.setSceneId(item.getId());
            sceneImageEntity.setImageType(3L);
            List<SceneImageEntity> sceneImageEntities = sceneImageService.findList(sceneImageEntity);
            item.setSceneImages(sceneImageEntities);
            //判断此场景是否有报警
            List<AlarmDetailsDto> alarmList = alarmDetailsService.selectBySceneId(item.getId().intValue());
            if (alarmList.size() > 0) {
                item.setIsAlarm(1);
            } else {
                item.setIsAlarm(0);
            }
        }

        List<SceneEntity> sceneTree = getSceneTree(sceneEntities, Long.valueOf(0), 1);
        return sceneTree;
    }

    /**
     * 根据场景id查询一级场景信息
     */
    public SceneEntity findParentSceneById(Long id) {
        return sceneMapper.findParentSceneById(id);
    }

    public void saveUpdateBatch(List<DeviceSceneEntity> deviceScenes) {
        //先进行查询判断哪些设备已经被保存
    }

    public List<SceneEntity> selectByTypeNameForCom(SceneEntity sceneEntity, Long companyOrgId) {
        LoginUser currentUser = UserUtil.getCurrentUser();
        if (currentUser != null) {
            sceneEntity.setTenantId(currentUser.getTenantId());
            sceneEntity.setProgramItems(currentUser.getProgramItemList());
            sceneEntity.setUserType(currentUser.getType());
            //1是公司，2是公司及以下，3部门，4部门及以下，5自定义
            sceneEntity.setPermissonType(currentUser.getPermissonType());
        }
        sceneEntity.setCompanyOrgId(companyOrgId);
        return sceneMapper.selectByTypeName(sceneEntity);
    }

    public List<Map<String,Object>> selectAlarmSceneAndDevice(SceneEntity sceneEntity, String startDate, String endDate){
        return sceneMapper.selectAlarmSceneAndDevice(sceneEntity, startDate, endDate);
    }

    public List<Map<String,Object>> selectMonthAlarmTimes(@Param("scene") SceneEntity sceneEntity, @Param("startDate") String startDate, @Param("endDate") String endDate,@Param("sort") int sort) throws ParseException {
        int days = differentDaysByMillisecond(startDate,endDate);
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> list = sceneMapper.selectMonthAlarmTimes(sceneEntity,startDate,endDate,sort);
        for(int i=0; i<days; i++) {
            String strDate =  subDay(startDate,i);
            Map<String, Object> data = new HashMap<>();
            data.put("数量", 0);
            data.put("日期", strDate);
            data.put("序号",i+1);
            result.add(data);
        }
        for(int i=0;i<list.size();i++){
            Map<String,Object> map =list.get(i);
            int day = Integer.parseInt(map.get("日期").toString().substring(8,10));
            result.get(day-1).put("数量",map.get("数量"));
        }
        return result;
    }

    public List<Map<String,Object>> selectYearAlarmTimes(@Param("scene") SceneEntity sceneEntity, @Param("startDate") String startDate, @Param("endDate") String endDate,@Param("sort") int sort) throws ParseException {
        int months = differentMonths(startDate,endDate);
        List<Map<String,Object>> list = sceneMapper.selectYearAlarmTimes(sceneEntity,startDate,endDate,sort);
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        for(int i=0; i<months; i++) {
            String strDate = startDate.substring(0, 4) + String.format("-%02d", i + 1);
            Map<String, Object> data = new HashMap<>();
            data.put("数量", 0);
            data.put("日期", strDate);
            data.put("序号",i+1);
            result.add(data);
        }
        for(int i=0;i<list.size();i++){
            Map<String,Object> map =list.get(i);
            int month = Integer.parseInt(map.get("日期").toString().substring(5,7));
            result.get(month-1).put("数量",map.get("数量"));
        }
        return result;
    }



    public List<Map<String,Object>> selectAlarmLable(@Param("scene") SceneEntity sceneEntity, @Param("startDate") String startDate, @Param("endDate") String endDate, @Param("sort") int sort){
        return sceneMapper.selectAlarmLable(sceneEntity, startDate, endDate, sort);
    }

    public List<Map<String,Object>> selectAlarmDeviceIdBySenceId(int id){
        return sceneMapper.selectAlarmDeviceIdBySenceId(id);
    }




    public int differentDaysByMillisecond(String date1,String date2) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt1 = sdf.parse(date1);
        Date dt2 = sdf.parse(date2);
        int days = (int) ((dt2.getTime() - dt1.getTime()) / (1000*3600*24));
        return days;
    }



    /**
     * 计算2个日期之间相差的  以年、月、日为单位，各自计算结果是多少
     * 比如：2011-02-02 到  2017-03-02
     *                                以年为单位相差为：6年
     *                                以月为单位相差为：73个月
     *                                以日为单位相差为：2220天
     * @param startDate
     * @param endDate
     * @return
     */
    public int differentMonths(String startDate,String endDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date fromDate = sdf.parse(startDate);
        Date toDate = sdf.parse(endDate);
        Calendar  from  =  Calendar.getInstance();
        from.setTime(fromDate);
        Calendar  to  =  Calendar.getInstance();
        to.setTime(toDate);
        //只要年月
        int fromYear = from.get(Calendar.YEAR);
        int fromMonth = from.get(Calendar.MONTH);

        int toYear = to.get(Calendar.YEAR);
        int toMonth = to.get(Calendar.MONTH);
        // int year = toYear  -  fromYear;
        int month = toYear *  12  + toMonth  -  (fromYear  *  12  +  fromMonth);
        // int day = (int) ((to.getTimeInMillis()  -  from.getTimeInMillis())  /  (24  *  3600  *  1000));
        return month;
    }


    /**
     *日期加一天
     */
    private String subDay(String date, int n) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = sdf.parse(date);
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.DATE, n);
        Date dt1 = rightNow.getTime();
        String reStr = sdf.format(dt1);
        return reStr;
    }


}
