package org.stm.audit.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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.stm.audit.entity.*;
import org.stm.audit.service.*;
import org.stm.utils.StmConstans;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: audit_compliane_item
 * @Author: jeecg-boot
 * @Date:   2024-08-23
 * @Version: V1.0
 */
@Api(tags="audit_compliane_item")
@RestController
@RequestMapping("/audit/auditComplianeItem")
@Slf4j
public class AuditComplianeItemController extends JeecgController<AuditComplianeItem, IAuditComplianeItemService> {
	@Autowired
	private IAuditComplianeItemService auditComplianeItemService;
	@Autowired
	private IAuditLabelRelLibService stLabelRelLibService;
	@Autowired
	private IAuditActRelOthersService stActRelOthersService;
	@Autowired
	private IAuditItemRelCheckService auditItemRelCheckService;
	@Autowired
	private IAuditCheckMethodService auditCheckMethodService;
	@Autowired
	private IAuditFileContentCategoriesService auditFileContentCategoriesService;
	@Autowired
	private IAuditCheckMethodItemService auditCheckMethodItemService;

	/**
	 * 分页列表查询
	 *
	 * @param auditComplianeItem
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "audit_compliane_item-分页列表查询")
	@ApiOperation(value="分页列表查询", notes="分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AuditComplianeItem>> queryPageList(AuditComplianeItem auditComplianeItem,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AuditComplianeItem> queryWrapper = QueryGenerator.initQueryWrapper(auditComplianeItem, req.getParameterMap());
		Page<AuditComplianeItem> page = new Page<AuditComplianeItem>(pageNo, pageSize);
		IPage<AuditComplianeItem> pageList = auditComplianeItemService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	@ApiOperation(value="分页列表查询", notes="分页列表查询")
	@GetMapping(value = "/listAll")
	public Result<List<AuditComplianeItem>> queryAllComplianes(AuditComplianeItem auditComplianeItem, HttpServletRequest req) {
		QueryWrapper<AuditComplianeItem> queryWrapper = QueryGenerator.initQueryWrapper(auditComplianeItem, req.getParameterMap());
		List<AuditComplianeItem> list = auditComplianeItemService.list(queryWrapper);
		return Result.OK(list);
	}
	
	/**
	 *   添加
	 *
	 * @param auditComplianeItem
	 * @return
	 */
	@AutoLog(value = "添加")
	@ApiOperation(value="添加", notes="添加")
	@PostMapping(value = "/add")
	public Result<AuditComplianeItem> add(@RequestBody AuditComplianeItem auditComplianeItem) {
		if(getComplianeItemNameIsExist(auditComplianeItem)) {
			return  Result.error("条目名称和内容已经村存在");
		}
		setSgrpPath(auditComplianeItem);
		auditComplianeItemService.save(auditComplianeItem);
		String labels = auditComplianeItem.getLabels();
		Integer tid =  auditComplianeItem.getId();
		if(labels!=null&&!labels.equals("")){
			stLabelRelLibService.saveLabelRel(labels,tid, StmConstans.Audit_TP_COMPLIANE_ITEM);
		}

		List<AuditCheckMethod> checkMethods = auditComplianeItem.getCheckMethods();
		if(checkMethods!=null){
			//checMethodExist(checkMethods);
			auditCheckMethodService.saveOrUpdateBatch(checkMethods);
			List<AuditItemRelCheck> auditItemRelCheckList = new ArrayList<>();
			Integer itemId = auditComplianeItem.getId();
			List<AuditActRelOthers> actRelOthers = new ArrayList<>();
			List<AuditCheckMethodItem> allCmItems = new ArrayList<>();
			List<Integer> checkIds = new ArrayList<>();
			for(AuditCheckMethod method : checkMethods){
				AuditItemRelCheck auditItemRelCheck = new AuditItemRelCheck();
				auditItemRelCheck.setCheckid(method.getId());
				auditItemRelCheck.setCitemid(itemId);
				auditItemRelCheckList.add(auditItemRelCheck);
				checkIds.add(method.getId());
				String actIds = method.getActIds();
				if(actIds!=null&&!actIds.equals("")) {
					stActRelOthersService.setActRelations(actRelOthers,actIds,method.getId(),StmConstans.Audit_TP_CHECK_METHOD);
				}
				List<AuditCheckMethodItem> cmItems = method.getCheckMethodItems();
				if(cmItems!=null&&cmItems.size()>0) {
					for(AuditCheckMethodItem item:cmItems) {
						item.setCheckid(method.getId());
						allCmItems.add(item);
					}
				}
			}

			if(actRelOthers.size()>0) {
				stActRelOthersService.saveBatch(actRelOthers);
			}
			if(auditItemRelCheckList.size()>0) {
				auditItemRelCheckService.saveBatch(auditItemRelCheckList);
			}
			if(allCmItems.size()>0) {
				auditCheckMethodItemService.saveBatch(allCmItems);
			}

		}
		return Result.OK(auditComplianeItem);
	}
	
