package org.jeecg.modules.stm.act.main.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 com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
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.mapper.StCaMainMapper;
import org.jeecg.modules.stm.act.main.service.IStCaMainLableService;
import org.jeecg.modules.stm.act.main.service.IStCaMainService;
import org.jeecg.modules.stm.act.main.vo.StCaMainLableVo;
import org.jeecg.modules.stm.act.main.vo.StCaMainVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.jeecg.modules.stm.base.domain.service.IStDomainService;
import org.jeecg.modules.stm.base.lable.service.IStLableService;
import org.jeecg.modules.stm.utils.QueryDomainParamsUtlis;
import org.jeecg.modules.stm.utils.QueryLableParamsUtlis;
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.Map;
import java.util.stream.Collectors;

/**
 * @Description: 控制活动
 * @Author: yzh
 * @Date:   2023-03-06
 * @Version: V1.0
 */
@Service
public class StCaMainServiceImpl extends ServiceImpl<StCaMainMapper, StCaMain> implements IStCaMainService {
    private static final String CAMAIN_NO_PRE = "ACT";
    private static final  int NO_SIZE = 5;

    @Autowired
    private IStCaMainLableService stCaMainLableService;

    @Autowired
    private IStLableService iStLableService;

    @Autowired
    private IStDomainService iStDomainService;

    @Autowired
    private IStCaMainLableService iStCaMainLableService;

    public String caMainNo(){
        QueryWrapper<StCaMain> wapper = new QueryWrapper();
        wapper.orderByDesc("ca_no");
        wapper.last("limit 1");
        StCaMain noUpper = super.baseMapper.selectOne(wapper);
        if(noUpper == null) {
            return CAMAIN_NO_PRE+StringUtils.leftPad("1",NO_SIZE,"0");
        }else{
            // 如果不为空+1
            int no  = Integer.valueOf(noUpper.getCaNo().replace(CAMAIN_NO_PRE,""))+1;
            String str = ""+no;
            return  CAMAIN_NO_PRE+StringUtils.leftPad(str,NO_SIZE,"0");
        }
    }

    private void checkName(StCaMain entity, boolean isSave){
        if(entity==null){
            return;
        }
        QueryWrapper<StCaMain> wapper = new QueryWrapper<>();
        wapper.eq("CA_NAME",entity.getCaName());
        if(!isSave){
            wapper.ne("CA_NO",entity.getCaNo());
        }
        long count = super.count(wapper);
        if(count>0){
            throw new JeecgBootException("控制活动名称已存在");
        }
    }

    @Override
    public boolean save(StCaMain entity) {
        //checkName(entity,true);
        StCaMainVo stCaMainVo = (StCaMainVo) entity;
        String lableCodeList = stCaMainVo.getLableList();
        StCaMain stCaMain = new StCaMain();
        BeanUtils.copyProperties(entity,stCaMain);
        stCaMain.setCaNo(caMainNo());
        stCaMain.setCreateUser(UserUtil.getUserCode());
        stCaMain.setVaild(StmConstans.DEFAULT_VALID);
        stCaMain.setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag);
        if(lableCodeList!=null) {
            savelable(stCaMain,lableCodeList);
        }
        return super.save(stCaMain);
    }
    public void savelable(StCaMain entity,String lableCodeList){
        String caNo = entity.getCaNo();
        String [] lableCodes = lableCodeList.split(",");
        for(String item:lableCodes) {
            StCaMainLable stCaMainLable = new StCaMainLable();
            stCaMainLable.setCaNo(caNo);
            stCaMainLable.setLableCode(item);
            stCaMainLable.setVaild(StmConstans.DEFAULT_VALID);
            stCaMainLable.setCreatedUser(entity.getCreateUser());
            stCaMainLable.setUpdatedUser(entity.getUpdatedUser());
            stCaMainLableService.save(stCaMainLable);
        }
    }
    @Override
    public boolean updateById(StCaMain entity) {
        checkName(entity,false);
        StCaMainVo stCaMainVo = (StCaMainVo) entity;
        String lableCodeList = stCaMainVo.getLableList();
        StCaMain stCaMain = new StCaMain();
        BeanUtils.copyProperties(entity,stCaMain);
        stCaMain.setUpdatedUser(UserUtil.getUserCode());
        stCaMain.setVaild(StmConstans.DEFAULT_VALID);
        stCaMain.setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag);
        updateLabel(stCaMain,lableCodeList);
        return super.updateById(stCaMain);
    }
    public void deleteLabel(StCaMain entity){
        QueryWrapper<StCaMainLable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CA_NO",entity.getCaNo());
        stCaMainLableService.remove(queryWrapper);
    }
    public void updateLabel(StCaMain entity,String lableCodeList){
        deleteLabel(entity);
        savelable(entity,lableCodeList);
    }
    @Override
    public List<StCaMainLable> listLable(String caNo){
        QueryWrapper<StCaMainLable> wapper = new QueryWrapper();
        wapper.eq("CA_NO",caNo);
        return stCaMainLableService.list(wapper);
    }

