package com.mvc.service.app;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.dao.AppDeviceGroupMapper;
import com.mvc.entity.AppDeviceGroup;
import com.mvc.entity.AppDeviceGroupExample;
import com.mvc.entity.CustomUser;
import com.mvc.entity.FacUser;
import com.mvc.model.*;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.setup.TSetupService;
import com.mvc.service.taizhang.CustomizeGroupService;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.service.taizhang.TaskRemoteCfgService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional
public class AppDeviceGroupService {
    @Resource
    private AppDeviceGroupMapper appDeviceGroupMapper;

    @Resource
    private AppDevgroupDetailService appDevgroupDetailService;

    @Resource
    private TAireadService tAireadService;

    @Resource
    private StationAccService stationAccService;

    @Resource
    private TaskRemoteCfgService taskRemoteCfgService;

    @Resource
    private TSetupService tSetupService;

    @Resource
    private AppUserService appUserService;

    @Resource
    private CustomizeGroupService customizeGroupService;

    public List<AppDeviceGroupModel> findAllAppDeviceGroupByUserid(String userid) {
        AppDeviceGroupExample example = new AppDeviceGroupExample();
        AppDeviceGroupExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userid);
        example.setOrderByClause("CREATE_TIME desc");
        return selectByExample(example, false);
    }

    /**
     * 根据用户id和分组名称查询分组
     * @param userId
     * @param groupName
     * @return
     */
    public AppDeviceGroupModel findAppDeviceGroupByUserIdAndGroupName(String userId, String groupName) {
        if(StringUtils.isEmpty(userId)||StringUtils.isEmpty(groupName)){
            return null;
        }
        AppDeviceGroupExample example = new AppDeviceGroupExample();
        AppDeviceGroupExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andGroupNameEqualTo(groupName);

        List<AppDeviceGroupModel> list = selectByExample(example,false);
        return list.size() > 0 ? list.get(0) : null;
    }

    /**
     * 根据AppDeviceGroupExample查询数据
     * @param example
     * @param isIncludeData
     * @return
     */
    private List<AppDeviceGroupModel> selectByExample(AppDeviceGroupExample example, boolean isIncludeData) {
        List<AppDeviceGroup> AppDeviceGroups = appDeviceGroupMapper.selectByExample(example);
        List<AppDeviceGroupModel> resList = new ArrayList<>();
        for (AppDeviceGroup AppDeviceGroup : AppDeviceGroups) {
            AppDeviceGroupModel model = new AppDeviceGroupModel();
            BeanUtils.copyProperties(AppDeviceGroup, model);
            if (isIncludeData) {
                model.setDetailCount(appDevgroupDetailService.countByGroupId(AppDeviceGroup.getGroupId()));
            }
            resList.add(model);
        }
        return resList;
    }

    public Map<String, Object> findAllAppDeviceGroup(AppDeviceGroupModel queryModel) {
        Map<String, Object> resMap = new CorrectMap();

        AppDeviceGroupExample example = new AppDeviceGroupExample();
        AppDeviceGroupExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotEmpty(queryModel.getGroupName())) {
            criteria.andGroupNameLike(StringUtil.getLikeFormat(queryModel.getGroupName()));
        }
        if (StringUtils.isNotEmpty(queryModel.getGroupType())) {
            criteria.andGroupTypeEqualTo(queryModel.getGroupType());
        }
        if (StringUtils.isNotEmpty(queryModel.getUserId())) {
            criteria.andUserIdEqualTo(queryModel.getUserId());
        }

        example.setOrderByClause("CREATE_TIME desc");
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPage(), queryModel.getRows());
        List<AppDeviceGroupModel> resList = selectByExample(example, true);
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    public AppDeviceGroupModel saveAppDeviceGroup(AppDeviceGroupModel model) {
        model.setGroupId(StringUtil.getUuid());
        model.setCreateTime(new Date());
        AppDeviceGroup AppDeviceGroup = new AppDeviceGroup();
        BeanUtils.copyProperties(model, AppDeviceGroup);
        int insert = appDeviceGroupMapper.insert(AppDeviceGroup);
        model.setId(AppDeviceGroup.getId());
        setAttachedProperties(model);
        return model;
    }

    /**
     * (预留)根据用户所属单位校验是否有查看站点的权限
     *
     * @param model
     * @return
     */
    private String checkStationInfoByAppUserId(AppDeviceGroupModel model) {
        StationAccModel accModel = null;
        if (model.getGroupType().equals("1")) {
            stationAccService.findStationAccByDeviceSn(model.getGroupName());
        } else {
            stationAccService.findStationAccByStationCode(model.getGroupName());
        }
        if (accModel == null) {
            return "[" + model.getGroupName() + "]未在遥测站台账中登记";
        }
        AppUserModel userModel = appUserService.getModelByUserId(model.getUserId());
        if (userModel != null && userModel.getUserType().equals("0")) {
            if (!accModel.getCreateUnitCode().equals(userModel.getUnitCode()) &&
                    !accModel.getVisUnitCodes().contains(userModel.getUnitCode()) &&
                    !accModel.getUnitCode().contains(userModel.getUnitCode())) {
                return "[" + model.getGroupName() + "]无权收藏此数据";
            }
        }
        return "";
    }

    public AppDeviceGroupModel updateAppDeviceGroup(AppDeviceGroupModel model) {
        if (model.getIsTop() != null && model.getIsTop() == 1) {//置顶时更新CreateTime
            model.setCreateTime(new Date());
        }

        AppDeviceGroup AppDeviceGroup = appDeviceGroupMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, AppDeviceGroup);
        int i = appDeviceGroupMapper.updateByPrimaryKey(AppDeviceGroup);
        setAttachedProperties(model);
        return model;
    }

    //删除组,并清空下面的明细
    public int deleteAppDeviceGroup(int id) {
        int i = 0;
        AppDeviceGroup appDeviceGroup = appDeviceGroupMapper.selectByPrimaryKey(id);
        if (appDeviceGroup != null) {
            String groupid = appDeviceGroup.getGroupId();
            i = appDeviceGroupMapper.deleteByPrimaryKey(id);
            if (i > 0) {
                appDevgroupDetailService.deleteAppDevgroupDetailByGroupId(groupid, null);
            }
        }
        return i;
    }

    /**
     * 根据appUserid查询AppDeviceGroup列表(内嵌每个设备最新读数)
     *
     * @param queryModel
     * @return
     */
    public Map<String, Object> findLatestAiReadByAppUserId(AppDeviceGroupModel queryModel) {
        Map<String, Object> resMap = new HashMap<>();
        //此表APP借用为收藏列表,GroupType=1代表GroupName中存储的是DeviceSN,GroupType=2代表GroupName中存储的是StationCode 2022-10-26 guozhao
        AppDeviceGroupExample example = new AppDeviceGroupExample();
        AppDeviceGroupExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getUserId())) {
            criteria.andUserIdEqualTo(queryModel.getUserId());
        } else {
            return resMap;
        }
        if (StringUtils.isNotEmpty(queryModel.getGroupName())) {
            criteria.andGroupNameEqualTo(queryModel.getGroupName());
        }

        /*if (StringUtils.isNotEmpty(queryModel.getGroupType())) {
            criteria.andGroupTypeEqualTo(queryModel.getGroupType());
        }*/
        criteria.andGroupTypeNotEqualTo("3");//兼容新旧APP 2024-10-24 guozhao
        //预留时间查询接口
        if (StringUtils.isNotEmpty(queryModel.getStartTime())) {
            Date dtStartTime = DateUtil.parseTimeStr(queryModel.getStartTime(), "yyyyMMddHHmmss");
            criteria.andCreateTimeGreaterThanOrEqualTo(dtStartTime);
        }
        if (StringUtils.isNotEmpty(queryModel.getEndTime())) {
            Date dtEndTime = DateUtil.parseTimeStr(queryModel.getEndTime(), "yyyyMMddHHmmss");
            criteria.andCreateTimeLessThanOrEqualTo(dtEndTime);
        }
        example.setOrderByClause("CREATE_TIME desc");
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPage(), queryModel.getRows());
        List<AppDeviceGroup> AppDeviceGroups = appDeviceGroupMapper.selectByExample(example);
        List<AppDeviceGroupModel> resList = new ArrayList<>();
        for (AppDeviceGroup AppDeviceGroup : AppDeviceGroups) {
            AppDeviceGroupModel model = new AppDeviceGroupModel();
            BeanUtils.copyProperties(AppDeviceGroup, model);
            setAttachedProperties(model);
            resList.add(model);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    /**
     * 设置附加属性(最新读数,安装记录,远程配置任务)
     *
     * @param model
     */
    private void setAttachedProperties(AppDeviceGroupModel model) {
        String deviceSn = "";
        String stationCode = "";
        TAireadModel aireadModel = null;
        if (model.getGroupType().equals("1")) {//SN
            aireadModel = tAireadService.findLatestTAireadByDeviceSn(model.getGroupName());
            deviceSn = model.getGroupName();
        } else if (model.getGroupType().equals("2")) {//StationCode
            aireadModel = tAireadService.findLatesTAireadByStationCode(model.getGroupName());
            stationCode = model.getGroupName();
        }

        if (aireadModel != null) {
            //获取站名(不在tAireadService中获站名,是其它调用的地方不必要查站名)
            StationAccModel stationAccModel = stationAccService.findStationAccByStationCode(aireadModel.getStationCode());
            if (stationAccModel != null) {
                aireadModel.setStationName(stationAccModel.getStationName());
            }
            deviceSn = aireadModel.getDeviceSn();
            stationCode = StringUtils.isEmpty(stationCode) ? aireadModel.getStationCode() : stationCode;
        }

        //绑定最新的安装记录 2022-11-03 guozhao
        TSetupModel setupModel = tSetupService.findTSetupByStationCode(stationCode, deviceSn);
        if (setupModel != null) {
            model.setSetupModel(setupModel);
        }

        if (StringUtils.isNotEmpty(deviceSn)) {
            //当前SN有远程任务则将远程任务表TaskId的赋值给TaskRemoteCfgId
            TaskRemoteCfgModel taskModel = taskRemoteCfgService.findUnfinishedTaskByDeviceSn(deviceSn);
            if (taskModel != null) {
                model.setTaskRemoteCfgId(taskModel.getTaskId());
            }
        }

        model.setLatestAireadModel(aireadModel);
    }

    /**
     * 根据groupName获取对象(判重使用)
     *
     * @param groupName
     * @return
     */
    public AppDeviceGroupModel findAppDeviceGroupModelByGroupName(String groupName, String appUserId) {
        if (StringUtils.isNotEmpty(groupName)) {
            AppDeviceGroupExample example = new AppDeviceGroupExample();
            AppDeviceGroupExample.Criteria criteria = example.createCriteria();
            criteria.andGroupNameEqualTo(groupName);
            criteria.andUserIdEqualTo(appUserId);
            List<AppDeviceGroup> appDeviceGroups = appDeviceGroupMapper.selectByExample(example);
            if (appDeviceGroups != null && appDeviceGroups.size() > 0) {
                AppDeviceGroupModel model = new AppDeviceGroupModel();
                BeanUtils.copyProperties(appDeviceGroups.get(0), model);
                return model;
            }
        }
        return null;
    }

    /**
     * 复制分组
     *
     * @param groupId
     * @param appLoginId
     * @return
     */
    public String copyAppDeviceGroupModel(String groupId, String appLoginId) {
        AppUserModel appUserModel = appUserService.getModelByLoginid(appLoginId);
        if (appUserModel == null) {
            return String.format("[%s]账号信息不存在,请再次核实", appLoginId);
        }
        AppDeviceGroupExample example = new AppDeviceGroupExample();
        AppDeviceGroupExample.Criteria criteria = example.createCriteria();
        criteria.andGroupIdEqualTo(groupId);

        List<AppDeviceGroup> appDeviceGroups = appDeviceGroupMapper.selectByExample(example);
        if (appDeviceGroups == null || appDeviceGroups.isEmpty()) {
            return String.format("当前分组已不存在,请刷新后再次尝试", groupId);
        }

        AppDeviceGroupModel model = new AppDeviceGroupModel();
        AppDeviceGroup appDeviceGroup = appDeviceGroups.get(0);
        BeanUtils.copyProperties(appDeviceGroup, model);
        model.setId(null);
        model.setUserId(appUserModel.getUserId());
        model = saveAppDeviceGroup(model);
        List<AppDevgroupDetailModel> detailModelList = appDevgroupDetailService.findAllAppDevgroupDetailByGroupid(groupId);
        for (AppDevgroupDetailModel detailModel : detailModelList) {
            detailModel.setId(null);
            detailModel.setGroupId(model.getGroupId());
            appDevgroupDetailService.saveAppDevgroupDetail(detailModel);
        }
        return "操作成功,请刷新后查询\r\n分享后的数据独立存在,操作互不影响";
    }

    /**
     * 复制APP分组到自定义分组(web端)
     * @param id
     * @param userModel
     * @return
     */
    public CustomizeGroupModel copyAppDeviceGroupToCustomizeGroup(int id, Object userModel) {
        CustomizeGroupModel customizeGroupModel = new CustomizeGroupModel();
        AppDeviceGroup appDeviceGroup = appDeviceGroupMapper.selectByPrimaryKey(id);
        FacUser facUser = null;
        CustomUser customUser = null;

        if (userModel.getClass() == FacUser.class) {
            facUser = (FacUser) userModel;
        } else {
            customUser = (CustomUser) userModel;
        }

        if (appDeviceGroup != null) {
            customizeGroupModel.setGroupName(appDeviceGroup.getGroupName());
            customizeGroupModel.setGroupId(appDeviceGroup.getGroupId());
            customizeGroupModel.setPublicFlag("1");
            customizeGroupModel.setCodeType("0");//APP的分组编码类型只能是站点
            if (facUser != null) {
                customizeGroupModel.setUserType("0");
                customizeGroupModel.setCreateUserId(facUser.getUserId());
                customizeGroupModel.setCreateUserName(facUser.getUserName());
            } else {
                customizeGroupModel.setUserType("1");
                customizeGroupModel.setCreateUserId(customUser.getUserId());
                customizeGroupModel.setCreateUserName(customUser.getUserName());
                customizeGroupModel.setUnitCode(customUser.getUnitCode());
            }
            List<AppDevgroupDetailModel> detailModelList = appDevgroupDetailService.findAllAppDevgroupDetailByGroupid(appDeviceGroup.getGroupId());
            List<String> stationCodes = new ArrayList<>();
            for (AppDevgroupDetailModel detailModel : detailModelList) {
                stationCodes.add(detailModel.getStationCode());
            }
            customizeGroupModel.setStationCodes(StringUtils.join(stationCodes, ","));
            customizeGroupService.saveCustomizeGroup(customizeGroupModel);
        }
        return customizeGroupModel;
    }
}
