package org.jeecg.modules.stm.baosong.controller;

import java.util.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.stm.baosong.entity.*;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskAllocService;

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.baosong.service.IBaosongTaskService;
import org.jeecg.modules.stm.baosong.service.IBaosongTplItemService;
import org.jeecg.modules.stm.utils.UserUtil;

/**
 * @Description: 任务分配
 * @Author: jeecg-boot
 * @Date:   2024-12-17
 * @Version: V1.0
 */
  
@RestController
@RequestMapping("/baosong/baosongTaskAlloc")
@Slf4j
public class BaosongTaskAllocController extends JeecgController<BaosongTaskAlloc, IBaosongTaskAllocService> {
	@Autowired
	private IBaosongTaskAllocService baosongTaskAllocService;
	@Autowired
	private IBaosongTplItemService baosongTplItemService;
	@Autowired
	private IBaosongTaskService baosongTaskService;
	/**
	 * 分页列表查询
	 *
	 * @param baosongTaskAlloc
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "任务分配-分页列表查询")
	  
	@GetMapping(value = "/list")
	public Result<IPage<BaosongTaskAlloc>> queryPageList(BaosongTaskAlloc baosongTaskAlloc,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BaosongTaskAlloc> queryWrapper = QueryGenerator.initQueryWrapper(baosongTaskAlloc, req.getParameterMap());
		Page<BaosongTaskAlloc> page = new Page<BaosongTaskAlloc>(pageNo, pageSize);
		IPage<BaosongTaskAlloc> pageList = baosongTaskAllocService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/queryAllTaskAlloc")
	 public Result<List<Map<String,Object>>> queryAllTaskAlloc(BaosongTaskAlloc alloc, HttpServletRequest req) {
		 List<Map<String,Object>> list = baosongTaskAllocService.queryAllTaskAlloc(alloc);
		 return Result.OK(list);
	 }
	
	/**
	 *   添加
	 *
	 * @param baosongTaskAlloc
	 * @return
	 */
	@AutoLog(value = "任务分配-添加")
	  
