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

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.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.stm.audit.entity.*;
import org.jeecg.modules.stm.audit.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import org.jeecg.modules.stm.doc.service.IDocFilesService;
import org.jeecg.modules.stm.utils.UserUtil;

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

/**
 * @Description: 任务分配
 * @Author: jeecg-boot
 * @Date:   2024-12-21
 * @Version: V1.0
 */

@RestController
@RequestMapping("/audit/auditTask")
@Slf4j
public class AuditTaskController extends JeecgController<AuditTask, IAuditTaskService> {
	@Autowired
	private IAuditTaskService auditTaskService;
	@Autowired
	private IAuditCheckMethodItemService auditCheckMethodItemService;
	@Autowired
	private IAuditActRelOthersService stActRelOthersService;
	@Autowired
	private IAuditCheckMethodService auditCheckMethodService;
	@Autowired
	private IAuditProjectItemService auditProjectItemService;
	@Autowired
	private IAuditTaskReportService auditTaskReportService;
	@Autowired
	private IAuditComplianeItemService auditComplianeItemService;
	@Autowired
	private IAuditItemRelCheckService auditItemRelCheckService;
	@Autowired
	private IDocFilesService docFilesService;
	
	/**
	 * 分页列表查询
	 *
	 * @param auditTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "任务分配-分页列表查询")

	@GetMapping(value = "/list")
	public Result<IPage<AuditTask>> queryPageList(AuditTask auditTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AuditTask> queryWrapper = QueryGenerator.initQueryWrapper(auditTask, req.getParameterMap());
		Page<AuditTask> page = new Page<AuditTask>(pageNo, pageSize);
		IPage<AuditTask> pageList = auditTaskService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@AutoLog(value = "任务分配-添加")

	@RequiresPermissions("audit:audit_task:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody AuditTask auditTask) {
		auditTaskService.save(auditTask);
		return Result.OK("添加成功！");
	}

	@AutoLog(value = "任务分配-编辑")

	@RequiresPermissions("audit:audit_task:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody AuditTask auditTask) {
		auditTaskService.updateById(auditTask);
		return Result.OK("编辑成功!");
	}

	@AutoLog(value = "任务分配-通过id删除")

	@RequiresPermissions("audit:audit_task:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		auditTaskService.removeById(id);
		return Result.OK("删除成功!");
	}

	@AutoLog(value = "任务分配-批量删除")

	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.auditTaskService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}


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

    @RequiresPermissions("audit:audit_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AuditTask auditTask) {
        return super.exportXls(request, auditTask, AuditTask.class, "任务分配");
    }

    @RequiresPermissions("audit:audit_task:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AuditTask.class);
    }

	 @PostMapping(value = "/saveProjectCheck")
	 public Result<String> batchSave(@RequestBody AuditTask auditTask) {
		List<AuditTask> list = new ArrayList<>();
		Integer pid = auditTask.getProjectid();
		Integer comeFrom = auditTask.getComeFrom();
		for(Integer id:auditTask.getCheckids()) {
			 AuditTask tmpTask = new AuditTask();
			 tmpTask.setProjectid(pid);
			 tmpTask.setCheckid(id);
			 tmpTask.setComeFrom(comeFrom);
			 tmpTask.setUserid(UserUtil.getUserId());
			 list.add(tmpTask);
		 }
		 QueryWrapper<AuditTask> queryWrapper = new QueryWrapper<>();
		 queryWrapper.in("checkid",auditTask.getCheckids()).eq("projectid",pid);
		 auditTaskService.remove(queryWrapper);
		 auditTaskService.saveBatch(list);
		 auditTaskService.copyCheckItem2ProjectItem(auditTask.getCheckids(),pid,comeFrom);
		 return Result.OK("保存成功！");
	 }

	@PostMapping(value = "/saveProjectAssign")
	public Result<String> taskAssignSave(@RequestBody AuditTask auditTask) {
		List<AuditTask> list = new ArrayList<>();
		Integer pid = auditTask.getProjectid();
		for(Integer id:auditTask.getIds()) {
			AuditTask tmpTask = new AuditTask();
			//tmpTask.setProjectid(pid);
			tmpTask.setId(id);
			tmpTask.setUserid(auditTask.getUserid());
			list.add(tmpTask);
		}
		auditTaskService.saveOrUpdateBatch(list);
		return Result.OK("保存成功！");
	}

	 @GetMapping(value = "/queryAllTask")
	 public Result< List<Map<String,Object>>> queryAllTask(AuditTask auditTask, HttpServletRequest req) {
		 String strActId = req.getParameter("actId");
		 Integer actId = strActId!=null?Integer.valueOf(strActId):null;
		 QueryWrapper<AuditTask> queryWrapper = QueryGenerator.initQueryWrapper(auditTask, req.getParameterMap());
		 //LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 List<Map<String,Object>> list = auditTaskService.getAllTask(null,actId);
		 setItemNum(list);
		 return Result.OK(list);
	 }

	@GetMapping(value = "/queryAllTaskForCurrentUser")
	public Result< List<Map<String,Object>>> queryAllTaskForCurrentUser(AuditTask auditTask, HttpServletRequest req) {
		QueryWrapper<AuditTask> queryWrapper = QueryGenerator.initQueryWrapper(auditTask, req.getParameterMap());
		List<Map<String,Object>> list = auditTaskService.getAllTask(UserUtil.getUserId(),null);
		if(list.size()>0){
			setItemNum(list);
			setActNames(list);
		}
		return Result.OK(list);
	}

	@DeleteMapping(value = "/deleteTaskBatch")
	public Result<String> deleteTaskBatch(
			@RequestParam(name="ids",required=true) String ids,
		  	@RequestParam(name="projectid",required=true) Integer projectid,
		  	@RequestParam(name="checkids",required=true) String checkids) {

		//删除 task 记录 通过 task的id
		if(ids!=null&&!ids.equals("")) {
			this.auditTaskService.removeByIds(Arrays.asList(ids.split(",")));
		}

		if(checkids!=null&&!checkids.equals("")) {
			List<String> checkidList = Arrays.asList(checkids.split(","));
			//删除项目条目
			QueryWrapper<AuditProjectItem> queryProjectItemWrapper = new QueryWrapper<>();
			queryProjectItemWrapper.eq("pid", projectid).in("checkid",checkidList);
			auditProjectItemService.remove(queryProjectItemWrapper);

			//删除项目报告
			QueryWrapper<AuditTaskReport> queryProjectReportWrapper = new QueryWrapper<>();
			queryProjectReportWrapper.eq("projectid", projectid).in("checkid",checkidList);
			auditTaskReportService.remove(queryProjectReportWrapper);

			//删除项目私有的 checkmethod

			QueryWrapper<AuditCheckMethod> queryWrapper = new QueryWrapper<>();
			queryWrapper.in("id",checkidList).eq("is_public",false);
			List<AuditCheckMethod> checkList = this.auditCheckMethodService.list(queryWrapper);
			List<Integer> privateMethodIdList = new ArrayList<>();  //私有的Methodid
			for(AuditCheckMethod method:checkList) {
				if(!method.getIsPublic()){
					privateMethodIdList.add(method.getId());
				}
			}
			if(privateMethodIdList.size()==0) {
				return Result.OK("批量删除成功!");
			}
			this.auditCheckMethodService.removeByIds(privateMethodIdList);

			//删除checkitem
			QueryWrapper<AuditCheckMethodItem> queryWrapperCheckItem = new QueryWrapper<>();
			queryWrapperCheckItem.in("checkid",privateMethodIdList);
			auditCheckMethodItemService.remove(queryWrapperCheckItem);

			//删除item和check关系表
			List<Integer> itemIdList = new ArrayList<>();
			QueryWrapper<AuditItemRelCheck> queryItemRelCheckWrapper = new QueryWrapper<>();
			queryItemRelCheckWrapper.in("checkid",privateMethodIdList);
			List<AuditItemRelCheck> itemRelCheckList = this.auditItemRelCheckService.list(queryItemRelCheckWrapper);
			for(AuditItemRelCheck itemRelCheck:itemRelCheckList) {

				itemIdList.add(itemRelCheck.getCitemid());
			}
			auditItemRelCheckService.remove(queryItemRelCheckWrapper);

			//删除私有文件
			List<Integer> fileIdList = new ArrayList<>();
			List<AuditComplianeItem> listItem = auditComplianeItemService.listByIds(itemIdList);
			for(AuditComplianeItem  item:listItem) {
				if(!item.getIsPublic()&&item.getFileId()!=null) {
					fileIdList.add(item.getFileId());
				}
			}
			if(fileIdList.size()>0){
				docFilesService.removeByIds(fileIdList);
			}
			// 删除合规条目
			if(itemIdList.size()>0){
				auditComplianeItemService.removeByIds(itemIdList);
			}
		}
		return Result.OK("批量删除成功!");
	}

	@GetMapping(value = "/deleteAssignBatch")
	public Result<String> deleteAssignBatch(@RequestParam(name="ids",required=true) String ids) {
		if(ids!=null&&!ids.equals("")) {

			AuditTask auditTask = new AuditTask();
			auditTask.setUserid("");
			QueryWrapper<AuditTask> queryWrapper = new QueryWrapper<>();
			queryWrapper.in("id",Arrays.asList(ids.split(",")));

			this.auditTaskService.update(auditTask, queryWrapper);
		}
		return Result.OK("分配删除成功!");
	}




	private void setItemNum(List<Map<String,Object>> list) {
		Map<Integer,Integer> cntMap = auditCheckMethodItemService.getAllCheckItemCount();
		for(Map<String,Object> item: list) {
			Integer checkId = Integer.valueOf(item.get("checkid").toString());
			if(cntMap.get(checkId)!=null){
				item.put("itemNum",cntMap.get(checkId));
			} else {
				item.put("itemNum",0);
			}
		}
	}

	private void setActNames(List<Map<String,Object>> dataList) {
		List<Integer> checkIdList = new ArrayList<>();
		for(Map<String,Object> data : dataList){
			checkIdList.add(Integer.valueOf(data.get("checkid").toString()));
		}

		Map<Integer, String> idActMap = stActRelOthersService.queryAllActByTids(checkIdList,5);
		for (Map<String, Object> tmap : dataList) {
			Integer tid = new Integer(tmap.get("checkid").toString());
			String tempStr = idActMap.get(tid);
			if(tempStr!=null) {
				int p = tempStr.indexOf("|");
				tmap.put("caNames", tempStr.substring(0,p));
				tmap.put("actIds", tempStr.substring(p+1));
			}
		}
	}
}
