package org.jeecg.modules.stm.base.classify.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.springframework.util.CollectionUtils;
import org.jeecg.modules.stm.base.classify.entity.StClassify;
import org.jeecg.modules.stm.base.classify.service.IStClassifyService;

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.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
 
 
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.modules.stm.base.classify.vo.ClassifyVo;

/**
 * @Description: st_classify
 * @Author: yzh
 * @Date:   2023-04-02
 * @Version: V1.0
 */

@RestController
@RequestMapping("/base.classify/stClassify")
@Slf4j
public class StClassifyController extends JeecgController<StClassify, IStClassifyService>{
	@Autowired
	private IStClassifyService stClassifyService;

	/**
	 * 分页列表查询
	 *
	 * @param stClassify
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "st_classify-分页列表查询")

	@GetMapping(value = "/rootList")
	public Result<IPage<StClassify>> queryPageList(StClassify stClassify,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		String hasQuery = req.getParameter("hasQuery");
        if(hasQuery != null && "true".equals(hasQuery)){
            QueryWrapper<StClassify> queryWrapper =  QueryGenerator.initQueryWrapper(stClassify, req.getParameterMap());
            List<StClassify> list = stClassifyService.queryTreeListNoPage(queryWrapper);
            IPage<StClassify> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        }else{
            String parentId = stClassify.getUpperClassifyCode();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            stClassify.setUpperClassifyCode(null);
            QueryWrapper<StClassify> queryWrapper = QueryGenerator.initQueryWrapper(stClassify, req.getParameterMap());
			// 特定树形查询带出一级标签处理
			if(!StringUtils.isEmpty(stClassify.getClassifyName()) || stClassify.getLevel()!=null ) {
				List<StClassify> list = stClassifyService.list(queryWrapper);
				if(!CollectionUtils.isEmpty(list)){
					List<String> upperDomainCode = list.stream().map(item-> "0".equals(item.getUpperClassifyCode())? item.getClassifyCode():
							item.getUpperClassifyCode()).distinct().collect(Collectors.toList());
					queryWrapper = new QueryWrapper<>();
					queryWrapper.in("classify_code",upperDomainCode);
				}
			}
            // 使用 eq 防止模糊查询
            queryWrapper.eq("upper_classify_code", parentId);
            Page<StClassify> page = new Page<StClassify>(pageNo, pageSize);
            IPage<StClassify> pageList = stClassifyService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
	}
	@GetMapping(value = "/listClassify")
	public Result<List<ClassifyVo>> listClassify(){
		List<ClassifyVo> classifyVos = stClassifyService.listClassify();
		return Result.OK(classifyVos);
	}
	 /**
	  * 【vue3专用】加载节点的子数据
	  *
	  * @param pid
	  * @return
	  */
	 @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
	 public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
		 Result<List<SelectTreeModel>> result = new Result<>();
		 try {
			 List<SelectTreeModel> ls = stClassifyService.queryListByPid(pid);
			 result.setResult(ls);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.setMessage(e.getMessage());
			 result.setSuccess(false);
		 }
		 return result;
	 }

	 /**
	  * 【vue3专用】加载一级节点/如果是同步 则所有数据
	  *
	  * @param async
	  * @param pcode
	  * @return
	  */
	 @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
	 public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
		 Result<List<SelectTreeModel>> result = new Result<>();
		 try {
			 List<SelectTreeModel> ls = stClassifyService.queryListByCode(pcode);
			 if (!async) {
				 loadAllChildren(ls);
			 }
			 result.setResult(ls);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.setMessage(e.getMessage());
			 result.setSuccess(false);
		 }
		 return result;
	 }

	 /**
	  * 【vue3专用】递归求子节点 同步加载用到
	  *
	  * @param ls
	  */
	 private void loadAllChildren(List<SelectTreeModel> ls) {
		 for (SelectTreeModel tsm : ls) {
			 List<SelectTreeModel> temp = stClassifyService.queryListByPid(tsm.getKey());
			 if (temp != null && temp.size() > 0) {
				 tsm.setChildren(temp);
				 loadAllChildren(temp);
			 }
		 }
	 }

	 /**
      * 获取子数据
      * @param stClassify
      * @param req
      * @return
      */
	//@AutoLog(value = "st_classify-获取子数据")

	@GetMapping(value = "/childList")
	public Result<IPage<StClassify>> queryPageList(StClassify stClassify,HttpServletRequest req) {
		QueryWrapper<StClassify> queryWrapper = QueryGenerator.initQueryWrapper(stClassify, req.getParameterMap());
		List<StClassify> list = stClassifyService.list(queryWrapper);
		IPage<StClassify> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
		return Result.OK(pageList);
	}

    /**
      * 批量查询子节点
      * @param parentIds 父ID（多个采用半角逗号分割）
      * @return 返回 IPage
      * @param parentIds
      * @return
      */
	//@AutoLog(value = "st_classify-批量获取子数据")

    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds,
									@RequestParam("level") String level,
									@RequestParam("classifyName") String classifyName) {
        try {
			QueryWrapper<StClassify> queryWrapper = new QueryWrapper<>();
			List<String> parentIdList = Arrays.asList(parentIds.split(","));
			// 去重
			List<String> distParentIdList = parentIdList.stream().distinct().collect(Collectors.toList());
			if(CollectionUtils.isEmpty(distParentIdList)){
				return Result.OK(new ArrayList<>());
			}
			queryWrapper.in("id", distParentIdList);
			List<StClassify> listids = stClassifyService.list(queryWrapper);
			// 查询子级
			QueryWrapper<StClassify> searchCodeQueryWrapper = new QueryWrapper<>();
			List<String> upperCodes = listids.stream().
					map(StClassify::getClassifyCode).distinct().collect(Collectors.toList());
			if(CollectionUtils.isEmpty(upperCodes)){
				return Result.OK(new ArrayList<>());
			}
			searchCodeQueryWrapper.in("UPPER_CLASSIFY_CODE",upperCodes);
			if(!StringUtils.isEmpty(level)){
				searchCodeQueryWrapper.eq("level",level);
			}
			if(!StringUtils.isEmpty(classifyName)){
				searchCodeQueryWrapper.like("CLASSIFY_NAME",classifyName.replace("*",""));
			}
			List<StClassify> list = stClassifyService.list(searchCodeQueryWrapper);
			IPage<StClassify> pageList = new Page<>(1, 10, list.size());
			pageList.setRecords(list);
			return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }
	
	/**
	 *   添加
	 *
	 * @param stClassify
	 * @return
	 */
	@AutoLog(value = "st_classify-添加")

    @RequiresPermissions("base.classify:st_classify:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody StClassify stClassify) {
		stClassifyService.addStClassify(stClassify);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param stClassify
	 * @return
	 */
	@AutoLog(value = "st_classify-编辑")

    @RequiresPermissions("base.classify:st_classify:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody StClassify stClassify) {
		stClassifyService.updateStClassify(stClassify);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "st_classify-通过id删除")

    @RequiresPermissions("base.classify:st_classify:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		stClassifyService.deleteStClassify(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "st_classify-批量删除")

    @RequiresPermissions("base.classify:st_classify:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.stClassifyService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "st_classify-通过id查询")

	@GetMapping(value = "/queryById")
	public Result<StClassify> queryById(@RequestParam(name="id",required=true) String id) {
		StClassify stClassify = stClassifyService.getById(id);
		if(stClassify==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(stClassify);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param stClassify
    */
    @RequiresPermissions("base.classify:st_classify:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StClassify stClassify) {
		return super.exportXls(request, stClassify, StClassify.class, "st_classify");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("base.classify:st_classify:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, StClassify.class);
    }

}
