package org.stm.audit.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.stm.audit.entity.AuditProjectProblem;
import org.stm.audit.entity.AuditProjectProblemRelItem;
import org.stm.audit.service.IAuditProjectProblemRelItemService;
import org.stm.audit.service.IAuditProjectProblemService;

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.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 项目问题表
 * @Author: jeecg-boot
 * @Date:   2025-04-23
 * @Version: V1.0
 */
@Api(tags="项目问题表")
@RestController
@RequestMapping("/audit/auditProjectProblem")
@Slf4j
public class AuditProjectProblemController extends JeecgController<AuditProjectProblem, IAuditProjectProblemService> {
	@Autowired
	private IAuditProjectProblemService auditProjectProblemService;
	 @Autowired
	 private IAuditProjectProblemRelItemService auditProjectProblemRelItemService;
	
	/**
	 * 分页列表查询
	 *
	 * @param auditProjectProblem
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "项目问题表-分页列表查询")
	@ApiOperation(value="项目问题表-分页列表查询", notes="项目问题表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AuditProjectProblem>> queryPageList(AuditProjectProblem auditProjectProblem,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AuditProjectProblem> queryWrapper = QueryGenerator.initQueryWrapper(auditProjectProblem, req.getParameterMap());
		Page<AuditProjectProblem> page = new Page<AuditProjectProblem>(pageNo, pageSize);
		IPage<AuditProjectProblem> pageList = auditProjectProblemService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/listAll")
	 public Result<List<AuditProjectProblem>> listAll(AuditProjectProblem auditProjectProblem, HttpServletRequest req) {
		 QueryWrapper<AuditProjectProblem> queryWrapper = QueryGenerator.initQueryWrapper(auditProjectProblem, req.getParameterMap());
		List<AuditProjectProblem> list = auditProjectProblemService.list(queryWrapper);
		 setReportItems(list);
		 return Result.OK(list);
	 }
	
	/**
	 *   添加
	 *
	 * @param auditProjectProblem
	 * @return
	 */
	@AutoLog(value = "项目问题表-添加")
	@ApiOperation(value="项目问题表-添加", notes="项目问题表-添加")
	@RequiresPermissions("audit:audit_project_problem:add")
	@PostMapping(value = "/add")
	public Result<AuditProjectProblem> add(@RequestBody AuditProjectProblem auditProjectProblem) {
		List<Integer> itemIdList = auditProjectProblem.getItemIdList();
		updateIscur(auditProjectProblem);
		auditProjectProblem.setIscur(true);
		auditProjectProblemService.save(auditProjectProblem);
		addReportItems(auditProjectProblem);
		return Result.OK(auditProjectProblem);
	}

	/**
	 *  编辑
	 *
	 * @param auditProjectProblem
	 * @return
	 */
	@AutoLog(value = "项目问题表-编辑")
	@ApiOperation(value="项目问题表-编辑", notes="项目问题表-编辑")
	@RequiresPermissions("audit:audit_project_problem:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody AuditProjectProblem auditProjectProblem) {
		auditProjectProblemService.updateById(auditProjectProblem);
		deleteReportItems(auditProjectProblem.getId());
		addReportItems(auditProjectProblem);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "项目问题表-通过id删除")
	@ApiOperation(value="项目问题表-通过id删除", notes="项目问题表-通过id删除")
	@RequiresPermissions("audit:audit_project_problem:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		auditProjectProblemService.removeById(id);
		deleteReportItems(Integer.parseInt(id));
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "项目问题表-批量删除")
	@ApiOperation(value="项目问题表-批量删除", notes="项目问题表-批量删除")
	@RequiresPermissions("audit:audit_project_problem:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.auditProjectProblemService.removeByIds(Arrays.asList(ids.split(",")));
		for(String id : ids.split(","))
		deleteReportItems(Integer.parseInt(id));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "项目问题表-通过id查询")
	@ApiOperation(value="项目问题表-通过id查询", notes="项目问题表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AuditProjectProblem> queryById(@RequestParam(name="id",required=true) String id) {
		AuditProjectProblem auditProjectProblem = auditProjectProblemService.getById(id);
		if(auditProjectProblem==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(auditProjectProblem);
	}


    /**
    * 导出excel
    *
    * @param request
    * @param auditProjectProblem
    */
    @RequiresPermissions("audit:audit_project_problem:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AuditProjectProblem auditProjectProblem) {
        return super.exportXls(request, auditProjectProblem, AuditProjectProblem.class, "项目问题表");
    }

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

	 private void updateIscur(AuditProjectProblem auditProjectProblem) {
		 QueryWrapper<AuditProjectProblem> queryWrapper = new QueryWrapper<>();
		 AuditProjectProblem audit = new AuditProjectProblem();
		 audit.setIscur(false);
		 queryWrapper.eq("project_id",auditProjectProblem.getProjectId());
		 audit.setProjectId(auditProjectProblem.getProjectId());
		 auditProjectProblemService.update(audit,queryWrapper);
	 }

	 private void addReportItems(AuditProjectProblem auditProjectProblem) {
		 List<Integer> itemIdList = auditProjectProblem.getItemIdList();
		 if(itemIdList==null||itemIdList.size()==0)  return;
		 List<AuditProjectProblemRelItem> itemList = new ArrayList<>();
		 for(Integer itemId : itemIdList) {
			 AuditProjectProblemRelItem aItem = new AuditProjectProblemRelItem();
			 aItem.setItemid(itemId);
			 aItem.setProblemid(auditProjectProblem.getId());
			 aItem.setProjectid(auditProjectProblem.getProjectId());
			 itemList.add(aItem);
		 }
		 auditProjectProblemRelItemService.saveBatch(itemList);
	 }

	 private void deleteReportItems(Integer problemid) {
		 QueryWrapper<AuditProjectProblemRelItem> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("problemid",problemid);
		 auditProjectProblemRelItemService.remove(queryWrapper);
	 }


	 private void setReportItems(List<AuditProjectProblem> list) {
		 if(list==null || list.size()==0) return;

		 Set<Integer> ids = list.stream()
				 .map(AuditProjectProblem::getId)
				 .collect(Collectors.toSet());

		 QueryWrapper<AuditProjectProblemRelItem> queryWrapper = new QueryWrapper<>();
		 queryWrapper.in("problemid", ids);
		 List<AuditProjectProblemRelItem> retList = auditProjectProblemRelItemService.list(queryWrapper);

		 Map<Integer, AuditProjectProblem> problemMap = list.stream()
				 .collect(Collectors.toMap(AuditProjectProblem::getId, problem -> problem));
		 for (AuditProjectProblemRelItem item : retList) {
			 AuditProjectProblem problem = problemMap.get(item.getProblemid());
			 if (problem != null) {
				 if (problem.getItemIdList() == null) {
					 problem.setItemIdList(new ArrayList<>()); // 确保不为null
				 }
				 problem.getItemIdList().add(item.getItemid());
			 }
		 }
	 }
 }
