package org.jeecg.modules.stm.act.collection.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.stm.act.collection.entity.StCaMainRelCollection;
import org.jeecg.modules.stm.act.collection.mapper.StCaMainRelCollectionMapper;
import org.jeecg.modules.stm.act.collection.service.IStCaMainRelCollectionService;
import org.jeecg.modules.stm.act.collection.vo.CaRelCollectionVo;
import org.jeecg.modules.stm.act.collection.vo.StCaMainRelCollectionVo;
import org.jeecg.modules.stm.act.main.entity.StCaMain;
import org.jeecg.modules.stm.act.main.entity.StCaMainLable;
import org.jeecg.modules.stm.act.main.service.IStCaMainLableService;
import org.jeecg.modules.stm.act.main.service.IStCaMainService;
import org.jeecg.modules.stm.problem.entity.StProblem;
import org.jeecg.modules.stm.problem.service.IStProblemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.stm.base.domain.service.IStDomainService;
import org.jeecg.modules.stm.base.domain.vo.StDomainVo;
import org.jeecg.modules.stm.base.lable.entity.StLable;
import org.jeecg.modules.stm.base.lable.service.IStLableService;
import org.jeecg.modules.stm.compliane.item.entity.StComplianeItem;
import org.jeecg.modules.stm.compliane.item.service.IStComplianeItemService;
import org.jeecg.modules.stm.risk.event.entity.StRiskEvent;
import org.jeecg.modules.stm.risk.event.entity.StRiskEventLable;
import org.jeecg.modules.stm.risk.event.service.IStRiskEventLableService;
import org.jeecg.modules.stm.risk.event.service.IStRiskEventService;
import org.jeecg.modules.stm.utils.StmConstans;
import org.jeecg.modules.stm.utils.UserUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: st_ca_main_rel_collection
 * @Author: yzh
 * @Date:   2023-03-22
 * @Version: V1.0
 */
@Service
public class StCaMainRelCollectionServiceImpl extends ServiceImpl<StCaMainRelCollectionMapper, StCaMainRelCollection> implements IStCaMainRelCollectionService {

    @Autowired
    private IStCaMainService iStCaMainService;

    @Autowired
    private IStLableService iStLableService;

    @Autowired
    private IStComplianeItemService iStComplianeItemService;

    @Autowired
    private IStDomainService iStDomainService;

    @Autowired
    private IStProblemService iStProblemService;

    @Autowired
    private IStRiskEventService iStRiskEventService;

    @Autowired
    private IStRiskEventLableService iStRiskEventLableService;

    @Autowired
    private IStCaMainLableService iStCaMainLableService;

