package org.stm.audit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.stm.audit.entity.AuditActRelOthers;
import org.stm.audit.entity.AuditItemRelCheck;
import org.stm.audit.service.*;
import org.stm.base.lable.entity.StLable;
import org.stm.base.lable.service.IStLableService;
import org.stm.utils.StmConstans;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Api(tags="审计信息管理")
@RestController
@RequestMapping("/audit")
@Slf4j
public class AuditController {

    @Autowired
    private IAuditActRelOthersService stActRelOthersService;
    @Autowired
    private IAuditLabelRelLibService stLabelRelLibService;
    @Autowired
    private IStLableService stLableService;
    @Autowired
    private IAuditComplianeItemService auditComplianeItemService;
    @Autowired
    private IAuditItemRelCheckService auditItemRelCheckService;
    @Autowired
    private IAuditFileContentCategoriesService auditFileContentCategoriesService;

    @GetMapping(value = "/queryActRelates")
    public Result<List<Map<String,Object>>> queryActRelates(AuditActRelOthers actRelOthers, HttpServletRequest req) {

        Integer actId = actRelOthers.getActId();
        Integer  tp = actRelOthers.getTp();
        List<Integer> listId = null;
        if(actId!=null){
            if(tp==1) {
                // 查询控制项对应的检查方法
                List<Integer> checkIdList = getExistRelation(5, actId);
                if (checkIdList == null || checkIdList.size() == 0) {
                    return Result.OK(new ArrayList<>());
                }
                listId = queryItemByCheckIds(checkIdList);

            } else {
                listId = getExistRelation(tp, actId);
                if (listId == null || listId.size() == 0) {
                    return Result.OK(new ArrayList<>());
                }
            }

            if(listId==null || listId.isEmpty()){
                return Result.OK(new ArrayList<>());
            }
        }
        List<Map<String,Object>> retList = new ArrayList<>();

        if(tp==1) {
            retList =  stActRelOthersService.queryActAndComplianeItems(listId);
            setLables(retList);
            setComplianeItemActNames(retList);
            setCgrp(retList);
        } else if(tp==2) {
            retList =  stActRelOthersService.queryActAndInnerStrategyItems(listId);
            setLables(retList);
            setActNames(retList,tp);
        } else if(tp==3) {
            retList =  stActRelOthersService.queryActAndInnerControlItems(listId);
            setLables(retList);
            setInnerOrderActNames(retList, StmConstans.Audit_TP_INNER_ORDER_CHECK_METHOD);
        } else if(tp==4) {
            if(actRelOthers.getId()!=null&&actRelOthers.getId()!=0){
                listId = new ArrayList<>();
                listId.add(actRelOthers.getId());
            }
            retList =  stActRelOthersService.queryActAndProblemItems(listId);
            setLables(retList);
            setActNames(retList,tp);

            if(actRelOthers.getId()!=null&&actRelOthers.getId()!=0){
                listId=null;
            }
        } else if(tp==5) {
            retList =  stActRelOthersService.queryActAndCheckItems(listId);
            setLables(retList);
            setActNames(retList,tp);
        } else if(tp==6) {
            retList =  stActRelOthersService.queryActAndRiskItems(listId);
            setLables(retList);
        } else if(tp==7) {
            retList =  stActRelOthersService.queryActAndPracticeItems(listId);
            setLables(retList);
        } else if(tp==8) {
            retList =  stActRelOthersService.queryActAndRiskScenarioItems(listId);
            setLables(retList);
        } else if(tp==9) {
            retList =  stActRelOthersService.queryAllAct();
            setLables(retList);
        } else if(tp==10) {
            retList =  stActRelOthersService.queryAllLabels();
        }

        return Result.OK(retList);
    }

