package org.jeecg.modules.stm.baosong.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.baosong.entity.BaosongQuery;
import org.jeecg.modules.stm.baosong.entity.BaosongTaskAlloc;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskAllocService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 org.jeecg.modules.stm.baosong.entity.BaosongTpl;
import org.jeecg.modules.stm.baosong.entity.BaosongTplItem;
import org.jeecg.modules.stm.baosong.service.IBaosongTplItemService;
import org.jeecg.modules.stm.baosong.service.IBaosongTplService;
import org.jeecg.modules.stm.utils.UserUtil;
import org.w3c.dom.Document;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Description: 报送模板
 * @Author: jeecg-boot
 * @Date:   2024-12-14
 * @Version: V1.0
 */
  
@RestController
@RequestMapping("/baosong/baosongTpl")
@Slf4j

public class BaosongTplController extends JeecgController<BaosongTpl, IBaosongTplService> {
	@Autowired
	private IBaosongTplService baosongTplService;
	@Autowired
	private IBaosongTplItemService baosongTplItemService;
	@Autowired
	private IBaosongTaskAllocService baosongTaskAllocService;

	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;
	
	/**
	 * 分页列表查询
	 *
	 * @param baosongTpl
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "报送模板-分页列表查询")
	  
	@GetMapping(value = "/list")
	public Result<IPage<BaosongTpl>> queryPageList(BaosongTpl baosongTpl,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BaosongTpl> queryWrapper = QueryGenerator.initQueryWrapper(baosongTpl, req.getParameterMap());
		Page<BaosongTpl> page = new Page<BaosongTpl>(pageNo, pageSize);
		IPage<BaosongTpl> pageList = baosongTplService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@GetMapping(value = "/allTpls")
	public Result<List<BaosongTpl>> queryAllTpls(BaosongTpl baosongTpl, HttpServletRequest req) {
		QueryWrapper<BaosongTpl> queryWrapper = QueryGenerator.initQueryWrapper(baosongTpl, req.getParameterMap());
		List<BaosongTpl> list = baosongTplService.list(queryWrapper);
		return Result.OK(list);
	}
	/**
	 *   添加
	 *
	 * @param baosongTpl
	 * @return
	 */
	@AutoLog(value = "报送模板-添加")
	  
