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.*;

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.utils.UserUtil;

/**
 * @Description: 任务表
 * @Author: jeecg-boot
 * @Date:   2024-12-17
 * @Version: V1.0
 */

@RestController
@RequestMapping("/baosong/baosongTask")
@Slf4j
public class BaosongTaskController extends JeecgController<BaosongTask, IBaosongTaskService> {
	@Autowired
	private IBaosongTaskService baosongTaskService;
	@Autowired
	private IBaosongTplService baosongTplService;
	@Autowired
	private IBaosongTaskAllocService baosongTaskAllocService;
	@Autowired
	private IBaosongTaskRecordService baosongTaskRecordService;
	@Autowired
	private IBaosongTaskReviewService baosongTaskReviewService;
	
	/**
	 * 分页列表查询
	 *
	 * @param baosongTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "任务表-分页列表查询")
	  
	@GetMapping(value = "/list")
	public Result<IPage<BaosongTask>> queryPageList(BaosongTask baosongTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BaosongTask> queryWrapper = QueryGenerator.initQueryWrapper(baosongTask, req.getParameterMap());
		queryWrapper.ne("sta",9);
		Page<BaosongTask> page = new Page<BaosongTask>(pageNo, pageSize);
		IPage<BaosongTask> pageList = baosongTaskService.page(page, queryWrapper);
		setStaValue (baosongTask,pageList.getRecords());
		return Result.OK(pageList);
	}


	@GetMapping(value = "/archiveList")
	public Result<IPage<BaosongTask>> archiveList(BaosongTask baosongTask,
				@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
				@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
				HttpServletRequest req) {

		QueryWrapper<BaosongTask> queryWrapper = QueryGenerator.initQueryWrapper(baosongTask, req.getParameterMap());
		queryWrapper.eq("sta",9);
		Page<BaosongTask> page = new Page<BaosongTask>(pageNo, pageSize);
		IPage<BaosongTask> pageList = baosongTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}


	@GetMapping(value = "/listForFillData")
	public Result<IPage<BaosongTask>> listForFillData(BaosongTask baosongTask,
					@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
					@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
					HttpServletRequest req) {
		QueryWrapper<BaosongTask> queryWrapper = QueryGenerator.initQueryWrapper(baosongTask, req.getParameterMap());
		Page<BaosongTask> page = new Page<BaosongTask>(pageNo, pageSize);

		QueryWrapper<BaosongTaskAlloc> queryWrapperAlloc = new QueryWrapper<>();
		queryWrapperAlloc.eq("fill_user",UserUtil.getUserId());
		List<BaosongTaskAlloc> listAlloc = baosongTaskAllocService.list(queryWrapperAlloc);
		List<Integer> taskIdList = new ArrayList<>();
		for(BaosongTaskAlloc alloc :listAlloc) {
			if(!taskIdList.contains(alloc.getTaskid())) {
				taskIdList.add(alloc.getTaskid());
			}
		}
		if(taskIdList==null||taskIdList.size()==0){
			return Result.OK("没有查询到数据");
		}
		queryWrapper.in("id",taskIdList);
		IPage<BaosongTask> pageList = baosongTaskService.page(page, queryWrapper);
		setStaValue (baosongTask,pageList.getRecords());
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/queryAllTasks")
	 public Result<List<BaosongTask>> queryAllTasks(BaosongTask baosongTask, HttpServletRequest req) {
		 QueryWrapper<BaosongTask> queryWrapper = QueryGenerator.initQueryWrapper(baosongTask, req.getParameterMap());

		 List<BaosongTask> list = baosongTaskService.list(queryWrapper);
		 setStaValue (baosongTask,list);
		 return Result.OK(list);
	 }
	
	/**
	 *   添加
	 *
	 * @param baosongTask
	 * @return
	 */
	@AutoLog(value = "任务表-添加")
	  
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BaosongTask baosongTask) {
		if(baosongTask.getTp()==null){
			baosongTask.setTp(1);
		}
		baosongTask.setSta(0);
		baosongTaskService.save(baosongTask);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param baosongTask
	 * @return
	 */
	@AutoLog(value = "任务表-编辑")
	  
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BaosongTask baosongTask) {
		baosongTaskService.updateById(baosongTask);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务表-通过id删除")
	  
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) Integer id) {
		baosongTaskService.removeById(id);
		deleteOther(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务表-批量删除")
	  
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idsList = Arrays.asList(ids.split(","));
		this.baosongTaskService.removeByIds(idsList);
		for(String id :idsList) {
			deleteOther(Integer.parseInt(id));
		}
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "任务表-通过id查询")
	  
	@GetMapping(value = "/queryById")
	public Result<BaosongTask> queryById(@RequestParam(name="id",required=true) String id) {
		BaosongTask baosongTask = baosongTaskService.getById(id);
		if(baosongTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(baosongTask);
	}

	 @PostMapping(value = "/addApproval")
	 public Result<BaosongTask> addApproval(@RequestBody BaosongTask task) {
		QueryWrapper<BaosongTpl> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("tp",task.getTp());
		List<BaosongTpl> tplList =	baosongTaskService.findUserRightForTpl(task.getId());

		List<BaosongTaskReview> saveList = new ArrayList<>();
		for(int i=0;i<tplList.size();i++) {
			BaosongTpl tpl = tplList.get(i);
			BaosongTaskReview view = new BaosongTaskReview();
			view.setTaskid(task.getId());
			view.setTaskname(task.getName());
			view.setTplid(tpl.getId());
			view.setTplname(tpl.getCode()+"-"+ tpl.getNm());
			view.setAppSta(0);
			saveList.add(view);
		}
		baosongTaskReviewService.saveBatch(saveList);
		baosongTaskService.updateTaskSta(3,task.getId());
		return Result.OK("保存成功!");
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param baosongTask
    */
    @RequiresPermissions("baosong:baosong_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BaosongTask baosongTask) {
        return super.exportXls(request, baosongTask, BaosongTask.class, "任务表");
    }

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

	private void setStaValue (BaosongTask baosongTask,List<BaosongTask> tasks) {
		BaosongTaskAlloc alloc = new BaosongTaskAlloc();
		alloc.setTaskid(baosongTask.getId());
		Map<Integer,Integer> taskAllocMap =  baosongTaskAllocService.statAllocNum(alloc);
		Map<Integer,Integer> tplChildNumMap = baosongTaskAllocService.staTplChildNum(alloc);
		Map<Integer,Integer> fillStatMap = baosongTaskAllocService.selectTaskFillSta(alloc);
		for(BaosongTask task: tasks){
			Integer tt = tplChildNumMap.get(task.getTp());
			if(tt==null) continue;
			Integer aa =taskAllocMap.get(task.getId());
			Integer cc =fillStatMap.get(task.getId());
			Integer sta = task.getSta();
			if(sta==null) sta = 1;
			updateTaskStatus(task,sta,aa,cc,tt);
			task.setAllocNum(aa);
			task.setTplItemNum(tt);
			task.setFillStaNum(cc);
		}
	}

	void updateTaskStatus(BaosongTask task, Integer sta, Integer aa, Integer cc, Integer tt) {
		switch (sta) {
			case 1:  // 分配阶段
				setStatusForAllocation(task, aa, tt);
				break;
			case 2: // 填报阶段
				setStatusForSubmission(task, aa, cc);
				break;
			case 3: // 审批阶段
				task.setStaText("待审批");
				break;
			case 4: // 审批结束归档
				task.setStaText("审批完成");
				break;
			default:
				task.setStaText("未知状态"); // 处理未知状态的默认情况
		}
	}

	private void setStatusForAllocation(BaosongTask task, Integer aa, int tt) {
		if (aa == null || aa == 0) {
			task.setStaText("待分配");
		} else if (aa < tt) {
			task.setStaText("分配中");
		} else {
			task.setStaText("分配完成");
		}
	}
	private void setStatusForSubmission(BaosongTask task, Integer aa, Integer cc) {
		if (cc == null || cc == 0) {
			task.setStaText("待填报");
		} else if (cc < aa) {
			task.setStaText("填报中");
		} else if (cc.equals(aa)) {
			task.setStaText("填报完成");
		} else {
			task.setStaText("待填报"); // 这个条件似乎与前一个重复，可以考虑重构
		}
	}


	private void deleteOther(Integer taskId) {
		QueryWrapper<BaosongTaskAlloc> queryAllocWrapper = new QueryWrapper<>();
		queryAllocWrapper.eq("taskid",taskId);
		baosongTaskAllocService.remove(queryAllocWrapper);

		QueryWrapper<BaosongTaskRecord> queryRecordWrapper = new QueryWrapper<>();
		queryRecordWrapper.eq("taskid",taskId);
		baosongTaskRecordService.remove(queryRecordWrapper);
	}



}