    @GetMapping(value = "/saveActRelations")
    public Result<String> saveActRelations(AuditActRelOthers actRelOthers, @RequestParam String tids,
                                           HttpServletRequest req) {
        Integer actId = actRelOthers.getActId();
        Integer  tp = actRelOthers.getTp();
        if(tids!=null && tids.length()>0) {
            String[] tidAry = tids.split(",");
            List<AuditActRelOthers> saveList = new ArrayList<>();
            for(String tid : tidAry) {
                AuditActRelOthers actRel = new AuditActRelOthers();
                actRel.setTp(tp);
                actRel.setActId(actId);
                actRel.setTid(Integer.parseInt(tid));
                saveList.add(actRel);
            }
            deleteActRel(tp,tidAry);
            stActRelOthersService.saveBatch(saveList);
        }
        return Result.OK("保存成功");
    }


    @GetMapping(value = "/saveBatchActRelations")
    public Result<String> saveBatchActRelations(@RequestParam Integer tp,
            @RequestParam String actIds, @RequestParam String tids, HttpServletRequest req) {

        String[] actIdsAry = actIds.split(",");
        String[] tidAry = tids.split(",");
        List<AuditActRelOthers> saveList = new ArrayList<>();
        for(int i=0;i<actIdsAry.length;i++) {
            if (tids != null && tids.length() > 0) {
                for (String tid : tidAry) {
                    AuditActRelOthers actRel = new AuditActRelOthers();
                    actRel.setTp(tp);
                    actRel.setActId(Integer.parseInt(actIdsAry[i]));
                    actRel.setTid(Integer.parseInt(tid));
                    saveList.add(actRel);
                }

            }
        }
        deleteActRel(tp,tidAry);
        stActRelOthersService.saveBatch(saveList);

        return Result.OK("保存成功");
    }

    @GetMapping(value = "/deleteActRel")
    public Result<String> deleteActRel(@RequestParam Integer tp,@RequestParam Integer actId,@RequestParam String ids, HttpServletRequest req) {
        String[] idAry = ids.split(",");
        QueryWrapper<AuditActRelOthers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tp",tp).eq("act_id",actId).in("tid",idAry);
        stActRelOthersService.remove(queryWrapper);
        return Result.OK("删除成功");
    }

    private Result<String> deleteActRel(Integer tp,String[] ids) {
        QueryWrapper<AuditActRelOthers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tp",tp).in("tid",ids);
        stActRelOthersService.remove(queryWrapper);
        return Result.OK("删除成功");
    }

    private List<Integer> getExistRelation(Integer tp,Integer actId) {
        List<Integer> idList = new ArrayList<>();
        QueryWrapper<AuditActRelOthers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tp",tp).eq("act_id",actId);
        List<AuditActRelOthers> list = stActRelOthersService.list(queryWrapper);
        for(AuditActRelOthers rel:list){
            idList.add(rel.getTid());
        }
        return idList;
    }


    private void setLables( List<Map<String,Object>> retList) {
        List<Integer> retListId = new ArrayList<>();
        for (Map<String, Object> tmap : retList) {
            retListId.add(new Integer(tmap.get("id").toString()));
        }
        if (retListId.size() > 0) {
            Map<Integer, StringBuffer> idLabelMap = stLabelRelLibService.getLablesByTids(retListId);
            for (Map<String, Object> tmap : retList) {
                Integer tid = new Integer(tmap.get("id").toString());
                StringBuffer tempStr = idLabelMap.get(tid);
                if(tempStr!=null&&tempStr.length()>0) {
                    int p = tempStr.indexOf("|");
                    tmap.put("labelNames", tempStr.substring(0,p));
                    tmap.put("labels", tempStr.substring(p+1));
                }
            }
        }
    }


