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

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

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.stm.baosong.entity.BaosongDataValid;
import org.jeecg.modules.stm.baosong.entity.BaosongTaskRecord;
import org.jeecg.modules.stm.baosong.entity.BaosongTplItem;
import org.jeecg.modules.stm.baosong.service.IBaosongDataValidService;

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

/**
 * @Description: 报送数据校验
 * @Author: jeecg-boot
 * @Date:   2025-05-16
 * @Version: V1.0
 */

@RestController
@RequestMapping("/baosong/baosongDataValid")
@Slf4j
public class BaosongDataValidController extends JeecgController<BaosongDataValid, IBaosongDataValidService> {
	@Autowired
	private IBaosongDataValidService baosongDataValidService;
	@Autowired
	private IBaosongTaskRecordService baosongTaskRecordService;
	@Autowired
	private IBaosongTplItemService baosongTplItemService;
	/**
	 * 分页列表查询
	 *
	 * @param baosongDataValid
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "报送数据校验-分页列表查询")

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

	 @GetMapping(value = "/queryAllList")
	 public Result<List<BaosongDataValid>> queryAllList(BaosongDataValid baosongDataValid,HttpServletRequest req) {
		 QueryWrapper<BaosongDataValid> queryWrapper = QueryGenerator.initQueryWrapper(baosongDataValid, req.getParameterMap());
		 List<BaosongDataValid> list = baosongDataValidService.list(queryWrapper);
		 return Result.OK(list);
	 }
	
	/**
	 *   添加
	 *
	 * @param baosongDataValid
	 * @return
	 */
	@AutoLog(value = "报送数据校验-添加")

	@RequiresPermissions("baosong:baosong_data_valid:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BaosongDataValid baosongDataValid) {
		baosongDataValidService.save(baosongDataValid);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param baosongDataValid
	 * @return
	 */
	@AutoLog(value = "报送数据校验-编辑")

	@RequiresPermissions("baosong:baosong_data_valid:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BaosongDataValid baosongDataValid) {
		baosongDataValidService.updateById(baosongDataValid);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "报送数据校验-通过id删除")

	@RequiresPermissions("baosong:baosong_data_valid:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		baosongDataValidService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "报送数据校验-批量删除")

	@RequiresPermissions("baosong:baosong_data_valid:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.baosongDataValidService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "报送数据校验-通过id查询")

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

    /**
    * 导出excel
    *
    * @param request
    * @param baosongDataValid
    */
    @RequiresPermissions("baosong:baosong_data_valid:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BaosongDataValid baosongDataValid) {
        return super.exportXls(request, baosongDataValid, BaosongDataValid.class, "报送数据校验");
    }

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

	 @GetMapping(value = "/validData")
	 public Result<Map<String,Object>> validData(
			 @RequestParam(name = "fillContent") String fillContent,
			 @RequestParam(name = "taskId") Integer taskId,
			 @RequestParam(name = "tplItemId") Integer tplItemId,
			 HttpServletRequest req) {

		 Map<String,Object> retMap = new HashMap<>();
//		 List<BaosongDataValid> listFormula = baosongDataValidService.lambdaQuery()
//				 .apply("FIND_IN_SET({0}, params)", tplItemId)
//				 .list();

		 List<BaosongDataValid> listFormula = baosongDataValidService.lambdaQuery()
				 .eq(BaosongDataValid::getTplItemid, tplItemId)
				 .list();

		 List<Integer> itemIdList = listFormula.stream()
				 .map(BaosongDataValid::getParams)
				 .filter(Objects::nonNull)
				 .flatMap(params -> Arrays.stream(params.split(",")))
				 .filter(StringUtils::isNotBlank)
				 .map(Integer::valueOf)
				 .collect(Collectors.toList());

		 Map<String,Object> codeValMap = new HashMap<>();
		 List<BaosongTplItem>  tplItemList = new ArrayList<>();
		 int fillFinishCnt = 0;
		 if (CollectionUtils.isNotEmpty(itemIdList)) {
			 tplItemList = baosongTplItemService.listByIds(itemIdList);
			 QueryWrapper<BaosongTaskRecord>  queryWrapper = new QueryWrapper<>();
			 queryWrapper.in("itemid",itemIdList).eq("taskid",taskId);
			 List<BaosongTaskRecord>  recordList = baosongTaskRecordService.list(queryWrapper);
			 fillFinishCnt = recordList.size();

			 for (BaosongTaskRecord record:recordList) {
				 codeValMap.put(record.getTplcode(),record.getContent());

			 }
		 }
		 retMap.put("codeVal",codeValMap);
		 retMap.put("formula",listFormula);
		 retMap.put("tplItemList",tplItemList);
		 retMap.put("noFillCnt",itemIdList.size()-fillFinishCnt);
		 return Result.OK(retMap);
	 }

}
