package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.entity.TagCategoryInfo;
import cn.com.ctop.common.module.entity.TagInfo;
import cn.com.ctop.common.module.model.TagInfoTreeModel;
import cn.com.ctop.common.module.service.ITagCategoryInfoService;
import cn.com.ctop.common.module.service.ITagInfoService;
import cn.com.ctop.common.module.utils.QueryGenerator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.model.TagInfoTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

 /**
 * 标签信息
 * @author jeecg-boot
 * @date   2020-08-26
 * @version V1.0
 */
@Slf4j
@RestController
@RequestMapping("/ctop/tagInfo")
public class TagInfoController {
	@Autowired
	private ITagInfoService tagInfoService;

	 /**
	  * 加载数据节点
	  *
	  * @return
	  */
	 @RequestMapping(value = "/treeList", method = RequestMethod.GET)
	 public Result<IPage<TagInfo>> list(@RequestParam (required = false)String tagName,@RequestParam(defaultValue = "10")Integer pageSize,@RequestParam(defaultValue = "1")Integer pageNo,@RequestParam(required = false)Long tagCategoryId,@RequestParam(defaultValue = "1")Integer level) {
		 Result<IPage<TagInfo>> result = new Result<>();
		 try {
		 	QueryWrapper<TagInfo> query = new QueryWrapper<>();
		 	query.eq("del_flag", CommonConstant.DEL_FLAG_0);
		 	if(null!=level){
				query.eq("level",level);
			}
		 	if(null!=tagCategoryId){
		 		query.eq("tag_category_id",tagCategoryId);
		 	}
			 if(null!=tagName&&!"".equals(tagName)){
				 query.like("tag_name",tagName);
			 }
		 	query.orderByAsc("tag_order");
		 	Page<TagInfo> page = new Page<>(pageNo, pageSize);
		 	IPage<TagInfo> pageList = tagInfoService.page(page,query);
		 	List<TagInfo>recordsLevel1 = pageList.getRecords();

		 	List<TagInfo>setRecordsLevel1 = new ArrayList<>();
		 	if(null!=recordsLevel1&&!recordsLevel1.isEmpty()){
		 		for (TagInfo level1tag:recordsLevel1) {
					if(!level1tag.isLeaf()){
						//非叶子节点
						List<TagInfo>recordsLevel2 = tagInfoService.getByParentId(level1tag.getId());
						List<TagInfo>setRecordsLevel2 = new ArrayList<>();
						if(null!=recordsLevel2&&!recordsLevel2.isEmpty()){
							for(TagInfo level2Tag:recordsLevel2){
								if(!level2Tag.isLeaf()){
									List<TagInfo>recordsLevel3 = tagInfoService.getByParentId(level2Tag.getId());
									level2Tag.setChildren(recordsLevel3);
								}
								setRecordsLevel2.add(level2Tag);
							}
						}
						level1tag.setChildren(setRecordsLevel2);
					}
					setRecordsLevel1.add(level1tag);
				}
			}
			pageList.setRecords(setRecordsLevel1);
		 	result.setSuccess(true);
		 	result.setResult(pageList);
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
		 }
		 return result;
	 }

	 private void getTreeList(List<TagInfoTree> treeList, List<TagInfo> metaList, TagInfoTree temp) {
		 for (TagInfo tagInfo : metaList) {
			 Long tempPid = tagInfo.getParentId();
			 TagInfoTree tree = new TagInfoTree(tagInfo);
			 if (temp == null && oConvertUtils.isEmpty(tempPid)) {
				 treeList.add(tree);
				 if (!tree.isLeaf()) {
					 getTreeList(treeList, metaList, tree);
				 }
			 } else if (temp != null && tempPid != null && tempPid.equals(temp.getId())) {
				 temp.getChildren().add(tree);
				 if (!tree.isLeaf()) {
					 getTreeList(treeList, metaList, tree);
				 }
			 }

		 }
	 }