//    @Override
//    public <E extends IPage<StCaMain>> E page(E page, Wrapper<StCaMain> queryWrapper) {
//        IPage<StCaMain> pageList = super.page(page, queryWrapper);
//        List<StCaMain> voList = new ArrayList<>();
//        List<StCaMain> list = pageList.getRecords();
//        for(StCaMain stCaMain:list){
//            StCaMainVo stCaMainVo = new StCaMainVo();
//            BeanUtils.copyProperties(stCaMain,stCaMainVo);
//            // 查询标签
//            List<StCaMainLable> data = listLable(stCaMain.getCaNo());
//            if(!CollectionUtils.isEmpty(data)){
//              List<String> lableCodeList = data.stream().map(StCaMainLable::getLableCode).collect(Collectors.toList());
//                stCaMainVo.setLableList(StringUtils.join(lableCodeList,","));
//                List<StLable> lables = iStLableService.listByCods(lableCodeList);
//                List<String> lableNames = lables.stream().map(StLable::getLableName).collect(Collectors.toList());
//                List<String> lableCodes = lables.stream().map(StLable::getLableCode).collect(Collectors.toList());
//                if(!CollectionUtils.isEmpty(lableNames)) {
//                    stCaMainVo.setLableNameList(lableNames);
//                    stCaMainVo.setLableCodeList(lableCodes);
//                }else {
//                    stCaMainVo.setLableNameList(Arrays.asList("-"));
//                    stCaMainVo.setLableCodeList(Arrays.asList("-"));
//                }
//            }else{
//                stCaMainVo.setLableNameList(Arrays.asList("-"));
//                stCaMainVo.setLableCodeList(Arrays.asList("-"));
//            }
//            StDomainVo stDomain = iStDomainService.queryEntityByCode(stCaMainVo.getDomainCode());
//            if(stDomain!=null) {
//                stCaMainVo.setDomainName(stDomain.getPathDomainName());
//            }else{
//                stCaMainVo.setDomainName("-");
//            }
//            voList.add(stCaMainVo);
//        }
//        pageList.setRecords(voList);
//        return (E) pageList;
//    }


    @Override
    public <E extends IPage<StCaMain>> E page(E page, Wrapper<StCaMain> queryWrapper) {
        IPage<StCaMain> pageList = super.page(page, queryWrapper);
        List<StCaMain> list = pageList.getRecords();
        if(list==null||list.size()==0) {
            return (E) pageList;
        }
        List<String> listDomainCode = new ArrayList<>();
        List<StCaMain> retList = new ArrayList<>();
        List<String> listCaNo = new ArrayList<>();
        StCaMainLableVo lableVo = new StCaMainLableVo();
        for(StCaMain stCaMain:list) {
            listDomainCode.add(stCaMain.getDomainCode());
            listCaNo.add(stCaMain.getCaNo());
        }

        Map<String, String> codeNameMap = null;
        if(listDomainCode.size()>0) {
            codeNameMap =iStDomainService.getAllParentCode(listDomainCode);
        }

        Map<String,StCaMainLableVo> lableVoMap = null;
        if(listCaNo.size()>0) {
            lableVo.setCaNoList(listCaNo);
            lableVoMap = iStCaMainLableService.queryLables(lableVo);
        }

        for(StCaMain stCaMain:list) {
            StCaMainVo stCaMainVo = new StCaMainVo();
            BeanUtils.copyProperties(stCaMain,stCaMainVo);
            retList.add(stCaMainVo);
            if(codeNameMap!=null&&codeNameMap.size()>0) {
                String strDomainCode = stCaMainVo.getDomainCode();
                if(strDomainCode!=null) {
                    String strDomain = codeNameMap.get(strDomainCode);
                    if(strDomain!=null) {
                        stCaMainVo.setDomainName(strDomain);
                    }

                }
            }
            if(lableVoMap!=null) {
                String strCaNo = stCaMainVo.getCaNo();
                if(strCaNo!=null&&!strCaNo.equals("")) {
                    String lableNames = lableVoMap.get(strCaNo)!=null?lableVoMap.get(strCaNo).getLableNames():null;
                    String lableCodes = lableVoMap.get(strCaNo)!=null?lableVoMap.get(strCaNo).getLableCodes():null;
                    if(lableNames!=null&&lableNames.length()>0) {
                        List lableNameList = Arrays.stream(lableNames.split(",")).collect(Collectors.toList());
                        stCaMainVo.setLableNameList(lableNameList);
                    }
                    if(lableCodes!=null&&lableCodes.length()>0) {
                        List lableCodeList = Arrays.stream(lableCodes.split(",")).collect(Collectors.toList());
                        stCaMainVo.setLableCodeList(lableCodeList);
                        stCaMainVo.setLableList(lableCodes);
                    }

                }

            }
        }

        pageList.setRecords(retList);
        return (E) pageList;
    }


    @Override
    public boolean removeById(Serializable id) {
        StCaMain stCaMain = this.baseMapper.selectById(id);
        if(stCaMain!=null){
           this.deleteLabel(stCaMain);
        }
        return super.removeById(id);
    }

    @Override
    public IPage<StCaMain> defPage(StCaMain stCaMain, Integer pageNo, Integer pageSize, Map<String, String[]> parameterMap) {
        QueryWrapper<StCaMain> queryWrapper = QueryGenerator.initQueryWrapper(stCaMain, parameterMap);
        List<String> caMainCodes = null;
        List<String> labelCodes = QueryLableParamsUtlis.getLableCodes(parameterMap);
        if(!CollectionUtils.isEmpty(labelCodes)){
            if(labelCodes.size()==1 && "notExist".equals(labelCodes.get(0))){
                caMainCodes = labelCodes;
            }else {
                caMainCodes = stCaMainLableService.listByLabelCodes(labelCodes);
            }
        }
        if(!CollectionUtils.isEmpty(caMainCodes)){
            queryWrapper.in("CA_NO",caMainCodes);
        }
        String domainCode = QueryDomainParamsUtlis.getDomainCode(parameterMap);
        if(!StringUtils.isEmpty(domainCode)){
            queryWrapper.likeRight("DOMAIN_CODE",domainCode);
        }
//        List<String> isFilteredCaNo = QueryCaManParamsUtlis.getFilterCaNos(parameterMap);
//        if(!CollectionUtils.isEmpty(isFilteredCaNo)){
//            queryWrapper.notIn("CA_NO",isFilteredCaNo);
//        }
        Page<StCaMain> page = new Page<StCaMain>(pageNo, pageSize);
        return this.page(page, queryWrapper);
    }

    @Override
    public StCaMain queryByCaNo(String caNo) {
        QueryWrapper<StCaMain> wapper = new QueryWrapper();
        wapper.eq("CA_NO",caNo);
        return super.baseMapper.selectOne(wapper);
    }

}
