package com.copy.trade.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copy.trade.entity.form.TagForm;
import com.copy.trade.entity.po.Tag;
import com.copy.trade.entity.vo.TagVo;
import com.copy.trade.service.ITagService;
import com.copy.trade.util.BeanCopior;
import com.copy.trade.util.WebAssert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 标签表 前端控制器
 * </p>
 *
 * @author wz
 * @since 2022-11-12
 */
@Api(value = "标签接口", tags = "标签接口")
@RestController
@RequestMapping("/tag")
public class TagController {

	ITagService tagServiceImpl;

	/**
	 * 推荐使用构造器注入
	 * @param tagServiceImpl
	 */	
	@Autowired
	TagController(ITagService tagServiceImpl) {
		this.tagServiceImpl = tagServiceImpl;
	}

	@ApiOperation(value = "标签列表")
	@GetMapping("/")
	public List<TagVo> list(){
		List<Tag> list = tagServiceImpl.list();
		List<TagVo> tagVoList = BeanCopior.mapList(list, TagVo.class);
		return tagVoList;
	}

	@ApiOperation(value="添加标签")
	@ApiImplicitParam(name="tagForm",value = "标签表单",dataType = "TagForm")
	@PostMapping("/add")
	public Boolean add(@RequestBody @Valid TagForm tagForm){
		QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();
		tagQueryWrapper.eq("name",tagForm.getName());
		Tag tag = tagServiceImpl.getOne(tagQueryWrapper);
		WebAssert.isNull(tag,"标签已存在");
		tag = new Tag();
		tag.setName(tagForm.getName());
		tag.setEnName(tagForm.getEnName());
		return tagServiceImpl.save(tag);
	}
	
	@ApiOperation(value="修改标签")
	@ApiImplicitParam(name="tagForm",value = "标签表单",dataType = "TagForm")
	@PostMapping("/update")
	public Boolean update(@RequestBody @Valid TagForm tagForm){
		Tag tag = tagServiceImpl.getById(tagForm.getId());
		tag.setName(tagForm.getName());
		tag.setEnName(tagForm.getEnName());
		return tagServiceImpl.updateById(tag);
	}
	
	@ApiOperation(value="删除标签")
	@PutMapping("/delete/{id}")
	public Boolean delete(@PathVariable Long id){
		return tagServiceImpl.removeById(id);
	}
}
