package org.stm.inner.control.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 org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.stm.act.check.entity.StCaMainCheck;
import org.stm.act.main.entity.StCaMain;
import org.stm.act.main.service.IStCaMainService;
import org.stm.base.domain.entity.StDomain;
import org.stm.base.domain.service.IStDomainService;
import org.stm.base.domain.vo.StDomainVo;
import org.stm.best.practices.entity.StBestPractices;
import org.stm.best.practices.vo.StBestPracticesVo;
import org.stm.compliane.info.constant.ComplianeClass;
import org.stm.compliane.info.entity.StComplianeInfo;
import org.stm.inner.control.entity.StInnerControl;
import org.stm.inner.control.mapper.StInnerControlMapper;
import org.stm.inner.control.service.IStInnerControlService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.stm.inner.control.vo.StInnerControlVo;
import org.stm.inner.order.entity.StInnerControlOrder;
import org.stm.utils.QueryCaManParamsUtlis;
import org.stm.utils.StmConstans;
import org.stm.utils.UserUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 内控策略表
 * @Author: yzh
 * @Date:   2023-03-05
 * @Version: V1.0
 */
@Service
public class StInnerControlServiceImpl extends ServiceImpl<StInnerControlMapper, StInnerControl> implements IStInnerControlService {

    private static final String pre = "CL";

    @Autowired
    private IStCaMainService iStCaMainService;
    @Autowired
    private IStDomainService iStDomainService;
    private String bizNo(){
        QueryWrapper<StInnerControl> wapper = new QueryWrapper();
        wapper.orderByDesc("STRATEGY_NO");
        wapper.last("limit 1");
        StInnerControl noUpper = super.baseMapper.selectOne(wapper);
        if(noUpper == null) {
            return pre+ StringUtils.leftPad("1",ComplianeClass.NO_LENGTH,"0");
        }else{
            // 如果不为空+1
            int no  = Integer.valueOf(noUpper.getStrategyNo().replace(pre,""))+1;
            String str = ""+no;
            return  pre+StringUtils.leftPad(str,ComplianeClass.NO_LENGTH,"0");
        }
    }
    private void checkName(StInnerControl entity, boolean isSave){
        if(entity==null){
            return;
        }
        QueryWrapper<StInnerControl> wapper = new QueryWrapper<>();
        wapper.eq("INNER_CONTROL_STRATEGY",entity.getInnerControlStrategy());
        if(!isSave){
            wapper.ne("ID",entity.getId());
        }
        long count = super.count(wapper);
        if(count>0){
            throw new JeecgBootException("内控策略已存在");
        }
    }
    @Override
    public boolean save(StInnerControl entity) {
        checkName(entity,true);
        String no = bizNo();
        entity.setStrategyNo(no);
        entity.setCreatedUser(UserUtil.getUserCode());
        entity.setValid(StmConstans.DEFAULT_VALID);
        entity.setApproveFlag(StmConstans.DEFAULT_APPROVE_Flag);
        return super.save(entity);
    }

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

    @Override
    public <E extends IPage<StInnerControl>> E page(E page, Wrapper<StInnerControl> queryWrapper) {
        IPage<StInnerControl> iPage =  super.page(page, queryWrapper);
        List<StInnerControl> data = iPage.getRecords();
        if(CollectionUtils.isEmpty(data)){
            return (E) iPage;
        }
        List<StInnerControl> records = new ArrayList<>();
        for(StInnerControl stInnerControl:data){
            StInnerControlVo stInnerControlVo = new StInnerControlVo();
            BeanUtils.copyProperties(stInnerControl,stInnerControlVo);
            StCaMain stCaMain = iStCaMainService.queryByCaNo(stInnerControl.getCaNo());
            if(stCaMain!=null) {
                stInnerControlVo.setCaName(stCaMain.getCaName());
                StDomainVo stDomain = iStDomainService.queryEntityByCode(stCaMain.getDomainCode());
                if(stDomain!=null) {
                    stInnerControlVo.setDomainName(stDomain.getPathDomainName());
                }else{
                    stInnerControlVo.setDomainName("-");
                }
            }else{
                stInnerControlVo.setCaName("-");
                stInnerControlVo.setDomainName("-");
            }
            records.add(stInnerControlVo);
        }
        iPage.setRecords(records);
        return (E) iPage;
    }

    @Override
    public IPage<StInnerControl> defPage(StInnerControl stInnerControl, Integer pageNo, Integer pageSize, Map<String, String[]> parameterMap) {
        QueryWrapper<StInnerControl> queryWrapper = QueryGenerator.initQueryWrapper(stInnerControl, parameterMap);
        List<String> caNos = QueryCaManParamsUtlis.getCaNos(parameterMap);
        if(!CollectionUtils.isEmpty(caNos)){
            if(caNos.size()==1 && "notExist".equals(caNos.get(0))){
                return null;
            }
            queryWrapper.in("CA_NO",caNos);
        }
        Page<StInnerControl> page = new Page<StInnerControl>(pageNo, pageSize);
        return this.page(page, queryWrapper);
    }

    @Override
    public StInnerControl queryByStrategyNo(String strategyNo) {
        QueryWrapper<StInnerControl> wapper = new QueryWrapper();
        wapper.eq("STRATEGY_NO",strategyNo);
        return super.baseMapper.selectOne(wapper);
    }
}
