package com.xhkjedu.sapi.service.assess;

import com.xhkjedu.sapi.mapper.assess.AssessQuotaMapper;
import com.xhkjedu.sapi.mapper.assess.AssessTemplateMapper;
import com.xhkjedu.sapi.model.assess.TAssessQuota;
import com.xhkjedu.sapi.vo.assess.AssessQuotaVo;
import com.xhkjedu.utils.N_Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ywx on 2021/11/10 10:31.
 * 评价指标
 */
@Service
public class AssessQuotaService {
    @Resource
    private AssessQuotaMapper assessQuotaMapper;
    @Resource
    private AssessTemplateMapper assessTemplateMapper;

    //添加
    public void save(TAssessQuota model) {
        model.setCreatetime(N_Utils.getSecondTimestamp());
        assessQuotaMapper.insertSelective(model);
    }

    //删除
    @Transactional
    public void deleteById(Integer id) throws Exception {
        Integer num= assessQuotaMapper.selectQuotaCount(id);
        if(num>0){
            throw new Exception("指标下包含子指标不能删除");
        }else{
            //更改指标状态
            assessQuotaMapper.updateQuotaState(10,id);

            //获取指标管理的模版，并且修改模版下指标数量
            List<Integer> temps = assessTemplateMapper.listTeimplateidsByQutoaid(id);
            if(temps!=null && temps.size()>0){
                assessTemplateMapper.updateQuotanum(temps);
            }

            //删除指标模版关联关系
            assessQuotaMapper.deleteTemplateQuota(id);
        }
    }

    //修改
    public Integer update(TAssessQuota model) {
        model.setCreatetime(N_Utils.getSecondTimestamp());
        return assessQuotaMapper.updateByPrimaryKeySelective(model);
    }


    //获取列表
    public List <AssessQuotaVo> listAll(Integer schoolid) {

        List<AssessQuotaVo> list = assessQuotaMapper.listAllQuotas(schoolid);//获取所有评价指标
        List<AssessQuotaVo> treelist = new ArrayList<>();
        if(list!=null && list.size()>0){
            for (AssessQuotaVo quotaVo: list) {

                if(quotaVo.getQuotapid()==null || quotaVo.getQuotapid()==0){
                    //说明属于一级
                    treelist.add(quotaVo);
                }
            }

            //处理第二层
            for (AssessQuotaVo quotaVo: treelist) {
                List<AssessQuotaVo> zquList = quotaVo.getChildren();
                for(AssessQuotaVo qvo : list){
                    if(quotaVo.getQuotaid().equals(qvo.getQuotapid())){
                        if(!isExistQuota(zquList,qvo.getQuotaid())){
                            zquList.add(qvo);
                        }
                    }
                }
            }
        }


        return treelist;
    }

    private boolean isExistQuota(List<AssessQuotaVo> lst,Integer quotaid){
        for(AssessQuotaVo q: lst){
            if(q.getQuotaid().equals(quotaid)){
                return true;
            }
        }
        return false;
    }


}
