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

import java.util.*;

import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.BaosongQuery;
import org.jeecg.modules.stm.baosong.entity.BaosongTaskRecord;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskRecordService;

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;

/**
 * @Description: 填报记录
 * @Author: jeecg-boot
 * @Date:   2024-12-17
 * @Version: V1.0
 */
  
@RestController
@RequestMapping("/baosong/baosongTaskRecord")
@Slf4j
public class BaosongTaskRecordController extends JeecgController<BaosongTaskRecord, IBaosongTaskRecordService> {
	@Autowired
	private IBaosongTaskRecordService baosongTaskRecordService;

	
	/**
	 * 分页列表查询
	 *
	 * @param baosongTaskRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "填报记录-分页列表查询")
	  
	@GetMapping(value = "/list")
	public Result<IPage<BaosongTaskRecord>> queryPageList(BaosongTaskRecord baosongTaskRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BaosongTaskRecord> queryWrapper = QueryGenerator.initQueryWrapper(baosongTaskRecord, req.getParameterMap());
		Page<BaosongTaskRecord> page = new Page<BaosongTaskRecord>(pageNo, pageSize);
		IPage<BaosongTaskRecord> pageList = baosongTaskRecordService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/queryRecord")
	 public Result<List<BaosongTaskRecord>> queryRecord(BaosongTaskRecord baosongTaskRecord,
														   HttpServletRequest req) {
		 QueryWrapper<BaosongTaskRecord> queryWrapper = QueryGenerator.initQueryWrapper(baosongTaskRecord, req.getParameterMap());
		 List<BaosongTaskRecord> list = baosongTaskRecordService.list(queryWrapper);
		 return Result.OK(list);
	 }


	 /**
	 *   添加
	 *
	 * @param baosongTaskRecord
	 * @return
	 */
	@AutoLog(value = "填报记录-添加")
	  
	@RequiresPermissions("baosong:baosong_task_record:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BaosongTaskRecord baosongTaskRecord) {
		baosongTaskRecordService.save(baosongTaskRecord);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param baosongTaskRecord
	 * @return
	 */
	@AutoLog(value = "填报记录-编辑")
	  
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BaosongTaskRecord baosongTaskRecord) {
		baosongTaskRecordService.updateById(baosongTaskRecord);
		return Result.OK("编辑成功!");
	}

	 @PostMapping(value = "/batchSaveOrUpdate")
	 public Result<String> batchSaveOrUpdate(@RequestBody List<BaosongTaskRecord> list,HttpServletRequest req) {
		 baosongTaskRecordService.saveOrUpdateBatch(list);
		 return Result.OK("添加成功！");
	 }


