package me.qwq.doghouse.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.qwq.doghouse.config.DoghouseProperties;
import me.qwq.doghouse.controller.common.BaseController;
import me.qwq.doghouse.entity.Link;
import me.qwq.doghouse.exception.RException;
import me.qwq.doghouse.pojo.dto.LayPageReq;
import me.qwq.doghouse.pojo.dto.LayPageResp;
import me.qwq.doghouse.pojo.dto.R;
import me.qwq.doghouse.service.LinkService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.Objects;


/**
 * 友链控制器
 * @author Doghole
 */
@Controller
@RequestMapping("/admin/v2/link")
public class LinkController extends BaseController {

    @Autowired
    DoghouseProperties doghouseProperties;
    
    @Autowired
    LinkService linkService;

    /**
     * 主页
     * @return
     */
    @GetMapping({"", "/", "/index"})
    String index() {
        return "admin/link/index";
    }
    
    @ResponseBody
    @GetMapping("/list")
    public LayPageResp<?> getLinkList(LayPageReq<Link> pageReq) {
        
        LambdaQueryWrapper<Link> ew = new LambdaQueryWrapper<Link>()
                .eq(Link::getIsDeleted, false)
                .orderByDesc(Link::getHealth, Link::getCreateTime);
        
        IPage<Link> page = linkService.page(pageReq, ew);
        LayPageResp<Link> result = new LayPageResp<>(page);
        return result;
    }
    
    
    /**
     * 更新文件基本信息
     * @param asset
     * @return
     */
    @ResponseBody
    @PostMapping("/update")
    R<?> update(Link link) {
        if (linkService.saveOrUpdate(link)) {
            return R.ok();
        }
        throw RException.internalServerError("保存失败");
    }
    
    /**
     * 删除文件
     * @param assetId
     * @return
     */
    @ResponseBody
    @PostMapping("/delete")
    R<?> delete(Long id) {
        if (Objects.isNull(id)) {
            throw RException.badRequest("友链 ID 不允许为空！");
        }
        if (linkService.update(new LambdaUpdateWrapper<Link>()
                .eq(Link::getId, id)
                .set(Link::getIsDeleted, true))) {
            return R.ok();
        }
        throw RException.internalServerError("删除友链失败");
    }
    
}
