package org.dromara.monitoring.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.monitoring.config.SnowFlakeUtil;
import org.dromara.monitoring.domain.MonDevicePreset;
import org.dromara.monitoring.domain.bo.MonDevicePresetBo;
import org.dromara.monitoring.domain.dto.DelYzd;
import org.dromara.monitoring.domain.vo.MonDevicePresetVo;
import org.dromara.monitoring.mapper.MonDevicePresetMapper;
import org.dromara.monitoring.monEnum.YsPort;
import org.dromara.monitoring.service.IMonDevicePresetService;
import org.dromara.monitoring.service.MonitoringYsService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 摄像头预置位Service业务层处理
 *
 * @author LionLi
 * @date 2025-09-23
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MonDevicePresetServiceImpl implements IMonDevicePresetService {

    private final MonDevicePresetMapper baseMapper;

    private  final MonitoringYsService monitoringYsService;

    /**
     * 查询摄像头预置位
     *
     * @param id 主键
     * @return 摄像头预置位
     */
    @Override
    public MonDevicePresetVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询摄像头预置位列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 摄像头预置位分页列表
     */
    @Override
    public TableDataInfo<MonDevicePresetVo> queryPageList(MonDevicePresetBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MonDevicePreset> lqw = buildQueryWrapper(bo);
        Page<MonDevicePresetVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的摄像头预置位列表
     *
     * @param bo 查询条件
     * @return 摄像头预置位列表
     */
    @Override
    public List<MonDevicePresetVo> queryList(MonDevicePresetBo bo) {
        LambdaQueryWrapper<MonDevicePreset> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MonDevicePreset> buildQueryWrapper(MonDevicePresetBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MonDevicePreset> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(MonDevicePreset::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceSerial()), MonDevicePreset::getDeviceSerial, bo.getDeviceSerial());
        lqw.eq(bo.getChannelNo() != null, MonDevicePreset::getChannelNo, bo.getChannelNo());
        lqw.eq(bo.getPresetIndex() != null, MonDevicePreset::getPresetIndex, bo.getPresetIndex());
        lqw.like(StringUtils.isNotBlank(bo.getPresetName()), MonDevicePreset::getPresetName, bo.getPresetName());
        return lqw;
    }

    /**
     * 新增摄像头预置位
     *
     * @param bo 摄像头预置位
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(MonDevicePresetBo bo) {
        MonDevicePreset add = MapstructUtils.convert(bo, MonDevicePreset.class);
        validEntityBeforeSave(add);
        String jsonStr = HttpRequest
            .post(YsPort.ADDDEVICEPRESETURLBYPOST.getSite()).
            form("accessToken",monitoringYsService.getYsTokenService())
            .form("deviceSerial", add.getDeviceSerial())
            .form("channelNo", add.getChannelNo())
            .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr.trim());

        Map page1 = JSONUtil.parseObj(jsonObject.get("data")).toBean(Map.class);


        add.setPresetIndex(Integer.parseInt(page1.get("index").toString()));
        add.setId(SnowFlakeUtil.getID());

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改摄像头预置位
     *
     * @param bo 摄像头预置位
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(MonDevicePresetBo bo) {
        MonDevicePreset update = MapstructUtils.convert(bo, MonDevicePreset.class);
        String jsonStr = HttpRequest
            .post(YsPort.ADDDEVICEPRESETURLBYPOST.getSite()).
            form("accessToken",monitoringYsService.getYsTokenService())
            .form("deviceSerial", update.getDeviceSerial())
            .form("channelNo", update.getChannelNo())
            .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr.trim());

        Map page1 = JSONUtil.parseObj(jsonObject.get("data")).toBean(Map.class);


        update.setPresetIndex(Integer.parseInt(page1.get("index").toString()));



        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MonDevicePreset entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除摄像头预置位信息
     *
     * @param
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(List<DelYzd> yzd, Boolean isValid) {
        if(isValid){
            if (yzd.size() >0){
                yzd.stream().forEach(temp ->{
                     HttpRequest
                        .post(YsPort.DELETEDEVICEPRESETURLBYPOST.getSite()).
                        form("accessToken",monitoringYsService.getYsTokenService())
                        .form("deviceSerial", temp.getDeviceSerial())
                        .form("channelNo", temp.getChannelNo())
                        .form("index", temp.getPresetIndex())
                        .execute().body();
                });
            }
        }
        Collection<Long> collect = yzd.stream().map(temp -> {
            return temp.getId();
        }).collect(Collectors.toList());
        return baseMapper.deleteByIds(collect) > 0;
    }

    @Override
    public boolean invoking(List<DelYzd> yzd) {
        try {
            yzd.stream().forEach(temp ->{{
                HttpRequest
                    .post(YsPort.MOVEDEVICEPRESETURLBYPOST.getSite()).
                    form("accessToken",monitoringYsService.getYsTokenService())
                    .form("deviceSerial", temp.getDeviceSerial())
                    .form("channelNo", temp.getChannelNo())
                    .form("index", temp.getPresetIndex())
                    .execute().body();
            }});
        }catch (Exception e) {
            return false;
        }

        return true;
    }
}
