package com.zjty.autotest.service.impl;

import com.alibaba.fastjson.JSON;
import com.zjty.autotest.dao.AutoResultSetDao;
import com.zjty.autotest.mq.CacheManager;
import com.zjty.autotest.mq.PushBlockQueue;
import com.zjty.autotest.mq.QueueManager;
import com.zjty.autotest.pojo.sjq.AutoResultSet;
import com.zjty.autotest.pojo.sjq.TestChannel;
import com.zjty.autotest.pojo.sjq.TestReport;
import com.zjty.autotest.pojo.sjq.common.AppHttpCodeEnum;
import com.zjty.autotest.pojo.sjq.common.ResponseResult;
import com.zjty.autotest.service.AsyncService;
import com.zjty.autotest.service.AutoResultSetService;
import com.zjty.autotest.service.TestReportService;
import com.zjty.autotest.util.IdWorker;
import com.zjty.autotest.util.TimeUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AutoResultSetServiceImpl implements AutoResultSetService {
    @Autowired
    private AutoResultSetDao autoResultSetDao;
    @Autowired
    private TestReportService testReportService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private AsyncService asyncService;
    @Override
    public Page<AutoResultSet> findSearch(Map whereMap, int page, int size) {
        Specification<AutoResultSet> specification = createSpecification(whereMap);
        PageRequest pageRequest =  PageRequest.of(page-1, size, Sort.Direction.DESC,"createTime");
        return autoResultSetDao.findAll(specification, pageRequest);
    }
    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    private Specification<AutoResultSet> createSpecification(Map searchMap) {

        return new Specification<AutoResultSet>() {

            @Override
            public Predicate toPredicate(Root<AutoResultSet> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                if (searchMap.get("projectName") != null && !"".equals(searchMap.get("projectName"))) {
                    predicateList.add(cb.like(root.get("projectName").as(String.class), "%" + (String) searchMap.get("projectName") + "%"));
                }
                return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }


    @Override
    public ResponseResult deleteByid(String id) {
        try {
            autoResultSetDao.deleteById(id);
            testReportService.deleteByResultId(id);
        }catch (Exception e){
            return ResponseResult.okResult(AppHttpCodeEnum.SAVE_ERROR);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateByid(String id) {
        int i = autoResultSetDao.updateStatus(id);
        if(i==1){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_ERROR);
    }

    @Override
    public ResponseResult addResultSet(TestChannel testChannel) {
        String tid=idWorker.nextId()+"";
        AutoResultSet autoResultSet=new AutoResultSet();
        autoResultSet.setId(tid);
        autoResultSet.setProjectName(testChannel.getName());
        autoResultSet.setUser(testChannel.getUser());
        autoResultSet.setCreateTime(new Date());
        autoResultSet.setUpdateTime(new Date());
        autoResultSet.setStatus(0);
        AutoResultSet save = autoResultSetDao.save(autoResultSet);

        CacheManager.putCache(tid,testChannel);
        //将数据保存到队列
        try {
            asyncService.executeAsync(tid);
//            PushBlockQueue pushBlockQueue=new PushBlockQueue(autoResultSetDao,testReportService);
//            QueueManager.put(tid);
            return ResponseResult.okResult(save);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,e.getMessage());
        }

    }
}
