package org.jeecg.modules.stm.compliane.item.controller;

import java.util.*;
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.act.main.entity.StCaMain;
import org.jeecg.modules.stm.act.main.service.IStCaMainService;
import org.jeecg.modules.stm.act.main.vo.StCaMainVo;
import org.jeecg.modules.stm.compliane.item.entity.StComplianeItem;
import org.jeecg.modules.stm.compliane.item.entity.StComplianeItemCa;
import org.jeecg.modules.stm.compliane.item.service.IStComplianeItemService;
import org.jeecg.modules.stm.base.domain.entity.StDomain;
import org.jeecg.modules.stm.base.domain.service.IStDomainService;

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.utils.DirectoryItem;
import org.jeecg.modules.stm.utils.DirectoryList;
import org.jeecg.modules.stm.utils.StmConstans;
import org.jeecg.modules.stm.utils.UserUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 合规条目
 * @Author: yzh
 * @Date:   2023-03-05
 * @Version: V1.0
 */
  
@RestController
@RequestMapping("/compliane.item/stComplianeItem")
@Slf4j
public class StComplianeItemController extends JeecgController<StComplianeItem, IStComplianeItemService> {
	@Autowired
	private IStComplianeItemService stComplianeItemService;
	@Autowired
	private IStCaMainService stCaMainService;
	@Autowired
	private IStDomainService stDomainService;
	
	/**
	 * 分页列表查询
	 *
	 * @param stComplianeItem
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "合规条目-分页列表查询")
	  
	@GetMapping(value = "/list")
	public Result<IPage<StComplianeItem>> queryPageList(StComplianeItem stComplianeItem,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		//QueryWrapper<StComplianeItem> queryWrapper = QueryGenerator.initQueryWrapper(stComplianeItem, req.getParameterMap());
		Page<StComplianeItem> page = new Page<StComplianeItem>(pageNo, pageSize);
		IPage<StComplianeItem> pageList = stComplianeItemService.queryStComplianeItemsWithPage(page, stComplianeItem);
		return Result.OK(pageList);
	}

	   
	 @GetMapping(value = "/listca")
	 public Result<IPage<StComplianeItem>> queryCaPageList(StComplianeItem stComplianeItem,
														 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														 HttpServletRequest req) {
		 QueryWrapper<StComplianeItem> queryWrapper = QueryGenerator.initQueryWrapper(stComplianeItem, req.getParameterMap());
		 Page<StComplianeItem> page = new Page<StComplianeItem>(pageNo, pageSize);
		 IPage<StComplianeItem> pageList = stComplianeItemService.caPage(page, queryWrapper);
		 return Result.OK(pageList);
	 }
	
	/**
	 *   添加
	 *
	 * @param stComplianeItem
	 * @return
	 */
	@AutoLog(value = "合规条目-添加")
	  
	@RequiresPermissions("compliane.item:st_compliane_item:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody StComplianeItem stComplianeItem) {
		stComplianeItemService.save(stComplianeItem);
		if(stComplianeItem.getCaNo()!=null) {
			StComplianeItemCa stComplianeItemCa = new StComplianeItemCa();
			stComplianeItemCa.setItemid(stComplianeItem.getId());
			stComplianeItemCa.setCaNo(stComplianeItem.getCaNo());
			stComplianeItemService.insertItemCa(stComplianeItemCa);
		}
		return Result.OK("添加成功！");
	}

