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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.metric.entity.StCaMainMetric;
import org.jeecg.modules.stm.act.metric.entity.StMetric;
import org.jeecg.modules.stm.act.metric.mapper.StMetricMapper;
import org.jeecg.modules.stm.act.metric.service.IStCaMainMetricService;
import org.jeecg.modules.stm.act.metric.service.IStMetricService;
import org.jeecg.modules.stm.act.metric.vo.StCaMainMetricVo;
import org.jeecg.modules.stm.act.metric.vo.StMetricVo;
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.utils.StmConstans;
import org.jeecg.modules.stm.utils.UserUtil;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: st_metric
 * @Author: yzh
 * @Date:   2023-03-02
 * @Version: V1.0
 */
@Service
public class StMetricServiceImpl extends ServiceImpl<StMetricMapper, StMetric> implements IStMetricService {
    private static final String METRIC_NO_PRE = "ZB";
    private static final  int NO_SIZE = 5;
    @Autowired
    private IStCaMainMetricService iStCaMainMetricService;

    private String metricNo(){
        QueryWrapper<StMetric> wapper = new QueryWrapper();
        wapper.orderByDesc("metric_no");
        wapper.last("limit 1");
        StMetric noUpper = super.baseMapper.selectOne(wapper);
        if(noUpper == null) {
            return METRIC_NO_PRE+StringUtils.leftPad("1",NO_SIZE,"0");
        }else{
            // 如果不为空+1
            int no  = Integer.valueOf(noUpper.getMetricNo().replace(METRIC_NO_PRE,""))+1;
            String str = ""+no;
            return  METRIC_NO_PRE+StringUtils.leftPad(str,NO_SIZE,"0");
        }
    }

    private void checkName(StMetric entity, boolean isSave){
        if(entity==null){
            return;
        }
        QueryWrapper<StMetric> wapper = new QueryWrapper<>();
        wapper.eq("METRIC_NAME",entity.getMetricName());
        if(!isSave){
            wapper.ne("METRIC_NO",entity.getMetricNo());
        }
        long count = super.count(wapper);
        if(count>0){
            throw new JeecgBootException("指标名称已存在");
        }
    }

    @Override
    public boolean save(StMetric entity) {
        checkName(entity,true);
        StMetricVo stMetricVo = (StMetricVo) entity;
        StMetric stMetric = new StMetric();
        BeanUtils.copyProperties(stMetricVo,stMetric);
        String metricNo = metricNo();
        stMetric.setMetricNo(metricNo);
        stMetric.setCreatedUser(UserUtil.getUserCode());
        stMetric.setVaild(StmConstans.DEFAULT_VALID);
        stMetric.setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag);
        if(!StringUtils.isEmpty(stMetricVo.getCaNo())) {
            StCaMainMetric stCaMainMetric = new StCaMainMetric();
            stCaMainMetric.setMetricNo(metricNo);
            stCaMainMetric.setCaNo(stMetricVo.getCaNo());
            iStCaMainMetricService.save(stCaMainMetric);
        }
        return super.save(stMetric);
    }

    @Override
    public boolean updateById(StMetric entity){
        checkName(entity,false);
        entity.setUpdatedUser(UserUtil.getUserCode());
        return super.updateById(entity);
    }


    @Override
    public IPage<StMetric> defPage(StMetric stMetric, Integer pageNo, Integer pageSize, Map<String, String[]> parameterMap) {
        QueryWrapper<StMetric> queryWrapper = QueryGenerator.initQueryWrapper(stMetric, parameterMap);
        String [] caNo = parameterMap.get("caNo");
        if(caNo!=null && caNo.length == 1 && StringUtils.isNotEmpty(caNo[0])){
            QueryWrapper<StCaMainMetric> stCaMainMetricQueryWrapper = new QueryWrapper<>();
            stCaMainMetricQueryWrapper.eq("CA_NO",caNo[0]);
            List<StCaMainMetric> stCaMainMetrics = iStCaMainMetricService.list(stCaMainMetricQueryWrapper);
            if(CollectionUtils.isEmpty(stCaMainMetrics)){
                queryWrapper.eq("METRIC_NO","NOEXIST");
            }else{
                List<String> metricNos =  stCaMainMetrics.stream().map(StCaMainMetric::getMetricNo).collect(Collectors.toList());
                queryWrapper.in("METRIC_NO",metricNos);
            }
        }
        Page<StMetric> page = new Page<StMetric>(pageNo, pageSize);
        IPage<StMetric> pageList = super.page(page, queryWrapper);
        return pageList;
    }

    private void checkRef(StCaMainMetric stCaMainMetric){
        QueryWrapper<StCaMainMetric> stCaMainMetricQueryWrapper = new QueryWrapper<>();
        stCaMainMetricQueryWrapper.eq("CA_NO",stCaMainMetric.getCaNo());
        stCaMainMetricQueryWrapper.eq("METRIC_NO",stCaMainMetric.getMetricNo());
        long count = iStCaMainMetricService.count(stCaMainMetricQueryWrapper);
        if(count>0){
            throw new JeecgBootException("控制活动和指标关系已存在请重新选择");
        }

    }

    @Override
    public void saveRef(StCaMainMetricVo stCaMainMetricVo) {
        if(!StringUtils.isEmpty(stCaMainMetricVo.getCaNo())
         && !CollectionUtils.isEmpty(stCaMainMetricVo.getMetricNos())){
            for(String metricsNo:stCaMainMetricVo.getMetricNos()){
                StCaMainMetric stCaMainMetric = new StCaMainMetric();
                stCaMainMetric.setMetricNo(metricsNo);
                stCaMainMetric.setCaNo(stCaMainMetricVo.getCaNo());
                checkRef(stCaMainMetric);
                iStCaMainMetricService.save(stCaMainMetric);
            }
        }else{
            throw new JeecgBootException("没有指标编号或者控制活动编号");
        }
    }

    @Override
    public void removeRefById(Serializable id,String caNo) {
        StMetric stMetric = super.getById(id);
        iStCaMainMetricService.removeByMetricCaNo(stMetric.getMetricNo(),caNo);
    }

    @Override
    public boolean removeById(Serializable id) {
        StMetric stMetric = super.getById(id);
        iStCaMainMetricService.removeByMetricNo(stMetric.getMetricNo());
        return super.removeById(id);
    }
}
