package com.sptg.device.biz.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.device.api.entity.InstructPublishLog;
import com.sptg.device.biz.mapper.InstructPublishLogMapper;
import com.sptg.device.biz.service.InstructPublishLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

/**
 *
 *
 * description:
 */
@Service
@RequiredArgsConstructor
public class InstructPublishLogServiceImpl extends ServiceImpl<InstructPublishLogMapper, InstructPublishLog>
        implements InstructPublishLogService {

    /**
     * 计算出前30分钟的时间
     * @param nowDate
     * @return
     */
    private Date beforeDate(Date nowDate){
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(nowDate);
        calendar.add(Calendar.MINUTE, -30);
        Date beforeDate = calendar.getTime();
        return beforeDate;
    }


    @Override
    public Page<InstructPublishLog> pagingQuery(PageBean<InstructPublishLog,InstructPublishLog> pageBean){
        InstructPublishLog dto = pageBean.getDto();
        Wrapper<InstructPublishLog> wrapper = new EntityWrapper<>();
        if (!StringUtils.isEmpty(dto.getInstructCode())){
            wrapper.eq("instruct_code",dto.getInstructCode());
        }
        if (StringUtils.hasText(dto.getSerialNumber())){
            wrapper.eq("serial_number",dto.getSerialNumber());
        }
        if (StringUtils.hasText(dto.getInstructCode())){
            wrapper.eq("instruct_code",dto.getInstructCode());
        }
        if (dto.getSortField() != null && dto.getSortOrder() != null){
            wrapper.orderBy(dto.getSortField(),dto.getSortOrder().equals("asc"));
        }
        if (!StringUtils.isEmpty(dto.getCardNo())){
            wrapper.like("card_no",dto.getCardNo(),SqlLike.RIGHT);
        }
        Integer handleStatus = dto.getHandleStatus();
        if (null != handleStatus && handleStatus != 0){
            wrapper.eq("handle_status", handleStatus);
        }
        if (null != dto.getBeginDate()){
            wrapper.ge("create_time",dto.getBeginDate());
        }
        if (null != dto.getEndDate()){
            wrapper.lt("create_time",dto.getEndDate());
        }
        wrapper.orderBy("create_time", false);
        Page<InstructPublishLog> page = this.selectPage(pageBean,wrapper);

        //返回结果之前先处理是否有作废的记录
        long overTime = System.currentTimeMillis() - 1000 * 60 * 30;
        List<InstructPublishLog> instructPublishLogList = new ArrayList<>();
        page.getRecords().forEach(instructPublishLog -> {
            if (instructPublishLog.getStatus() != OperationConstant.TWO){
                Long time;
                if (null != instructPublishLog.getLastResendTime()){
                    time = instructPublishLog.getLastResendTime().getTime();
                }else {
                    time = instructPublishLog.getCreateTime().getTime();
                }
                if (time < overTime){
                    instructPublishLog.setInvalid(OperationConstant.TWO);
                    instructPublishLogList.add(instructPublishLog);
                }else {
                    instructPublishLog.setInvalid(OperationConstant.ONE);
                    instructPublishLogList.add(instructPublishLog);
                }
            }else {
                instructPublishLog.setInvalid(OperationConstant.ONE);
                instructPublishLogList.add(instructPublishLog);
            }
        });
        page.setRecords(instructPublishLogList);
        return page;
    }


    @Override
    public Page<InstructPublishLog> pageFace(PageBean<InstructPublishLog, InstructPublishLog> pageBean) {
        InstructPublishLog dto = pageBean.getDto();
        Wrapper<InstructPublishLog> wrapper = new EntityWrapper<>();
        if (!StringUtils.isEmpty(dto.getSerialNumber())){
            wrapper.like("serial_number",dto.getSerialNumber(),SqlLike.RIGHT);
        }
        if (null != dto.getHandleStatus()){
            wrapper.eq("handle_status",dto.getHandleStatus());
        }
        if (null != dto.getBeginDate()){
            wrapper.ge("create_time",dto.getBeginDate());
        }
        if (null != dto.getEndDate()){
            wrapper.lt("create_time",dto.getEndDate());
        }
        //添加人脸指令过滤
        wrapper.eq("instruct_code", "add_user_face");
        if (StringUtils.hasText(dto.getPublishData())){
            //按照传送数据的格式，组装userId信息，作模糊匹配，用于对用户进行过滤
            String publishData = "\"id\":\"u_" + dto.getPublishData() + "\"";
            dto.setPublishData(null);
            wrapper.like("publish_data", publishData, SqlLike.DEFAULT);
        }
        return this.selectPage(pageBean,wrapper);
    }

    @Override
    public Page<InstructPublishLog> pageCard(PageBean<InstructPublishLog, InstructPublishLog> pageBean) {
        InstructPublishLog dto = pageBean.getDto();
        Wrapper<InstructPublishLog> wrapper = new EntityWrapper<>();
        if (!StringUtils.isEmpty(dto.getSerialNumber())){
            wrapper.like("serial_number",dto.getSerialNumber(),SqlLike.RIGHT);
        }
        if (null != dto.getHandleStatus()){
            wrapper.eq("handle_status",dto.getHandleStatus());
        }
        if (null != dto.getBeginDate()){
            wrapper.ge("create_time",dto.getBeginDate());
        }
        if (null != dto.getEndDate()){
            wrapper.lt("create_time",dto.getEndDate());
        }
        wrapper.orderBy("create_time",false);
        //添加门禁卡指令过滤
        if (StringUtils.hasText(dto.getPublishData())){
            //按照传送数据的格式，组装门禁卡信息，作模糊匹配，用于对用户进行过滤
            String publishData = "\"cardNo\":\"" + dto.getPublishData() + "\"";
            dto.setPublishData(null);
            wrapper.like("publish_data", publishData, SqlLike.DEFAULT);
        }
        wrapper.and("(instruct_code = 'add_open_door_card' OR instruct_code = 'del_open_door_card')");
        Page<InstructPublishLog> instructPublishLogPage = this.selectPage(pageBean, wrapper);
        return instructPublishLogPage;
    }

    @Override
    public Page<InstructPublishLog> pageAppPackage(PageBean<InstructPublishLog, InstructPublishLog> pageBean) {
        InstructPublishLog dto = pageBean.getDto();
        Wrapper<InstructPublishLog> wrapper = new EntityWrapper<>();
        //添加设备版本指令过滤
        if (StringUtils.hasText(dto.getPublishData())){
            //按照传送数据的格式，组装设备版本信息，作模糊匹配
            String publishData = "\"version\":\"" + dto.getPublishData() + "\"";
            dto.setPublishData(null);
            wrapper.like("publish_data", publishData, SqlLike.DEFAULT);
        }
        wrapper.eq("instruct_code","update_app_package");
        Page<InstructPublishLog> instructPublishLogPage = this.selectPage(pageBean, wrapper);
        return instructPublishLogPage;
    }

    @Override
    public List<InstructPublishLog> getListPutBin(InstructPublishLog instructPublishLog){
        Wrapper<InstructPublishLog> wrapper = new EntityWrapper<>();
        if (null != instructPublishLog.getBeginDate()){
            wrapper.lt("create_time",instructPublishLog.getBeginDate());
        }
        wrapper.eq("status",OperationConstant.TWO);
        wrapper.eq("handle_status",OperationConstant.TWO);
        List<InstructPublishLog> list = this.selectList(wrapper);
        return list;
    }

    @Override
    public ResultBean<Boolean> deletePutBinList(List<InstructPublishLog> logList){
        Assert.isTrue(logList.size() > 0,"删除数据不能为空");
        List<Long> ids = new ArrayList<>();
        logList.forEach(instructPublishLog -> {
            ids.add(instructPublishLog.getId());
        });
        return new ResultBean<>(ResultEnum.SUCCESS,this.deleteBatchIds(ids));
    }
    @Override
    public List<InstructPublishLog> findInstructPublishLogByCondition(InstructPublishLog instructPublishLog){
        Wrapper<InstructPublishLog> wrapper = new EntityWrapper<>();
        if (!StringUtils.isEmpty(instructPublishLog.getSerialNumber())){
           wrapper.eq("serial_number",instructPublishLog.getSerialNumber());
        }
        wrapper.notIn("handle_status",OperationConstant.TWO);
        List<String> list = new ArrayList<>();
        list.add("add_user_face");
        list.add("delete_user_face");
        list.add("add_user_face_batch");
        list.add("delete_user_face_batch");
        list.add("add_open_door_card");
        list.add("del_open_door_card");
        list.add("add_open_door_card_batch");
        list.add("del_open_door_card_batch");
        wrapper.in("instruct_code",list);
        return this.selectList(wrapper);
    }
//    @Override
//    public ResultBean<Boolean> resendInstruct(InstructPublishLog instructPublishLog) {
//        String publishData = instructPublishLog.getPublishData();
//        JSONObject jsonObject = JSONObject.parseObject(publishData);
//        String serialNumber = instructPublishLog.getSerialNumber();
//        msgPublishService.asyncResendInstruct(jsonObject, serialNumber, instructPublishLog);
//        return ResultBean.ok(true);
//    }
//
//
//    @Override
//    public ResultBean<Boolean> resendInstructDH(InstructPublishLog instructPublishLog) {
//        String publishData = instructPublishLog.getPublishData();
//        JSONObject jsonObject = JSONObject.parseObject(publishData);
//        String serialNumber = instructPublishLog.getSerialNumber();
//        msgPublishService.asyncResendInstructDH(jsonObject, serialNumber, instructPublishLog);
//        return ResultBean.ok(true);
//    }
}