	@RequiresPermissions("baosong:baosong_tpl:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BaosongTpl baosongTpl) {
		baosongTpl.setCreatedTime(new Date());
		baosongTpl.setUpdatedTime(new Date());
		baosongTpl.setCreatedUser(UserUtil.getUserId());
		baosongTpl.setUpdatedUser(UserUtil.getUserId());
		baosongTplService.save(baosongTpl);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param baosongTpl
	 * @return
	 */
	@AutoLog(value = "报送模板-编辑")
	  
	@RequiresPermissions("baosong:baosong_tpl:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BaosongTpl baosongTpl) {
		baosongTpl.setUpdatedUser(UserUtil.getUserId());
		baosongTpl.setUpdatedTime(new Date());
		baosongTplService.updateById(baosongTpl);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "报送模板-通过id删除")
	  
	@RequiresPermissions("baosong:baosong_tpl:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		baosongTplService.removeById(id);
		QueryWrapper<BaosongTplItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("tplid",id);
		baosongTplItemService.removeById(queryWrapper);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "报送模板-批量删除")
	  
	@RequiresPermissions("baosong:baosong_tpl:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		this.baosongTplService.removeByIds(idList);
		QueryWrapper<BaosongTplItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("tplid",idList);
		baosongTplItemService.removeById(queryWrapper);
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "报送模板-通过id查询")
	  
	@GetMapping(value = "/queryById")
	public Result<BaosongTpl> queryById(@RequestParam(name="id",required=true) String id) {
		BaosongTpl baosongTpl = baosongTplService.getById(id);
		if(baosongTpl==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(baosongTpl);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param baosongTpl
    */
    @RequiresPermissions("baosong:baosong_tpl:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BaosongTpl baosongTpl) {
        return super.exportXls(request, baosongTpl, BaosongTpl.class, "报送模板");
    }

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

	@RequiresPermissions("baosong:baosong_tpl_item:importExcel")
	@RequestMapping(value = "/importXml", method = RequestMethod.POST)
	public Result<?> importXml(BaosongTpl baosongTpl, HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {

			MultipartFile file = entity.getValue();
			if (file.isEmpty() || !file.getContentType().equals("text/xml")) {
				return Result.error("请传入有效的XML文件！");
			}
			try {
				if(baosongTpl.getBtp()==null) {
					baosongTpl.setBtp(1);
				}
				if(baosongTpl.getXmlfilePath() ==null||baosongTpl.getXmlfilePath().equals("null")){
					baosongTpl.setXmlfilePath("");
				}
				if(baosongTpl.getDes()==null||baosongTpl.getDes().equals("null")){
					baosongTpl.setDes("");
				}
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				InputStream inputStream = file.getInputStream();
				Document document = builder.parse(inputStream);

				List<BaosongTplItem> tplItems =findCurTplItems(baosongTpl);
				baosongTplItemService.parseXmlFile(document,baosongTpl,tplItems);
				baosongTpl.setUpdatedTime(new Date());
				baosongTplService.saveOrUpdate(baosongTpl);
				return Result.ok();
			} catch (Exception e) {
				String msg = e.getMessage();
				log.error(msg, e);
				if(msg!=null && msg.indexOf("Duplicate entry")>=0){
					return Result.error("文件导入失败:有重复数据！");
				}else{
					return Result.error("文件导入失败:" + e.getMessage());
				}
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}


	@RequestMapping(value = "/importTplItemDes", method = RequestMethod.GET)
	public Result<?> importTplItemDes(HttpServletRequest request, HttpServletResponse response) {
		ImportTplItemDes importTplItemDes = new ImportTplItemDes(getDesFileName());
		List<BaosongTplItem> itemList = baosongTplItemService.list();
		Map<Integer,String> retMap = importTplItemDes.getTplItemDesMap(itemList);
		List<BaosongTplItem> desItems = new ArrayList<>();

		for(BaosongTplItem item:itemList) {
			item.setDes(retMap.get(item.getId()));
			if(retMap.get(item.getId())!=null) {
				desItems.add(item);
			}
		}
		baosongTplItemService.updateBatchById(desItems);
		return Result.ok("操作完成");

	}

	private void removeData(BaosongTpl baosongTpl) {
		QueryWrapper<BaosongTplItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("tplid",baosongTpl.getId());
		baosongTplItemService.remove(queryWrapper);
	}

	private List<BaosongTplItem> findCurTplItems(BaosongTpl baosongTpl) {
		QueryWrapper<BaosongTplItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("tplid",baosongTpl.getId());
		return baosongTplItemService.list(queryWrapper);
	}


	// 得到填报说明文件名称
	private String getDesFileName(){
		StringBuffer sb = new StringBuffer();
		sb.append(uploadpath).append("/baosong/").append("银行业保险业信息科技非现场监管报表填报指南（2024版）.pdf");
		return sb.toString();
	}

	@GetMapping(value = "/findUserRightForTpl")
	public Result<List<BaosongTpl>> findUserRightForTpl(Integer taskId,HttpServletRequest req) {
		List<BaosongTpl> retTplList = new ArrayList<>();

		try {
			String userId = UserUtil.getUserId();
			List<BaosongTaskAlloc> allocTplList = baosongTaskAllocService.lambdaQuery()
					.eq(BaosongTaskAlloc::getFillUser, userId)
					.eq(BaosongTaskAlloc::getTaskid,taskId)
					.list();
			Set<Integer> tplIdSet = new HashSet<>();
			for (BaosongTaskAlloc alloc : allocTplList) {
				Integer tplId = alloc.getTplid();
				if (tplId != null) {
					tplIdSet.add(tplId);
				}
			}

			if (!tplIdSet.isEmpty()) {
				retTplList = baosongTplService.lambdaQuery()
						.in(BaosongTpl::getId, tplIdSet)
						.list();
			}

			return Result.OK(retTplList);

		} catch (Exception e) {
			log.error("查询用户模板权限失败", e);
			return Result.error("查询失败，请稍后重试");
		}
	}


 }
