package im.zhaojun.system.service;

import com.github.pagehelper.PageHelper;
import im.zhaojun.common.util.DateUtils;
import im.zhaojun.system.mapper.TraffdevicewriteresultMapper;
import im.zhaojun.system.model.*;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@Service
@Slf4j
public class TraffdevicewriteresultService {

    @Autowired
    private RestTemplate restTemplate;
    @Value("${qingzhi.devicewrite.url}")
    private String url;
    @Value("${qingzhi.devicewrite.timeout}")
    private Integer timeout;


    @Autowired
    private TraffdevicewriteresultMapper traffdevicewriteresultMapper;


    /**
     * 查询分页
     */
    public List<SbtdspsrResult> querySbtdspsrResultByPage(SbtdspsrParams sbtdspsr) {
        PageHelper.startPage(sbtdspsr.getPage(), sbtdspsr.getLimit());
        return traffdevicewriteresultMapper.querySbtdspsrResultByPage(sbtdspsr);
    }
    /**
     * 查询分页
     */
    public List<Traffdevicewriteresult> queryTraffdevicewriteresultByPage(TraffdevicewriteresultParams traffdevicewriteresult) {
        PageHelper.startPage(traffdevicewriteresult.getPage(), traffdevicewriteresult.getLimit());
        Condition condition = new Condition(Traffdevicewriteresult.class);
        Example.Criteria criteria = condition.createCriteria();
        if (traffdevicewriteresult.getCreatetime() != null) {
            criteria.andEqualTo("createtime", traffdevicewriteresult.getCreatetime());
        }
        if (traffdevicewriteresult.getPushdesc() != null) {
            criteria.andEqualTo("pushdesc", traffdevicewriteresult.getPushdesc());
        }
        if (traffdevicewriteresult.getPushstatus() != null) {
            criteria.andEqualTo("pushstatus", traffdevicewriteresult.getPushstatus());
        }
        if (StringUtils.isNotBlank(traffdevicewriteresult.getSbbh())) {
            criteria.andLike("sbbh", "%" + traffdevicewriteresult.getSbbh()+"%" );
        }
        if (traffdevicewriteresult.getTdbh() != null) {
            criteria.andEqualTo("tdbh", traffdevicewriteresult.getTdbh());
        }
        if (traffdevicewriteresult.getLikePushdesc() != null) {
            criteria.andLike("pushdesc", "%" + traffdevicewriteresult.getLikePushdesc() + "%");
        }
        if (traffdevicewriteresult.getLikePushstatus() != null) {
            criteria.andLike("pushstatus", "%" + traffdevicewriteresult.getLikePushstatus() + "%");
        }
        if (StringUtils.isNotBlank(traffdevicewriteresult.getLikeSbbh())) {
            criteria.andLike("sbbh", "%" + traffdevicewriteresult.getLikeSbbh() + "%");
        }
        if (traffdevicewriteresult.getLikeTdbh() != null) {
            criteria.andLike("tdbh", "%" + traffdevicewriteresult.getLikeTdbh() + "%");
        }
        if (StringUtils.isNotBlank(traffdevicewriteresult.getCreatetimeBegin())) {
            criteria.andGreaterThanOrEqualTo("createtime", DateUtils.parseDate(traffdevicewriteresult.getCreatetimeBegin()));
        }
        if (StringUtils.isNotBlank(traffdevicewriteresult.getCreatetimeEnd())) {
            criteria.andLessThanOrEqualTo("createtime", DateUtils.parseDate(traffdevicewriteresult.getCreatetimeEnd()));
        }
        return  traffdevicewriteresultMapper.selectByCondition(condition);
    }

    /**
     * 添加
     */
    public ResultObj saveTraffdevicewriteresult(Traffdevicewriteresult traffdevicewriteresult) {
        traffdevicewriteresultMapper.insertSelective(traffdevicewriteresult);
        return ResultObj.ok();
    }

    /**
     * 批量添加
     */
    public void saveTraffdevicewriteresultList(List<Traffdevicewriteresult> traffdevicewriteresultList) {
        traffdevicewriteresultMapper.insertList(traffdevicewriteresultList);
    }

    /**
     * 更新
     */
    public void updateTraffdevicewriteresult(Traffdevicewriteresult traffdevicewriteresult) {
        traffdevicewriteresultMapper.updateByPrimaryKeySelective(traffdevicewriteresult);
    }

    /**
     * 删除
     */
    public void deleteTraffdevicewriteresult(Traffdevicewriteresult traffdevicewriteresult) {
        traffdevicewriteresultMapper.deleteByPrimaryKey(traffdevicewriteresult);
    }

    /**
     * 批量删除
     */
    public void deleteTraffdevicewriteresultList(List<Traffdevicewriteresult> traffdevicewriteresultList) {
        for (Traffdevicewriteresult traffdevicewriteresult : traffdevicewriteresultList) {
            traffdevicewriteresultMapper.deleteByPrimaryKey(traffdevicewriteresult);
        }
    }

    public ResultObj sendDevices(List<String> xhs) {
        List<SbtdspsrParams> sbtdspsrs = traffdevicewriteresultMapper.querySbtdspsrByXh(xhs);
        ResultObj resultObj;
        try {
            resultObj = sendAllMessage(sbtdspsrs);
        } catch (TimeoutException e) {
            log.error("Deviceswrite - sendDevicess 请求超时:" + e.toString());
            return ResultObj.error(ResponseEnum.E_1008.getCode(), ResponseEnum.E_1008.getMsg());
        } catch (Exception e) {
            log.error("Deviceswrite - sendDevicess 异常:" + e.toString());
            return ResultObj.error(ResponseEnum.E_9999.getCode(), e.toString());
        }
        return resultObj;
    }

    private ResultObj sendAllMessage(List<SbtdspsrParams> sbtdspsrs) throws InterruptedException, ExecutionException, TimeoutException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<List<SbtdspsrParams>> requestEntity = new HttpEntity<>(sbtdspsrs, headers);
        return CompletableFuture.supplyAsync(() -> restTemplate.postForObject(url, requestEntity, ResultObj.class)).get(timeout, TimeUnit.MILLISECONDS);
    }


}