	@PostMapping(value = "/addItemCa")
	public Result<String> addItemCa(@RequestBody StComplianeItemCa stComplianeItemCa) {;
		String caNos = stComplianeItemCa.getCaNo();
		if(caNos!=null && !caNos.equals("")) {
			if(stComplianeItemCa.getItemid()!=null) {
				stComplianeItemService.deleteItemCa(stComplianeItemCa);
				String[] tmpAry = caNos.split(",");
				for (int i = 0; i < tmpAry.length; i++) {
					StComplianeItemCa itemCa = new StComplianeItemCa();
					StComplianeItem item = new StComplianeItem();
					item.setCaNo(tmpAry[i]);
					item.setId(stComplianeItemCa.getItemid())
;					itemCa.setCaNo(tmpAry[i]);
					itemCa.setItemid(stComplianeItemCa.getItemid());
					stComplianeItemService.insertItemCa(itemCa);
					stComplianeItemService.updateById(item);
				}
			}
		}
		return Result.OK("添加成功！");
	}

	@PostMapping(value = "/importFromFile")
	public Result<String> importDomainFromFile(@RequestBody StComplianeItem stComplianeItem) {;
		String complianeNo = stComplianeItem.getComplianeNo();
		String filePath = "d://abc/银行业金融机构信息科技风险监管现场检查手册.pdf";
		List<DirectoryItem> directoryList=  DirectoryList.getDataFromFile(filePath);
        List<StDomain> listStDomain = new ArrayList<>();

		List<StDomain> oldDomainList = stDomainService.list();
		Map<String,String> oldDomainNameMap = new HashMap<>();
		for(int i=0;i<oldDomainList.size();i++){
			oldDomainNameMap.put(oldDomainList.get(i).getDomainName(),oldDomainList.get(i).getDomainCode());
		}

		List<StCaMain> oldStCaMainList = stCaMainService.list();
		Map<String,String> oldCaMainNameMap = new HashMap<>();
		for(int i=0;i<oldStCaMainList.size();i++){
			StCaMain stCaMain = oldStCaMainList.get(i);
			String strKey = stCaMain.getCaName()+ "-"+stCaMain.getDomainCode();
			oldCaMainNameMap.put(strKey,stCaMain.getCaNo());
		}

		try {
			for (DirectoryItem item : directoryList) {
				String strDomain1 = handleName(item.getTitle());
				String oldCode  = setRooDomain(item.getTitle());
				String pDomainCode = oldDomainNameMap.get(strDomain1);
				if (pDomainCode == null) {
					StDomain stDomainOne = new StDomain();
					stDomainOne.setDomainName(strDomain1);
					stDomainOne.setLevel(2);
					stDomainOne.setUpperDomainCode(oldCode);
					stDomainOne.setDomainDesc(item.getContent());
					stDomainService.addStDomain(stDomainOne);
					pDomainCode = stDomainOne.getDomainCode();
					oldDomainNameMap.put(stDomainOne.getDomainName(),stDomainOne.getDomainCode());
				}
				Map<String, List<String[]>> tmpMapCur = item.getSubItems();
				for (String key : tmpMapCur.keySet()) {
					String cdname = handleName(key);
					String cDomainCode = oldDomainNameMap.get(cdname);
					if (cDomainCode == null) {
						StDomain stDomainTwo = new StDomain();
						stDomainTwo.setDomainName(cdname);
						stDomainTwo.setUpperDomainCode(pDomainCode);
						stDomainTwo.setLevel(3);
						stDomainService.addStDomain(stDomainTwo);
						oldDomainNameMap.put(stDomainTwo.getDomainName(),stDomainTwo.getDomainCode());
						cDomainCode = stDomainTwo.getDomainCode();
					}
					List<String[]> valueList = tmpMapCur.get(key);
					if (valueList == null) continue;

					for (int j = 0; j < valueList.size(); j++) {
						String[] vals = valueList.get(j);
						String val0 = handleName1(vals[0]);
						String val1 = handleName2(vals[1]);
						String val2 = handleName3(vals[2]);

						String caNo = oldCaMainNameMap.get(val0+"-"+cDomainCode);
						if (caNo == null) {
							StCaMainVo stCaMain = new StCaMainVo();
							stCaMain.setCaName(val0);
							stCaMain.setCaDesc(key);
							stCaMain.setDomainCode(cDomainCode);
							stCaMain.setCaNo(stCaMainService.caMainNo());
							stCaMain.setCreateUser(UserUtil.getUserCode());
							stCaMain.setVaild(StmConstans.DEFAULT_VALID);
							stCaMain.setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag);
							stCaMainService.save(stCaMain);
							oldCaMainNameMap.put(stCaMain.getCaName()+"-"+cDomainCode, stCaMain.getCaNo());
							caNo = stCaMain.getCaNo();
						}

						StComplianeItem stItem = new StComplianeItem();
						stItem.setCaNo(caNo);
						stItem.setComplianeNo(complianeNo);
						stItem.setComplianeItem(cdname+":\t\n"+val0);
						stItem.setComplianeAsk(val1);
						stItem.setCreatedUser("admin");
						stItem.setCreatedTime(new Date());
						stItem.setApplicableCode("0001");
						stItem.setCaName(key);
						stItem.setApproveFlag("1");
						stItem.setValid("1");
						stComplianeItemService.save(stItem);
						StComplianeItemCa itemCa = new StComplianeItemCa();
						itemCa.setCaNo(caNo);
						itemCa.setItemid(stItem.getId());
						stComplianeItemService.deleteItemCa(itemCa);
						addItemCa(itemCa);

					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return Result.OK("成功！");
	}

	/**
	 *  编辑
	 *
	 * @param stComplianeItem
	 * @return
	 */
	@AutoLog(value = "合规条目-编辑")
	  
	@RequiresPermissions("compliane.item:st_compliane_item:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody StComplianeItem stComplianeItem) {
		stComplianeItemService.updateById(stComplianeItem);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "合规条目-通过id删除")
	  
	@RequiresPermissions("compliane.item:st_compliane_item:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		stComplianeItemService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "合规条目-批量删除")
	  
	@RequiresPermissions("compliane.item:st_compliane_item:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.stComplianeItemService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "合规条目-通过id查询")
	  
	@GetMapping(value = "/queryById")
	public Result<StComplianeItem> queryById(@RequestParam(name="id",required=true) String id) {
		StComplianeItem stComplianeItem = stComplianeItemService.getById(id);
		if(stComplianeItem==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(stComplianeItem);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param stComplianeItem
    */
    @RequiresPermissions("compliane.item:st_compliane_item:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StComplianeItem stComplianeItem) {
        return super.exportXls(request, stComplianeItem, StComplianeItem.class, "合规条目");
    }

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

	private String handleName(String str) {
		String pattern = "^\\d{0,2}\\.{0,1}\\d{0,2}[\\.：、:]*\\s*";
		String result = str.replaceFirst(pattern, "");
		//System.out.println(str+"===" +result);
		return result;
	}
	private String handleName1(String str) {
		String pattern = "^检查项\\s*\\d{0,2}\\s*[：:]\\s*";
		String result = str.replaceFirst(pattern, "");
		//System.out.println(str+"===" +result);
		return result;
	}
	private String handleName2(String str) {
		String pattern = "^基本要求[：:]\\s*";
		String result = str.replaceFirst(pattern, "");
		//System.out.println(str+"===" +result);
		return result;
	}
	private String handleName3(String str) {
		String pattern = "^检查方法、步骤[:：]\\s*";
		String result = str.replaceFirst(pattern, "");
		//System.out.println(str+"===" +result);
		return result;
	}

	private String setRooDomain(String strDomainName) {
		String regex = "(\\d+)\\s*";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(strDomainName);
		System.out.println(strDomainName);
		int p = 0;
		if (matcher.find()) {
			String strNum = matcher.group(1);  // 获取第一个数字
			p = Integer.parseInt(strNum);
		}
		String domainCode="";
		if(p>12) {
			domainCode = "10";
		} else if(p>19) {
			domainCode = "11";
		} else {
			domainCode = "10";
		}
		return domainCode;
	}
}