	/**
	 *  编辑
	 *
	 * @param auditComplianeItem
	 * @return
	 */
	@AutoLog(value = "编辑")
	@ApiOperation(value="编辑", notes="编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<AuditComplianeItem> edit(@RequestBody AuditComplianeItem auditComplianeItem) {

		if(getComplianeItemNameIsExist(auditComplianeItem)) {
			return  Result.error("条目名称和内容已经村存在!");
		}
		setSgrpPath(auditComplianeItem);
		auditComplianeItemService.updateById(auditComplianeItem);
		Integer complianeItemId =  auditComplianeItem.getId();

		String labels = auditComplianeItem.getLabels();

		stLabelRelLibService.deleteLabelRel(complianeItemId, StmConstans.Audit_TP_COMPLIANE_ITEM);
		if(labels!=null && labels.trim().length()>0) {
			stLabelRelLibService.saveLabelRel(labels, complianeItemId, StmConstans.Audit_TP_COMPLIANE_ITEM);
		}

		List<AuditCheckMethod> checkMethods = auditComplianeItem.getCheckMethods();
		if(checkMethods!=null&&checkMethods.size()>0){
			checkAndDeleteCheckMethod(checkMethods,complianeItemId);
			auditCheckMethodService.saveOrUpdateBatch(checkMethods);
			List<AuditItemRelCheck> auditItemRelCheckList = new ArrayList<>();
			List<AuditActRelOthers> actRelOthers = new ArrayList<>();
			List<AuditCheckMethodItem> allCmItems = new ArrayList<>();
			List<Integer> checkIds = new ArrayList<>();

			for(AuditCheckMethod method : checkMethods){
				AuditItemRelCheck auditItemRelCheck = new AuditItemRelCheck();
				auditItemRelCheck.setCheckid(method.getId());
				auditItemRelCheck.setCitemid(complianeItemId);
				auditItemRelCheckList.add(auditItemRelCheck);
				checkIds.add(method.getId());
				String actIds = method.getActIds();
				if(actIds!=null&&!actIds.equals("")) {
					stActRelOthersService.setActRelations(actRelOthers,actIds,method.getId(),StmConstans.Audit_TP_CHECK_METHOD);
				}

				List<AuditCheckMethodItem> cmItems = method.getCheckMethodItems();
				if(cmItems!=null&&cmItems.size()>0) {
					for(AuditCheckMethodItem item:cmItems) {
						item.setCheckid(method.getId());
						allCmItems.add(item);
					}
				}
			}

			deleteItemAndCheckRel(checkIds,complianeItemId);
			if(auditItemRelCheckList.size()>0) {
				auditItemRelCheckService.saveOrUpdateBatch(auditItemRelCheckList);
			}

			deleteActAndCheckRel(checkIds);
			if(actRelOthers.size()>0) {
				stActRelOthersService.saveOrUpdateBatch(actRelOthers);
			}

			deleteCheckItms(checkIds);
			if(allCmItems.size()>0) {
				auditCheckMethodItemService.saveOrUpdateBatch(allCmItems);
			}

		}
		return Result.OK(auditComplianeItem);
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "通过id删除")
	@ApiOperation(value="通过id删除", notes="通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		auditComplianeItemService.removeById(id);
		List<String> idList = new ArrayList<>();
		idList.add(id);
		deleteOtherTable(idList);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "批量删除")
	@ApiOperation(value="批量删除", notes="批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		this.auditComplianeItemService.removeByIds(idList);
		deleteOtherTable(idList);
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "audit_compliane_item-通过id查询")
	@ApiOperation(value="通过id查询", notes="通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AuditComplianeItem> queryById(@RequestParam(name="id",required=true) String id) {
		AuditComplianeItem auditComplianeItem = auditComplianeItemService.getById(id);
		if(auditComplianeItem==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(auditComplianeItem);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param auditComplianeItem
    */
    @RequiresPermissions("audit:audit_compliane_item:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AuditComplianeItem auditComplianeItem) {
        return super.exportXls(request, auditComplianeItem, AuditComplianeItem.class, "audit_compliane_item");
    }

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

	private boolean getComplianeItemNameIsExist(AuditComplianeItem item) {
		QueryWrapper<AuditComplianeItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("item",item.getItem()).eq("content",item.getContent());
		if(item.getId()!=null) {
			queryWrapper.ne("id",item.getId());
		}
		List<AuditComplianeItem>  list  = auditComplianeItemService.list(queryWrapper);
		if(list.size()>0) {
			return  true;
		} else {
			return  false;
		}
 	}

	private void checkMethodExist(List<AuditCheckMethod> checkMethods) {
		List<String> listContent = new ArrayList<>();
		for(AuditCheckMethod method : checkMethods) {
			listContent.add(method.getContent());
		}
		QueryWrapper<AuditCheckMethod> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("content",listContent);
		List<AuditCheckMethod> retList = auditCheckMethodService.list(queryWrapper);
		if(retList!=null&&retList.size()>0) {
			for (AuditCheckMethod method : retList) {
				for (int i=0;i< checkMethods.size(); i++){
					AuditCheckMethod method2 = checkMethods.get(i);
					if(method.getContent().equals(method2.getContent())) {
						method.setContent(method2.getContent());
						method.setDes(method2.getDes());
						method.setActIds(method2.getActIds());
						break;
					}
				}
			}
		}
	}
	private void deleteItemAndCheckRel(List<Integer> checkids,Integer citemid) {
		AuditItemRelCheck relCheck = new AuditItemRelCheck();
		QueryWrapper<AuditItemRelCheck> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("citemid",citemid).in("checkid",checkids);
		auditItemRelCheckService.remove(queryWrapper);
	}

	private void deleteActAndCheckRel(Integer chkid) {
		AuditItemRelCheck relCheck = new AuditItemRelCheck();
		QueryWrapper<AuditActRelOthers> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("tid",chkid).eq("tp",StmConstans.Audit_TP_CHECK_METHOD);
		stActRelOthersService.remove(queryWrapper);
	}

	private void deleteActAndCheckRel(List<Integer> chkidList) {
		AuditItemRelCheck relCheck = new AuditItemRelCheck();
		QueryWrapper<AuditActRelOthers> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("tid",chkidList).eq("tp",StmConstans.Audit_TP_CHECK_METHOD);
		stActRelOthersService.remove(queryWrapper);
	}

	private void setSgrpPath(AuditComplianeItem auditComplianeItem) {
		String crgpid = auditComplianeItem.getCgrp();
		if(crgpid!=null) {
			Integer fileId = auditComplianeItem.getFileId();
			AuditFileContentCategories cat = auditFileContentCategoriesService.getById(crgpid);
			String strPath = auditFileContentCategoriesService.queryFullPathNodeId(cat,fileId);
			auditComplianeItem.setCgrpPath(strPath);
		} else {
			auditComplianeItem.setCgrpPath("");
		}
	}

	private void deleteOtherTable(List<String> itemIdList){
		//删除与检查方法的关系表
		QueryWrapper<AuditItemRelCheck> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("citemid",itemIdList);
		List<AuditItemRelCheck> relCheckList =  auditItemRelCheckService.list(queryWrapper);
		List<Integer> checkIdList = new ArrayList<>();
		for(AuditItemRelCheck check:relCheckList) {
			checkIdList.add(check.getCheckid());

		}
		if(checkIdList.size()>0) {
			auditCheckMethodService.removeBatchByIds(checkIdList);
			auditItemRelCheckService.remove(queryWrapper);
			QueryWrapper<AuditCheckMethodItem> queryCheckWrapper = new QueryWrapper<>();
			queryCheckWrapper.in("checkid",checkIdList);
			auditCheckMethodItemService.remove(queryCheckWrapper);
		}
	}



	private void deleteCheckItms(List<Integer> checkidList) {
		QueryWrapper<AuditCheckMethodItem> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("checkid",checkidList);
		auditCheckMethodItemService.remove(queryWrapper);
	}

	private void checkAndDeleteCheckMethod(List<AuditCheckMethod> checkMethods,Integer itemid) {
		QueryWrapper<AuditItemRelCheck> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("citemid",itemid);
		List<AuditItemRelCheck> relCheckList =  auditItemRelCheckService.list(queryWrapper);
		List<Integer> deleteCheckId = new ArrayList<>();

		for(AuditItemRelCheck refCheck:relCheckList) {
			deleteCheckId.add(refCheck.getCheckid());
		}

		for(AuditCheckMethod method:checkMethods) {
			Integer checkid = method.getId();
			if(checkid!=null) {
				if(deleteCheckId.contains(checkid)) {
					deleteCheckId.remove(checkid);
				}
			}
		}

		if(deleteCheckId.size()>0) {
			auditCheckMethodService.removeBatchByIds(deleteCheckId);
			auditItemRelCheckService.remove(queryWrapper);
			QueryWrapper<AuditCheckMethodItem> queryCheckWrapper = new QueryWrapper<>();
			queryCheckWrapper.in("checkid",deleteCheckId);
			auditCheckMethodItemService.remove(queryCheckWrapper);
		}
	}

}