    private boolean checkRel(String caNo,String collectionNo){
        QueryWrapper<StCaMainRelCollection> queryWrapper = new QueryWrapper();
        queryWrapper.eq("ca_no",caNo);
        queryWrapper.eq("collection_no",collectionNo);
        StCaMainRelCollection stCaMainRelCollection = super.baseMapper.selectOne(queryWrapper);
        return stCaMainRelCollection!=null;
    }
    @Override
    public void save(CaRelCollectionVo caRelCollectionVo) {
        if(!caRelCollectionVo.valid()){
            throw new JeecgBootException("集合和控制活动关联信息不存在");
        }
        List<String> caNos = caRelCollectionVo.getCaNos();
        for(String caNo:caNos){
            if(this.checkRel(caNo,caRelCollectionVo.getCollectionNo())){
                throw new JeecgBootException("集合和控制活动关联信息已存在，请重选！");
            }
            StCaMainRelCollection entity = new StCaMainRelCollection();
            entity.setCollectionNo(caRelCollectionVo.getCollectionNo())
                    .setCaNo(caNo).setVaild(StmConstans.DEFAULT_VALID)
                    .setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag)
                    .setCreatedUser(UserUtil.getUserCode());
            super.save(entity);
        }
    }

    @Override
    public void addBycaIds(CaRelCollectionVo caRelCollectionVo) {
        if(!caRelCollectionVo.validIds()){
            throw new JeecgBootException("请选择控制活动和集合");
        }
        String type = caRelCollectionVo.getType();
        String collectionNo = caRelCollectionVo.getCollectionNo();
        QueryWrapper<StCaMainRelCollection> relCollectionQueryWrapper = new QueryWrapper<>();
        relCollectionQueryWrapper.eq("COLLECTION_NO",collectionNo);
        List<StCaMainRelCollection> collections = this.list(relCollectionQueryWrapper);
        boolean isRelFlag = true;
        if(CollectionUtils.isEmpty(collections)){
            isRelFlag = false;
        }
        List<String> caNos = collections.stream().map(StCaMainRelCollection::getCaNo).collect(Collectors.toList());
        if("camain".equals(type)){
            List<Serializable> ids = caRelCollectionVo.getCaIds();
            List<StCaMain> caMainList = iStCaMainService.listByIds(ids);
            if(CollectionUtils.isEmpty(caMainList)){
                return;
            }
            for(StCaMain stCaMain:caMainList){
                if(isRelFlag && caNos.contains(stCaMain.getCaNo())){
                    continue;
                }
                StCaMainRelCollection entity = new StCaMainRelCollection();
                entity.setCollectionNo(caRelCollectionVo.getCollectionNo())
                        .setCaNo(stCaMain.getCaNo()).setVaild(StmConstans.DEFAULT_VALID)
                        .setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag)
                        .setCreatedUser(UserUtil.getUserCode());
                super.save(entity);
            }
        }else if("complianeItem".equals(type)){
            List<Serializable> ids = caRelCollectionVo.getCaIds();
            List<StComplianeItem> complianeItems = iStComplianeItemService.listByIds(ids);
            if(CollectionUtils.isEmpty(complianeItems)){
                return;
            }
            for(StComplianeItem stComplianeItem:complianeItems){
                if(isRelFlag && caNos.contains(stComplianeItem.getCaNo())){
                    continue;
                }
                StCaMainRelCollection entity = new StCaMainRelCollection();
                entity.setCollectionNo(caRelCollectionVo.getCollectionNo())
                        .setCaNo(stComplianeItem.getCaNo()).setVaild(StmConstans.DEFAULT_VALID)
                        .setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag)
                        .setCreatedUser(UserUtil.getUserCode());
                super.save(entity);
            }
        }else if("problem".equals(type)){
            List<Serializable> ids = caRelCollectionVo.getCaIds();
            List<StProblem> stProblemList = iStProblemService.listByIds(ids);
            for(StProblem stProblem:stProblemList){
                if(isRelFlag && caNos.contains(stProblem.getCaNo())){
                    continue;
                }
                StCaMainRelCollection entity = new StCaMainRelCollection();
                entity.setCollectionNo(caRelCollectionVo.getCollectionNo())
                        .setCaNo(stProblem.getCaNo()).setVaild(StmConstans.DEFAULT_VALID)
                        .setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag)
                        .setCreatedUser(UserUtil.getUserCode());
                super.save(entity);
            }
        }else if("riskEvent".equals(type)){
            List<Serializable> ids = caRelCollectionVo.getCaIds();
            List<StRiskEvent> stRiskEvents = iStRiskEventService.listByIds(ids);
            List<String> riskEventNos = stRiskEvents.stream().map(StRiskEvent::getRiskEventNo).collect(Collectors.toList());
            QueryWrapper<StRiskEventLable> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("RISK_EVENT_NO",riskEventNos);
            List<StRiskEventLable> riskEventLables = iStRiskEventLableService.list(queryWrapper);
            List<String> lableCodes = riskEventLables.stream().map(StRiskEventLable::getLableCode).collect(Collectors.toList());
            QueryWrapper<StCaMainLable> stCaMainLableQueryWrapper = new QueryWrapper<>();
            stCaMainLableQueryWrapper.in("LABLE_CODE",lableCodes);
            List<StCaMainLable> stCaMainLableList = iStCaMainLableService.list(stCaMainLableQueryWrapper);
            for(StCaMainLable stCaMainLable:stCaMainLableList){
                if(isRelFlag && caNos.contains(stCaMainLable.getCaNo())){
                    continue;
                }
                StCaMainRelCollection entity = new StCaMainRelCollection();
                entity.setCollectionNo(caRelCollectionVo.getCollectionNo())
                        .setCaNo(stCaMainLable.getCaNo()).setVaild(StmConstans.DEFAULT_VALID)
                        .setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag)
                        .setCreatedUser(UserUtil.getUserCode());
                super.save(entity);
            }
        }
    }

    @Override
    public <E extends IPage<StCaMainRelCollection>> E page(E page, Wrapper<StCaMainRelCollection> queryWrapper) {
        IPage<StCaMainRelCollection> data = super.page(page, queryWrapper);
        List<StCaMainRelCollection> collections = data.getRecords();
        List<StCaMainRelCollection> records = new ArrayList<>();
        for(StCaMainRelCollection stCaMainRelCollection:collections){
            String caNo = stCaMainRelCollection.getCaNo();
            StCaMainRelCollectionVo stCaMainRelCollectionVo = new StCaMainRelCollectionVo();
            BeanUtils.copyProperties(stCaMainRelCollection,stCaMainRelCollectionVo);
            StCaMain stCaMain = iStCaMainService.queryByCaNo(caNo);
            if(stCaMain!=null) {
                stCaMainRelCollectionVo.setCaName(stCaMain.getCaName());
                StDomainVo stDomain = iStDomainService.queryEntityByCode(stCaMain.getDomainCode());
                if(stDomain!=null) {
                    stCaMainRelCollectionVo.setDomainName(stDomain.getPathDomainName());
                }else {
                    stCaMainRelCollectionVo.setDomainName("-");
                }
            }else{
                stCaMainRelCollectionVo.setCaName("-");
                stCaMainRelCollectionVo.setDomainName("-");
            }
            List<StCaMainLable> labledata = iStCaMainService.listLable(caNo);
            if(!CollectionUtils.isEmpty(labledata)){
                List<String> lableCodeList = labledata.stream().map(StCaMainLable::getLableCode).collect(Collectors.toList());
                stCaMainRelCollectionVo.setLableList(StringUtils.join(lableCodeList,","));
                List<StLable> lables = iStLableService.listByCods(lableCodeList);
                List<String> lableNames = lables.stream().map(StLable::getLableName).collect(Collectors.toList());
                if(!CollectionUtils.isEmpty(lableNames)) {
                    stCaMainRelCollectionVo.setLableNameList(lableNames);
                }else{
                    stCaMainRelCollectionVo.setLableNameList(Arrays.asList("-"));
                }
            }else{
                stCaMainRelCollectionVo.setLableNameList(Arrays.asList("-"));
            }

            records.add(stCaMainRelCollectionVo);
        }
        data.setRecords(records);
        return (E) data;
    }
}
