package org.jeecg.modules.stm.rectify.assin.controller;

import java.io.Serializable;
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.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
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.rectify.assin.entity.StProblemTaskAssin;
import org.jeecg.modules.stm.rectify.assin.service.IStProblemTaskAssinService;

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.rectify.assin.vo.BatchFpVo;
import org.jeecg.modules.stm.rectify.assin.vo.ProjectImportAssinVo;
import org.jeecg.modules.stm.utils.UserUtil;

/**
 * @Description: 任务分配
 * @Author: jeecg-boot
 * @Date:   2023-07-21
 * @Version: V1.0
 */
  
@RestController
@RequestMapping("/rectify.assin/stProblemTaskAssin")
@Slf4j
public class StProblemTaskAssinController extends JeecgController<StProblemTaskAssin, IStProblemTaskAssinService>{
	@Autowired
	private IStProblemTaskAssinService stProblemTaskAssinService;

	/**
	 * 分页列表查询
	 *
	 * @param stProblemTaskAssin
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "任务分配-分页列表查询")
	  
	@GetMapping(value = "/rootList")
	public Result<IPage<StProblemTaskAssin>> queryPageList(StProblemTaskAssin stProblemTaskAssin,
								   @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<StProblemTaskAssin> queryWrapper =  QueryGenerator.initQueryWrapper(stProblemTaskAssin, req.getParameterMap());
            String userCode = UserUtil.getUserCode();
            queryWrapper.and(wrapper->wrapper.eq("CREATED_USER",userCode).or().eq("HEAD_CODE",userCode));
            List<StProblemTaskAssin> list = stProblemTaskAssinService.queryTreeListNoPage(queryWrapper);
            IPage<StProblemTaskAssin> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        }else{
            String parentId = stProblemTaskAssin.getPid().toString();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            stProblemTaskAssin.setPid(null);
            QueryWrapper<StProblemTaskAssin> queryWrapper = QueryGenerator.initQueryWrapper(stProblemTaskAssin, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
			String userCode = UserUtil.getUserCode();
			queryWrapper.and(wrapper->wrapper.eq("CREATED_USER",userCode).or().eq("HEAD_CODE",userCode));

			QueryWrapper<StProblemTaskAssin> queryWrapperChild = QueryGenerator.initQueryWrapper(stProblemTaskAssin, req.getParameterMap());
			queryWrapperChild.select("pid").ne("pid","0").and(wrapper->wrapper.eq("CREATED_USER",userCode).or().eq("HEAD_CODE",userCode));
			List<StProblemTaskAssin> stProblemTaskAssinList =  stProblemTaskAssinService.list(queryWrapperChild);
			if(!CollectionUtils.isEmpty(stProblemTaskAssinList)){
				List<Serializable> ids = stProblemTaskAssinList.stream().map(StProblemTaskAssin::getPid).collect(Collectors.toList());
				queryWrapper.or(wrapper -> wrapper.in("id",ids));
			}
			Page<StProblemTaskAssin> page = new Page<StProblemTaskAssin>(pageNo, pageSize);
            IPage<StProblemTaskAssin> pageList = stProblemTaskAssinService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
	}

	 /**
	  * 【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 = stProblemTaskAssinService.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 = stProblemTaskAssinService.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 = stProblemTaskAssinService.queryListByPid(tsm.getKey());
			 if (temp != null && temp.size() > 0) {
				 tsm.setChildren(temp);
				 loadAllChildren(temp);
			 }
		 }
	 }

	 /**
      * 获取子数据
      * @param stProblemTaskAssin
      * @param req
      * @return
      */
	//@AutoLog(value = "任务分配-获取子数据")
	  
	@GetMapping(value = "/childList")
	public Result<IPage<StProblemTaskAssin>> queryPageList(StProblemTaskAssin stProblemTaskAssin,HttpServletRequest req) {
		QueryWrapper<StProblemTaskAssin> queryWrapper = QueryGenerator.initQueryWrapper(stProblemTaskAssin, req.getParameterMap());
		String userCode = UserUtil.getUserCode();
		queryWrapper.and(wrapper->wrapper.eq("CREATED_USER",userCode).or().eq("HEAD_CODE",userCode));
		List<StProblemTaskAssin> list = stProblemTaskAssinService.list(queryWrapper);
		IPage<StProblemTaskAssin> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
		return Result.OK(pageList);
	}

