package fastweb.controller;

import fastweb.domain.dataagent.Artical;
import fastweb.domain.system.WrapperResult;
import fastweb.domain.usertype.User;
import fastweb.respository.dataagent.ArticalRepository;
import fastweb.service.IEmailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api")
public class ApiController {
    @Autowired
    private ArticalRepository articalRepository;

    @RequestMapping("/list")
    private WrapperResult list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "limit", defaultValue = "20") Integer limit,
                               @RequestParam(value = "name",required = false)String name) {
        try {
            Sort sort = new Sort(Sort.Direction.DESC, "id");
            Pageable pageable = new PageRequest(page - 1, limit, sort);
            Specification<Artical> specification = (root, query, cb) -> {
                List<Predicate> preList = new ArrayList<Predicate>();
                if(!StringUtils.isEmpty(name)) {
                    Predicate predicate = cb.like(root.get("account"),"%" + name+"%");
                    preList.add(predicate);
                }
                query.where(preList.toArray(new Predicate[preList.size()]));
                return null;
            };
            Page<Artical> contents = articalRepository.findAll(specification,pageable);
            return WrapperResult.successWrapedResult(contents);
        } catch (Exception e) {
            return WrapperResult.failedWrappedResult(e.getMessage());
        }
    }
    @GetMapping("/listAll")
    private WrapperResult listAll(@RequestParam(value = "type", required = false) Integer type) {
        try {
            Specification<Artical> specification = new Specification<Artical>() {
                @Override
                public Predicate toPredicate(Root<Artical> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    List<Predicate> preList = new ArrayList<Predicate>();
                    if (type!= null) {
                        Predicate predicate = cb.equal(root.get("type"),  type);
                        preList.add(predicate);
                    }
                    query.where(preList.toArray(new Predicate[preList.size()]));
                    return null;
                }
            };
            return WrapperResult.successWrapedResult(articalRepository.findAll(specification));
        } catch (Exception e) {
            return WrapperResult.failedWrappedResult(e.getMessage());
        }
    }

    @PostMapping("/saveorupdate")
    private WrapperResult saveOrUpdate(@RequestBody Artical artical) {
        try {
            if (StringUtils.isEmpty(artical.getId())) {
                artical.setDate(new Date(System.currentTimeMillis()));
                Artical contentNew = articalRepository.save(artical);
                return WrapperResult.successWrapedResult(contentNew);
            } else {
                Optional<Artical> contentOld = articalRepository.findById(artical.getId());
                if (contentOld.isPresent()) {
                    BeanUtils.copyProperties(artical, contentOld.get(), "date");
                    articalRepository.save(contentOld.get());
                }
                return WrapperResult.successWrapedResult(contentOld.get());
            }
        } catch (Exception e) {
            return WrapperResult.failedWrappedResult(e.getMessage());
        }
    }

    @GetMapping("/detail")
    private WrapperResult get(@PathVariable String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return WrapperResult.failedWrappedResult("id不能为空");
            }
            Artical content = articalRepository.getOne(id);
            return WrapperResult.successWrapedResult(content);
        } catch (Exception e) {
            return WrapperResult.failedWrappedResult(e.getMessage());
        }
    }

    @GetMapping("/getarticle")
    private WrapperResult getarticle(@RequestParam(value = "id") String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return WrapperResult.failedWrappedResult("id不能为空");
            }
            Artical content = articalRepository.getOne(id);
            return WrapperResult.successWrapedResult(content);
        } catch (Exception e) {
            return WrapperResult.failedWrappedResult(e.getMessage());
        }
    }


}
