package me.qwq.doghouse.controller.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.yulichang.wrapper.MPJLambdaWrapper;

import jakarta.validation.Valid;
import me.qwq.doghouse.controller.common.BaseController;
import me.qwq.doghouse.entity.Meta;
import me.qwq.doghouse.entity.Tag;
import me.qwq.doghouse.enums.MetaTypeEnum;
import me.qwq.doghouse.exception.RException;
import me.qwq.doghouse.pojo.dto.R;
import me.qwq.doghouse.service.MetaService;

@Controller
@RequestMapping("/admin/v2/tag")
public class TagController extends BaseController {
    
    @Autowired
    MetaService metaService;
    
    @GetMapping({"", "/"})
    private String index() {
        request.setAttribute("title", "标签管理");
        return "admin/tag/index";
    }
    
    /**
     * 提供建议的 Tag，一般用于输入提示
     * @param input
     * @return
     */
    @GetMapping("/suggest")
    @ResponseBody
    private List<Tag> suggest(String input){
        List<Tag> list = new ArrayList<>();
        if (StringUtils.isBlank(input)) return list;
        list = metaService.listJoin(Tag.class, new MPJLambdaWrapper<Tag>(Tag.class)
                .selectAll(Tag.class)
                .eq(Tag::getType, MetaTypeEnum.TAG)
                .nested(i -> i
                        .like(Tag::getName, input).or()
                        .like(Tag::getFriendlyName, input))
                .last(" LIMIT 5"));
        return list;
    }
    

    /**
     * 新增或编辑分类
     * @param id
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    private R<?> update(@Valid Tag tag, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new RException(HttpStatus.BAD_REQUEST, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if (tag == null) {
            throw new RException(HttpStatus.BAD_REQUEST, "分类不允许为空");
        }
        if (StringUtils.isEmpty(tag.getFriendlyName())) {
            tag.setFriendlyName(tag.getName().toLowerCase(Locale.ENGLISH));
        }
        // 查询友好名称是否重复
        long count = metaService.count(new MPJLambdaWrapper<Meta>()
                .eq(Meta::getType, MetaTypeEnum.TAG)
                .eq(Meta::getFriendlyName, tag.getFriendlyName()));
        if (count >= 1) {
            if (tag.getMid() == null) {
                throw new RException(HttpStatus.BAD_REQUEST, "友好名称与其他标签重复");
            }
            else {
                Tag existTag = metaService.getOneJoin(Tag.class,
                        new MPJLambdaWrapper<Tag>(Tag.class).eq(Tag::getFriendlyName, tag.getFriendlyName()));
                if (!existTag.getMid().equals(tag.getMid())) {
                    throw new RException(HttpStatus.BAD_REQUEST, "友好名称与其他标签重复");
                }
            }
        }
        if(metaService.saveOrUpdate(tag)) {
            return R.ok();
        }
        throw new RException(HttpStatus.BAD_REQUEST);
    }

    /**
     * 删除指定 id 的分类
     * @param id
     * @return
     */
    @PostMapping("/deleteUnusedTags")
    @ResponseBody
    private R<?> deleteUnusedTags() {
        metaService.removeUnusedTags();
        return R.ok();
    }
    /**
     * 删除指定 id 的分类
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    private R<?> delete(Long id) {
        metaService.removeById(id);
        return R.ok();
    }

}