	@RequiresPermissions("baosong:baosong_task_alloc:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BaosongTaskAlloc baosongTaskAlloc) {
		baosongTaskAllocService.save(baosongTaskAlloc);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param baosongTaskAlloc
	 * @return
	 */
	@AutoLog(value = "任务分配-编辑")
	  
	@RequiresPermissions("baosong:baosong_task_alloc:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BaosongTaskAlloc baosongTaskAlloc) {
		baosongTaskAllocService.updateById(baosongTaskAlloc);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务分配-通过id删除")
	  
	@RequiresPermissions("baosong:baosong_task_alloc:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		baosongTaskAllocService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务分配-批量删除")
	  
	@RequiresPermissions("baosong:baosong_task_alloc:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.baosongTaskAllocService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "任务分配-通过id查询")
	  
	@GetMapping(value = "/queryById")
	public Result<BaosongTaskAlloc> queryById(@RequestParam(name="id",required=true) String id) {
		BaosongTaskAlloc baosongTaskAlloc = baosongTaskAllocService.getById(id);
		if(baosongTaskAlloc==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(baosongTaskAlloc);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param baosongTaskAlloc
    */
    @RequiresPermissions("baosong:baosong_task_alloc:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BaosongTaskAlloc baosongTaskAlloc) {
        return super.exportXls(request, baosongTaskAlloc, BaosongTaskAlloc.class, "任务分配");
    }

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

	 @PostMapping(value = "/saveOrUpdateBatch")
	 public Result<String> saveOrUpdateBatch(@RequestBody BaosongTaskAlloc taskAlloc) {
		List<Integer> itemIds =  taskAlloc.getItemids();
		List<BaosongTaskAlloc> allocList = new ArrayList<>();
		Integer taskId = taskAlloc.getTaskid();
		String userid = taskAlloc.getFillUser();
		removeBatch(itemIds,taskId);
		if(userid==null||userid.trim().length()==0){
			return Result.OK("保存成功！");
		}
		for(Integer itemId:itemIds){
			BaosongTaskAlloc alloc = new BaosongTaskAlloc();
			alloc.setItemid(itemId);
			alloc.setTplid(taskAlloc.getTplid());
			alloc.setTaskid(taskAlloc.getTaskid());
			alloc.setFillUser(taskAlloc.getFillUser());
			allocList.add(alloc);
		}
		baosongTaskAllocService.saveOrUpdateBatch(allocList);
		baosongTaskService.updateTaskSta(1,taskId);

		return Result.OK("保存成功！");
	 }


	@PostMapping(value = "/updateFillStaBatch")
	public Result<String> updateFillStaBatch(@RequestBody BaosongTaskAlloc taskAlloc) {
		QueryWrapper<BaosongTaskAlloc> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("taskid",taskAlloc.getTaskid())
				.eq("fill_user",UserUtil.getUserId());
		taskAlloc.setFillSta(true);
		baosongTaskService.updateTaskSta(2,taskAlloc.getTaskid());
		baosongTaskAllocService.update(taskAlloc,queryWrapper);
		return Result.OK("保存成功！");
	}

	 @GetMapping(value = "/queryAllTplForUser")
	 public Result<List<BaosongTpl>> queryAllTplForUser(BaosongTask task, HttpServletRequest req) {
		 BaosongTaskAlloc alloc = new BaosongTaskAlloc();
		 alloc.setFillUser(UserUtil.getUserId());
		 alloc.setTaskid(task.getId());
		 List<BaosongTpl> list = baosongTaskAllocService.queryAllTplForUser(alloc);
		 return Result.OK(list);
	 }

	@GetMapping(value = "/queryAllTplItemForUser")
	public Result<List<BaosongTplItem>> queryAllTplItemForUser(BaosongTaskAlloc alloc, HttpServletRequest req) {
		alloc.setFillUser(UserUtil.getUserId());
		List<BaosongTplItem> list = baosongTaskAllocService.queryAllTplItemForUser(alloc);
		if(list!=null&&list.size()>0) {
			addParentItems(list);
		}
		return Result.OK(list);
	}

	@GetMapping(value = "/queryCurTaskAllocUser")
	public Result<List<Map<String,Object>>> queryCurTaskAllocUser(BaosongTaskAlloc task, HttpServletRequest req) {
		BaosongTaskAlloc alloc = new BaosongTaskAlloc();
		alloc.setTaskid(task.getId());
		List<Map<String,Object>> list = baosongTaskAllocService.queryCurTaskAllocUser(alloc);
		return Result.OK(list);
	}

	private void removeBatch(List<Integer> itemIds,Integer taskId) {
		QueryWrapper<BaosongTaskAlloc> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("taskid",taskId).in("itemid",itemIds);
		baosongTaskAllocService.remove(queryWrapper);
	}

	private void addParentItems(List<BaosongTplItem> list) {
		QueryWrapper<BaosongTplItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.gt("child_num",0);
		List<BaosongTplItem> parentList = baosongTplItemService.list(queryWrapper);
		Map<String, BaosongTplItem> idToPidMap = new HashMap<>();
		for (BaosongTplItem node : parentList) {
			idToPidMap.put(node.getCode(), node);
		}
		List<BaosongTplItem> rootItemList = new ArrayList<>();
		for(BaosongTplItem item:list) {
			BaosongTplItem currentItem = idToPidMap.get(item.getPcode());
			while (currentItem != null) {
				if(rootItemList.contains(currentItem)) {
					break;
				}
				rootItemList.add(currentItem);
				BaosongTplItem currentPItem = idToPidMap.get(currentItem.getPcode());
				if (currentPItem == null) {
					break;
				}
				currentItem	= currentPItem;
			}
		}
		if(rootItemList.size()>0) {
			list.addAll(0,rootItemList);
		}
	}

	@GetMapping(value = "/findUserRightForTplItem")
	public Result<Set<String>> findUserRightForTplItem(BaosongTaskAlloc taskAlloc,HttpServletRequest req) {
		Set<String> retCodeSet = new HashSet<>();
		try {
			String userId = UserUtil.getUserId();
			List<BaosongTaskAlloc> allocTplList = baosongTaskAllocService.lambdaQuery()
					.eq(BaosongTaskAlloc::getFillUser, userId)
					.eq(BaosongTaskAlloc::getTaskid,taskAlloc.getTaskid())
					.eq(BaosongTaskAlloc::getTplid,taskAlloc.getTplid())
					.list();
			Set<Integer> tplIdSet = new HashSet<>();
			for (BaosongTaskAlloc alloc : allocTplList) {
				tplIdSet.add(alloc.getItemid());
			}
			if(tplIdSet.size()>0) {
				List<BaosongTplItem> itemList = baosongTplItemService.lambdaQuery()
						.in(BaosongTplItem::getId, tplIdSet)
						.list();
				for (BaosongTplItem item : itemList) {
					retCodeSet.add(item.getPcode() + "_" + item.getCode());
				}
			}
			return Result.OK(retCodeSet);
		} catch (Exception e) {
			log.error("查询用户模板权限失败", e);
			return Result.error("查询失败，请稍后重试");
		}
	}
}
