package com.dtok.api.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.dtok.entity.Account;
import com.dtok.entity.CommonItem;
import com.dtok.entity.LoginHistory;
import com.dtok.framework.exception.AuthenticateException;
import com.dtok.framework.exception.BizExceptionEnum;
import com.dtok.framework.response.ResponseData;
import com.dtok.framework.util.ToolUtil;
import com.dtok.repository.CommonItemRepository;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/commonItem")
public class CommonItemController {

    @Autowired
    CommonItemRepository commonItemRepository;

    @GetMapping("/search")
    public ResponseData search(@RequestParam("app") String app, @RequestParam("content") String content, @RequestParam("type") String type) {
        Specification<CommonItem> query = (root, query1, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            if (ToolUtil.isNotEmpty(app)) {
                predicate.getExpressions().add(criteriaBuilder.or(criteriaBuilder.equal(root.get("app"), app)));
            }
            if (ToolUtil.isNotEmpty(content)) {
                predicate.getExpressions().add(criteriaBuilder.or(criteriaBuilder.like(root.get("content"), "%" + content + "%")));
            }
            if (ToolUtil.isNotEmpty(type)) {
                predicate.getExpressions().add(criteriaBuilder.or(criteriaBuilder.like(root.get("type"), "%" + type + "%")));
            }
            predicate.getExpressions().add(criteriaBuilder.and(criteriaBuilder.equal(root.get("isDefault"), true)));

            predicate.getExpressions().add(criteriaBuilder.and(criteriaBuilder.equal(root.get("createdAt"), ((Account) StpUtil.getSession().get("loginUser")).getId())));

            return predicate;
        };
        List<CommonItem> result = commonItemRepository.findAll(query);
        return ResponseData.success(result);
    }


    @PostMapping("/add")
    public ResponseData search(CommonItem commonItem) {
        if (Objects.isNull(commonItem)) {
            throw new NullPointerException("对象不存在");
        }
        if (!StringUtils.hasLength(commonItem.getContent()) || !StringUtils.hasLength(commonItem.getApp()) || !StringUtils.hasLength(commonItem.getType())) {
            throw new NullPointerException("属性缺省");
        }
        if (!((Account) StpUtil.getSession().get("loginUser")).getIsSuper() && commonItem.getIsDefault()) {
            throw new AuthenticateException(BizExceptionEnum.NO_PERMISSION);
        }

        commonItem.setCreatedAt(((Account) StpUtil.getSession().get("loginUser")).getId());
        commonItem.setCreatedTime(new Date());
        commonItemRepository.save(commonItem);
        return ResponseData.success("添加成功");
    }

    @PostMapping("/update/{id}")
    public ResponseData update(CommonItem commonItem, @PathVariable Integer id) {
        if (Objects.isNull(id)) {
            throw new NullPointerException("对象不存在");
        }

        if (Objects.isNull(commonItem)) {
            throw new NullPointerException("对象不存在");
        }
        if (!StringUtils.hasLength(commonItem.getContent()) || !StringUtils.hasLength(commonItem.getApp()) || !StringUtils.hasLength(commonItem.getType())) {
            throw new NullPointerException("属性缺省");
        }
        if (!((Account) StpUtil.getSession().get("loginUser")).getIsSuper() && commonItem.getIsDefault()) {
            throw new AuthenticateException(BizExceptionEnum.NO_PERMISSION);
        }

        commonItem.setId(Long.valueOf(id));
        commonItem.setCreatedAt(((Account) StpUtil.getSession().get("loginUser")).getId());
        commonItem.setCreatedTime(new Date());
        commonItemRepository.save(commonItem);
        return ResponseData.success("添加成功");
    }

    @PostMapping("/delete/{id}")
    public ResponseData delete(CommonItem commonItem, @PathVariable Integer id) {
        if (Objects.isNull(commonItem)) {
            throw new NullPointerException("对象不存在");
        }
        if (!StringUtils.hasLength(commonItem.getContent()) || !StringUtils.hasLength(commonItem.getApp()) || !StringUtils.hasLength(commonItem.getType())) {
            throw new NullPointerException("属性缺省");
        }

        if (Objects.isNull(id)) {
            throw new NullPointerException("对象不存在");
        }

        CommonItem commonItemAlready = commonItemRepository.getOne(String.valueOf(id));

        if (!((Account) StpUtil.getSession().get("loginUser")).getIsSuper() && commonItemAlready.getIsDefault()) {
            throw new AuthenticateException(BizExceptionEnum.NO_PERMISSION);
        }

        commonItemRepository.delete(commonItemAlready);
        return ResponseData.success("添加成功");
    }

}