	/**
	  * 分页列表查询
	 * @param tagInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<TagInfo>> queryPageList(TagInfo tagInfo, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="100") Integer pageSize,
												HttpServletRequest req) {
		Result<IPage<TagInfo>> result = new Result<>();
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		QueryWrapper<TagInfo> queryWrapper = QueryGenerator.initQueryWrapper(tagInfo, req.getParameterMap());
		Page<TagInfo> page = new Page<>(pageNo, pageSize);
		queryWrapper.eq("del_flag",0);
		IPage<TagInfo> pageList = tagInfoService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	@Autowired
	private ITagCategoryInfoService tagCategoryInfoService;
	@PostMapping(value = "/add")
	public Result<TagInfo> add(@RequestBody TagInfo tagInfo) {
		Result<TagInfo> result = new Result<>();
		try {
			TagCategoryInfo categoryInfo = tagCategoryInfoService.getById(tagInfo.getTagCategoryId());
			if(null!=categoryInfo){
				tagInfo.setTagCategoryName(categoryInfo.getName());
			}
			TagInfo getTag = tagInfoService.getByTagCode(tagInfo.getTagCode());
			if(null!=getTag){
				result.error500("标签编码已存在");
				return result;
			}
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			tagInfo.setDelFlag(0);
			if(null == tagInfo.getStatus()){
				tagInfo.setStatus(1);
			}
			tagInfo.setUserId(user.getId());

			int level = 1;
			Long parentId = tagInfo.getParentId();
			if(null!=parentId){
				TagInfo parentTag = tagInfoService.getById(parentId);
				if(null == parentTag){
					result.error500("父级标签不存在");
					return result;
				}
				String tagCode = parentTag.getTagCode()+tagInfo.getTagCode();
				TagInfo getTag2 = tagInfoService.getByTagCode(tagCode);
				if(null!=getTag2){
					result.error500("标签编码已存在");
					return result;
				}
				tagInfo.setTagCategoryId(parentTag.getTagCategoryId());
				if(parentTag.getLevel() == 1){
					tagInfo.setFirstTagId(parentTag.getId());
				}
				if(parentTag.getLevel() == 2){
					tagInfo.setSecendTagId(parentTag.getId());
					tagInfo.setFirstTagId(parentTag.getParentId());
				}
				level = parentTag.getLevel()+1;
				tagInfo.setTagCode(tagCode);
			}
			tagInfo.setLevel(level);
			tagInfoService.save(tagInfo);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	  *  编辑
	 * @param tagInfo
	 * @return
	 */
	@PostMapping("/edit")
	public Result<TagInfo> edit(@RequestBody TagInfo tagInfo) {
		Result<TagInfo> result = new Result<>();
		TagInfo tagInfoEntity = tagInfoService.getById(tagInfo.getId());
		if(tagInfoEntity==null) {
			result.error500("未找到对应实体");
		}else {
			tagInfo.setUpdateTime(new Date());
			boolean ok = tagInfoService.updateById(tagInfo);
			if(ok) {
				result.success("修改成功!");
			}
		}

		return result;
	}

	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<TagInfo> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<TagInfo> result = new Result<>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.tagInfoService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<TagInfo> queryById(@RequestParam(name="id",required=true) String id) {
		Result<TagInfo> result = new Result<>();
		TagInfo tagInfo = tagInfoService.getById(id);
		if(tagInfo==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(tagInfo);
			result.setSuccess(true);
		}
		return result;
	}

	@RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
    public Result<List<TagInfoTreeModel>> queryTreeList(@RequestParam(name = "categoryId",defaultValue = "0")Long categoryId) {
	    Result<List<TagInfoTreeModel>> result = new Result<>();
	    try {
			LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<TagInfoTreeModel> list = tagInfoService.queryTreeList(user.getId(),categoryId);
	        result.setResult(list);
	        result.setSuccess(true);
	    } catch (Exception e) {
	        log.error(e.getMessage(),e);
	    }
	    return result;
	}
}