    /**
      * 批量查询子节点
      * @param parentIds 父ID（多个采用半角逗号分割）
      * @return 返回 IPage
      * @param parentIds
      * @return
      */
	//@AutoLog(value = "任务分配-批量获取子数据")
      
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<StProblemTaskAssin> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<StProblemTaskAssin> list = stProblemTaskAssinService.list(queryWrapper);
            IPage<StProblemTaskAssin> 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 stProblemTaskAssin
	 * @return
	 */
	@AutoLog(value = "任务分配-添加")
	  
    @RequiresPermissions("rectify.assin:st_problem_task_assin:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody StProblemTaskAssin stProblemTaskAssin) {
		stProblemTaskAssinService.addStProblemTaskAssin(stProblemTaskAssin);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param stProblemTaskAssin
	 * @return
	 */
	@AutoLog(value = "任务分配-编辑")
	  
    @RequiresPermissions("rectify.assin:st_problem_task_assin:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody StProblemTaskAssin stProblemTaskAssin) {
		stProblemTaskAssinService.updateStProblemTaskAssin(stProblemTaskAssin);
		return Result.OK("编辑成功!");
	}

	@AutoLog(value = "任务分配-编辑")
	  
	@RequiresPermissions("rectify.assin:st_problem_task_assin:edit")
	@RequestMapping(value = "/editFp", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editFp(@RequestBody StProblemTaskAssin stProblemTaskAssin) {
		if(StringUtils.isEmpty(stProblemTaskAssin.getSeverity())){
			throw new JeecgBootException("请修改选择严重程度");
		}
		if(StringUtils.isEmpty(stProblemTaskAssin.getPriorityFlag())){
			throw new JeecgBootException("请修改选择优先级");
		}
		if(ObjectUtils.isEmpty(stProblemTaskAssin.getLateFinishTime())){
			throw new JeecgBootException("请修改选择最晚完成时间");
		}
		stProblemTaskAssinService.updateStProblemTaskAssin(stProblemTaskAssin);
		return Result.OK("编辑成功!");
	}

	@AutoLog(value = "任务分配-编辑")
	  
	@RequiresPermissions("rectify.assin:st_problem_task_assin:edit")
	@RequestMapping(value = "/batchEditFp", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> batchEditFp(@RequestBody BatchFpVo batchFpVo) {
		stProblemTaskAssinService.batchEditFp(batchFpVo);
		return Result.OK("批量分配成功!");
	}

	@AutoLog(value = "任务分配-编辑")
	@RequestMapping(value = "/importProblemAssin", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> importProblemAssin(@RequestBody List<Serializable> ids) {
		stProblemTaskAssinService.importProblemAssin(ids);
		return Result.OK("问题导入成功!");
	}

	@AutoLog(value = "任务分配-项目导入")
	@PostMapping(value = "/projectImport")
	public Result<String> projectImport(@RequestBody ProjectImportAssinVo projectImportAssinVo) {
		stProblemTaskAssinService.projectImport(projectImportAssinVo);
		return Result.OK("项目导入成功！");
	}


	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务分配-通过id删除")
	  
    @RequiresPermissions("rectify.assin:st_problem_task_assin:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		stProblemTaskAssinService.deleteStProblemTaskAssin(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务分配-批量删除")
	  
    @RequiresPermissions("rectify.assin:st_problem_task_assin:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.stProblemTaskAssinService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "任务分配-通过id查询")
	  
	@GetMapping(value = "/queryById")
	public Result<StProblemTaskAssin> queryById(@RequestParam(name="id",required=true) String id) {
		StProblemTaskAssin stProblemTaskAssin = stProblemTaskAssinService.getById(id);
		if(stProblemTaskAssin==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(stProblemTaskAssin);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param stProblemTaskAssin
    */
    @RequiresPermissions("rectify.assin:st_problem_task_assin:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StProblemTaskAssin stProblemTaskAssin) {
		return super.exportXls(request, stProblemTaskAssin, StProblemTaskAssin.class, "任务分配");
    }

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

}