	@PostMapping(value = "/batchSaveOrUpdateBeforeDelete")
	public Result<String> batchSaveOrUpdateBeforeDelete(@RequestBody List<BaosongTaskRecord> list,HttpServletRequest req) {
		BaosongTaskRecord baosongTaskRecord0 = list.get(0);
		Integer taskId = baosongTaskRecord0.getTaskid();
		Integer tplId = baosongTaskRecord0.getTplid();
		QueryWrapper<BaosongTaskRecord> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("taskid",taskId).eq("tplid",tplId);
		baosongTaskRecordService.remove(queryWrapper);
		baosongTaskRecordService.saveOrUpdateBatch(list);
		return Result.OK("添加成功！");
	}
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "填报记录-通过id删除")
	  
	@RequiresPermissions("baosong:baosong_task_record:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		baosongTaskRecordService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "填报记录-批量删除")
	  
	@RequiresPermissions("baosong:baosong_task_record:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.baosongTaskRecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "填报记录-通过id查询")
	  
	@GetMapping(value = "/queryById")
	public Result<BaosongTaskRecord> queryById(@RequestParam(name="id",required=true) String id) {
		BaosongTaskRecord baosongTaskRecord = baosongTaskRecordService.getById(id);
		if(baosongTaskRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(baosongTaskRecord);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param baosongTaskRecord
    */
    @RequiresPermissions("baosong:baosong_task_record:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BaosongTaskRecord baosongTaskRecord) {
        return super.exportXls(request, baosongTaskRecord, BaosongTaskRecord.class, "填报记录");
    }

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


	@PostMapping(value = "/saveBatch")
	public Result<List<BaosongTaskRecord>> saveBatch(@RequestBody BaosongTaskRecord taskRecord) {
		Integer rind = taskRecord.getRind();
		List<BaosongTaskRecord> sList = new ArrayList<>();
		for (Map.Entry<String, Object> entry : taskRecord.getDatas().entrySet()) {
			if(entry.getValue()==null||entry.getValue().equals("")) continue;
			BaosongTaskRecord record = new BaosongTaskRecord();
			String[] tmpAry =entry.getKey().split("_");
			record.setRind(rind);
			record.setItemid(Integer.valueOf(tmpAry[0]));
			record.setTplid(taskRecord.getTplid());
			record.setTaskid(taskRecord.getTaskid());
			record.setTplcode(tmpAry[1]);
			String strContent = entry.getValue().toString().trim();
			strContent = strContent.replaceAll(" ","");
			if(strContent.startsWith("[")&&strContent.endsWith("]")) {
				strContent = strContent.substring(1, strContent.length() - 1);
			}
			record.setContent(strContent);
			record.setItempid(taskRecord.getItempid());
			sList.add(record);
		}
		deleteByPitemid(taskRecord);
		baosongTaskRecordService.saveBatch(sList);
		return Result.OK(sList);
	}

	@GetMapping(value = "/queryTaskRecords")
	public Result<List<BaosongTaskRecord>> queryTaskRecords(BaosongTaskRecord taskRecord) {
		QueryWrapper<BaosongTaskRecord> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("itempid",taskRecord.getItempid()).eq("taskid",taskRecord.getTaskid());
		List<BaosongTaskRecord> list =  baosongTaskRecordService.list(queryWrapper);
		return Result.OK(list);
	}

	@GetMapping(value = "/deleteByPitemidAndRind")
	public Result<String> deleteByPitemidAndRind(BaosongTaskRecord taskRecord) {
		deleteByPitemid(taskRecord);
		return Result.OK("删除成功");
	}

	private void deleteByPitemid(BaosongTaskRecord taskRecord) {
		QueryWrapper<BaosongTaskRecord> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("itempid",taskRecord.getItempid())
				.eq("rind",taskRecord.getRind())
				.eq("taskid",taskRecord.getTaskid());
		baosongTaskRecordService.remove(queryWrapper);
	}


	@GetMapping(value = "/findTaskRecords")
	public Result<List<Map<String,Object>>> findTaskRecords(BaosongTaskRecord taskRecord) {
		List<Map<String,Object>> list =  baosongTaskRecordService.queryTaskRecords(taskRecord);
		return Result.OK(list);
	}

	@GetMapping(value = "/findFilledlist")
	public Result<List<BaosongQuery>> findFilledlist(BaosongQuery baosongQuery,
												 HttpServletRequest req) {
		try {
			List<BaosongQuery> list = baosongTaskRecordService.findTaskRecords(baosongQuery);
			return Result.OK(list);
		} catch (Exception e) {

		}
		return null;
	}


	@GetMapping(value = "/findFillHistoryForCheck")
	public Result<List<Map<String, Object>>> findFillHistoryForCheckTraditional(BaosongQuery baosongQuery, HttpServletRequest req) {
		// 参数校验
		if (baosongQuery == null) {
			return Result.error("查询参数不能为空");
		}

		List<Map<String, Object>> retList = new ArrayList<>();

		try {
			List<BaosongQuery> list = baosongTaskRecordService.findTaskRecords(baosongQuery);

			if (CollectionUtils.isEmpty(list)) {
				return Result.OK(Collections.emptyList());
			}

			// 使用 LinkedHashMap 保持插入顺序
			Map<Integer, List<Map<String, Object>>> tmpMap = new LinkedHashMap<>();
			Map<Integer, String> itemNameMap = new HashMap<>();
			Map<Integer,String> taskNameMap = new HashMap<>();
			for (BaosongQuery taskRecord : list) {
				Integer itemId = taskRecord.getItemid();

				// 获取或创建列表
				List<Map<String, Object>> cList = tmpMap.computeIfAbsent(itemId,
						k -> new ArrayList<>());

				// 构建值Map
				Map<String, Object> tmpVal = new HashMap<>(3);
				tmpVal.put("value", taskRecord.getContent());
				tmpVal.put("taskid", taskRecord.getTaskid());
				tmpVal.put("taskName", taskRecord.getTaskName());

				cList.add(tmpVal);

				// 存储 itemName（如果已存在则跳过）
				itemNameMap.putIfAbsent(itemId, taskRecord.getTplItemName());
				if(taskNameMap.get(taskRecord.getTaskid())!=null){
					taskNameMap.put(taskRecord.getTaskid(),taskRecord.getTaskName());
				}

			}

			// 构建结果
			for (Map.Entry<Integer, List<Map<String, Object>>> entry : tmpMap.entrySet()) {
				Integer itemId = entry.getKey();

				Map<String, Object> resultItem = new HashMap<>(3);
				resultItem.put("itemId", itemId);
				resultItem.put("itemName", itemNameMap.get(itemId));
				resultItem.put("values", entry.getValue());

				retList.add(resultItem);
			}

			// 可选：按 itemId 排序
			retList.sort(Comparator.comparing(m -> (Integer) m.get("itemId")));

		} catch (ServiceException e) {
			log.error("查询填报历史记录失败，查询参数：{}", baosongQuery, e);
			return Result.error("查询失败：" + e.getMessage());
		} catch (Exception e) {
			log.error("系统异常，查询填报历史记录失败", e);
			return Result.error("系统异常，请稍后重试");
		}

		return Result.OK(retList);
	}
}