    private void setInnerOrderActNames( List<Map<String,Object>> retList,Integer tp) {
        List<Integer> retListId = new ArrayList<>();
        for (Map<String, Object> tmap : retList) {
            if(tmap.get("checkid")!=null) {
                retListId.add(new Integer(tmap.get("checkid").toString()));
            }
        }
        if (retListId.size() > 0) {
            Map<Integer, String> idActMap = stActRelOthersService.queryAllActByTids(retListId,tp);
            for (Map<String, Object> tmap : retList) {
                if(tmap.get("checkid")==null) {
                    continue;
                }
                Integer tid = new Integer(tmap.get("checkid").toString());
                String tempStr = idActMap.get(tid);
                if(tempStr!=null) {
                    int p = tempStr.indexOf("|");
                    tmap.put("caName", tempStr.substring(0,p));
                    tmap.put("actIds", tempStr.substring(p+1));
                }
            }
        }
    }

    private void setActNames( List<Map<String,Object>> retList,Integer tp) {
        List<Integer> retListId = new ArrayList<>();
        for (Map<String, Object> tmap : retList) {
            retListId.add(new Integer(tmap.get("id").toString()));
        }
        if (retListId.size() > 0) {
            Map<Integer, String> idActMap = stActRelOthersService.queryAllActByTids(retListId,tp);
            for (Map<String, Object> tmap : retList) {
                Integer tid = new Integer(tmap.get("id").toString());
                String tempStr = idActMap.get(tid);
                if(tempStr!=null) {
                    int p = tempStr.indexOf("|");
                    tmap.put("caName", tempStr.substring(0,p));
                    tmap.put("actIds", tempStr.substring(p+1));
                }
            }
        }
    }



    @GetMapping(value = "/queryLabelByCodes")
    public Result<List<StLable>> queryLabelByCodes(String labelCodes, HttpServletRequest req) {
        QueryWrapper<StLable> queryWrapper = new QueryWrapper<>();
        if(labelCodes==null){
            return Result.OK(new ArrayList<>());
        }
        queryWrapper.in("lable_code",labelCodes.split(","));
        List<StLable> list = stLableService.list(queryWrapper);
        return Result.OK(list);
    }


    private void setComplianeItemActNames( List<Map<String,Object>> retList) {
        List<Integer> retListId = new ArrayList<>();
        for (Map<String, Object> tmap : retList) {
            Integer tmpId = new Integer(tmap.get("id").toString());
            if(retListId.contains(tmpId)) continue;
            retListId.add(tmpId);
        }
        if (retListId.size() > 0) {
            Map<Integer, Map<String,String>> idActMap = auditComplianeItemService.queryAllActForItems(retListId);
            for (Map<String, Object> tmap : retList) {
                Integer tid = new Integer(tmap.get("id").toString());
                Map<String,String> tempMap = idActMap.get(tid);
                if(tempMap!=null) {
                    tmap.put("caName", tempMap.get("caNames"));
                    tmap.put("actIds", tempMap.get("actIds"));
                    tmap.put("checkIds", tempMap.get("checkIds"));
                }
            }
        }
    }

    private List<Integer> queryItemByCheckIds(List<Integer> checkIds) {
        QueryWrapper<AuditItemRelCheck> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("checkid",checkIds);
        List<AuditItemRelCheck> list = auditItemRelCheckService.list(queryWrapper);
        List<Integer> itemIdList = new ArrayList<>();
        for(AuditItemRelCheck check: list) {
            itemIdList.add(check.getCitemid());
        }
        return itemIdList;
    }

    private void setCgrp( List<Map<String,Object>> retList) {
        if(retList==null||retList.size()==0) return;
        //Integer fileId = Integer.valueOf(retList.get(0).get("fileId").toString());

        Map<Integer, String> idActMap = auditFileContentCategoriesService.queryAllDataByFileId(null);
        for (Map<String, Object> tmap : retList) {
            if(tmap.get("cgrp")!=null&&!tmap.get("cgrp").equals("")) {
                Integer tid = new Integer(tmap.get("cgrp").toString());
                String tempStr = idActMap.get(tid);
                if (tempStr != null) {
                    tmap.put("cgrpName", tempStr);
                }
            }
        }
    }

}




