package org.wcs.mapper.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.wcs.mapper.AppRecordErrMapper;
import org.wcs.mapper.intf.AppRecordErrService;
import org.wcs.model.bo.tuple.Tuple2;
import org.wcs.model.dto.serve.recordError.QueryEquipmentErrorReq;
import org.wcs.model.po.app.AppBaseErrInfo;
import org.wcs.model.po.app.AppRecordErr;
import org.wcs.model.po.app.JoinRecordError;
import org.wcs.utils.AppStringUtils;
import org.wcs.utils.AppTimeUtils;

import java.lang.invoke.VarHandle;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 错误记录数据访问层实现
 */
@Slf4j
@Service
public class AppRecordErrDao extends ServiceImpl<AppRecordErrMapper, AppRecordErr> implements AppRecordErrService {

    /**
     * 插入数据
     * @param record 待插入数据
     * @return 插入结果
     */
    @Override
    public int insert(AppRecordErr record) {
        if(record == null) {
            return 0;
        }
        record.setCreateTime(LocalDateTime.now());
        try {
            return baseMapper.insert(record);
        } catch (Exception e) {
            log.error("异常记录表插入数据失败，数据：{}", AppStringUtils.objectToString(record), e);
            return 0;
        }
    }

    /**
     * 查询设备错误详情
     * @param request 查询参数
     * @param pageSize 分页大小
     * @param pageIndex 索引
     * @return 查询结果
     */
    @Override
    public Tuple2<Long, List<JoinRecordError>> queryRecordErrorDetail(QueryEquipmentErrorReq request, Integer pageSize, Integer pageIndex) {
        MPJLambdaWrapper<AppRecordErr> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(AppRecordErr.class)
                .select(AppBaseErrInfo::getErrLevel)
                .select(AppBaseErrInfo::getErrType)
                .select(AppBaseErrInfo::getErrMsg);
        wrapper.leftJoin(AppBaseErrInfo.class,
                q -> q.eq(AppRecordErr::getErrCode, AppBaseErrInfo::getErrCode)
                        .eq(AppRecordErr::getEquipmentType, AppBaseErrInfo::getEquipmentType));
        wrapper.eq(request.getEquipmentId() != null, AppRecordErr::getEquipmentId, request.getEquipmentId())
                .eq(request.getEquipmentType() != null, AppRecordErr::getEquipmentType, request.getEquipmentType())
                .eq(request.getErrCode() != null, AppRecordErr::getErrCode, request.getErrCode());
        if(request.getCreateTime() != null && request.getCreateTime().length == 2) {
            wrapper.between(AppRecordErr::getCreateTime, request.getCreateTime()[0], request.getCreateTime()[1]);
        }
        wrapper.orderByDesc(AppRecordErr::getCreateTime);
        Page<JoinRecordError> page = new Page<>(pageIndex, pageSize);
        try {
            IPage<JoinRecordError> pageResult = super.baseMapper.selectJoinPage(page, JoinRecordError.class, wrapper);
            return new Tuple2<>(pageResult.getTotal(), pageResult.getRecords());
        } catch (Exception e) {
            log.error("查询设备错误详情失败，参数：{}", AppStringUtils.objectToString(request), e);
            return null;
        }
    }

    @Override
    public List<JoinRecordError> queryRecordErrorDetail(QueryEquipmentErrorReq request) {
        MPJLambdaWrapper<AppRecordErr> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(AppRecordErr.class)
                .select(AppBaseErrInfo::getErrLevel)
                .select(AppBaseErrInfo::getErrType)
                .select(AppBaseErrInfo::getErrMsg);
        wrapper.leftJoin(AppBaseErrInfo.class,
                q -> q.eq(AppRecordErr::getErrCode, AppBaseErrInfo::getErrCode)
                        .eq(AppRecordErr::getEquipmentType, AppBaseErrInfo::getEquipmentType));
        wrapper.eq(request.getEquipmentId() != null, AppRecordErr::getEquipmentId, request.getEquipmentId())
                .eq(request.getEquipmentType() != null, AppRecordErr::getEquipmentType, request.getEquipmentType())
                .eq(request.getErrCode() != null, AppRecordErr::getErrCode, request.getErrCode());
        if(request.getCreateTime() != null && request.getCreateTime().length == 2) {
            wrapper.between(AppRecordErr::getCreateTime, request.getCreateTime()[0], request.getCreateTime()[1]);
        }
        wrapper.orderByDesc(AppRecordErr::getCreateTime);
        try {
            return super.baseMapper.selectJoinList(JoinRecordError.class, wrapper);
        } catch (Exception e) {
            log.error("查询设备错误详情失败，参数：{}", AppStringUtils.objectToString(request), e);
            return null;
        }
    }

    /**
     * 查询最近N天的设备错误详情
     * @param days 天数
     * @return 错误详情
     */
    @Override
    public List<AppRecordErr> queryRecordErrorDetailRecentDays(int days) {
        try {
            LambdaQueryWrapper<AppRecordErr> wrapper = new LambdaQueryWrapper<>();
            wrapper.ge(AppRecordErr::getCreateTime, AppTimeUtils.getTodayEndTime().minusDays(days));
            return super.baseMapper.selectList(wrapper);
        } catch (Exception e) {
            return null;
        }
    }


}
