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.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.AutoResultSetService;
import com.zjty.autotest.service.TestReportService;
import com.zjty.autotest.util.IdWorker;
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.*;

@Service
public class AutoResultSetServiceImpl implements AutoResultSetService {
    @Autowired
    private AutoResultSetDao autoResultSetDao;
    @Autowired
    private TestReportService testReportService;
    @Autowired
    private IdWorker idWorker;
    @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,Integer status) {
        Optional<AutoResultSet> optional = autoResultSetDao.findById(id);
        if(optional.isPresent()){
            AutoResultSet autoResultSet = optional.get();
            autoResultSet.setStatus(status);
            autoResultSet.setUpdateTime(new Date());
            autoResultSetDao.save(autoResultSet);
            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);
        String in = JSON.toJSONString(testChannel);
        TestReport testReport = new TestReport();
        testReport.setId(idWorker.nextId()+"");
        testReport.setResultId(tid);
        testReport.setStatus(0);
        testReport.setInputReport(in);
        testReportService.save(testReport);
        CacheManager.putCache(tid,testChannel);
        //将数据保存到队列
        try {
            QueueManager.put(tid);
            return ResponseResult.okResult(save);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,e.getMessage());
        }

    }
}
