package com.artfess.cqlt.manager.impl;

import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.util.BeanUtils;
import com.artfess.base.util.StringUtil;
import com.artfess.cqlt.dao.SysSubjectClassDao;
import com.artfess.cqlt.manager.SysSubjectClassManager;
import com.artfess.cqlt.manager.SysSubjectTargetManager;
import com.artfess.cqlt.model.SysSubjectClass;
import com.artfess.cqlt.model.SysSubjectTarget;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 主题/专题分类表（sys_subject_class） 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author min.wu
 * @since 2023-03-30
 */
@Service
public class SysSubjectClassManagerImpl extends BaseManagerImpl<SysSubjectClassDao, SysSubjectClass> implements SysSubjectClassManager {

    @Autowired
    private SysSubjectTargetManager subjectTargetManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(List<SysSubjectClass> list) {
        List<SysSubjectTarget> targetList = Lists.newArrayList();
        AtomicReference<Integer> count = new AtomicReference<>(0);
        list.forEach(sysSubjectClass -> {
            Integer sn = count.getAndSet(count.get() + 1);
            sysSubjectClass.setCode(sysSubjectClass.getZbCode());
            sysSubjectClass.setBusiness("hr");
            sysSubjectClass.setClassification("2");
            sysSubjectClass.setName(sysSubjectClass.getZbName());
            sysSubjectClass.setSn(sn);
            QueryWrapper<SysSubjectClass> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code_", sysSubjectClass.getParentCode());
            SysSubjectClass subjectClass = this.baseMapper.selectOne(queryWrapper);
            if(null != subjectClass) {
                sysSubjectClass.setParentId(subjectClass.getId());
            }
            this.newInsertTree(sysSubjectClass);
            SysSubjectTarget target = new SysSubjectTarget();
            target.setCode(sysSubjectClass.getCode());
            target.setTargetNameEn(sysSubjectClass.getTargetNameEn());
            target.setName(sysSubjectClass.getName());
            target.setClassification("2");
            target.setTargetLevel(sysSubjectClass.getLevel());
            target.setUnit(sysSubjectClass.getTargetUnit());
            target.setType(sysSubjectClass.getType());
            target.setBusiness(sysSubjectClass.getBusiness());
            target.setAnalyseType(sysSubjectClass.getAnalyseType());
            target.setStaLat(sysSubjectClass.getStaLat());
            target.setMemo(sysSubjectClass.getMemo());
            target.setTargetCalculation(sysSubjectClass.getTargetCalculation());
            target.setTargetDataSourceMemo(sysSubjectClass.getTargetDataSourceMemo());
            target.setSubjectId(sysSubjectClass.getId());
            if(!StringUtil.isEmpty(sysSubjectClass.getRelatedCode())) {
                target.setRelatedCode(sysSubjectClass.getRelatedCode());
            }
            if(!StringUtil.isEmpty(sysSubjectClass.getLinksType())) {
                target.setLinksType(sysSubjectClass.getLinksType());
            }

            if(!StringUtil.isEmpty(sysSubjectClass.getConversionUnit())) {
                target.setConversionUnit(sysSubjectClass.getConversionUnit());
            }
            target.setSn(sn);
            targetList.add(target);
        });

        subjectTargetManager.saveBatch(targetList);
        return true;
    }

    @Override
    public List<SysSubjectClass> getTree(String targetId) {
        Assert.hasText(targetId, "请选择指标id");
        SysSubjectClass subjectClass = this.baseMapper.getSubjectInfo(targetId);
        if(null == subjectClass) {
            return Lists.newArrayList();
        }
        List<SysSubjectClass> list = this.baseMapper.findByTargetId(subjectClass.getFullId().split("/")[1], null);
        specialHandling(subjectClass, list);
        List<SysSubjectClass> tree = BeanUtils.listToTree(list);
        return tree;
    }

    private void specialHandling(SysSubjectClass subjectClass, List<SysSubjectClass> list) {
        if(!"净资产收益率".equals(subjectClass.getName())) {
            return;
        }

        Map<String, String> relateTarget = Maps.newHashMap();
        List<String> relatedCodes = Lists.newArrayList();
        list.forEach(subject -> {
            if(StringUtil.isEmpty(subject.getRelatedCode())) {
                return;
            }
            relateTarget.put(subject.getRelatedCode(), subject.getId());
            relatedCodes.add(subject.getRelatedCode());
        });

        List<SysSubjectClass> subjectClassList = this.baseMapper.getSubjectList(relatedCodes);
        subjectClassList.forEach(subject -> {
            if(relateTarget.containsKey(subject.getCode())) {
                subject.setParentId(relateTarget.get(subject.getCode()));
            }
            list.add(subject);
        });

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveInfo(SysSubjectClass t) {
        if(t.getSn() == null){
            t.setSn(this.getNextSequence(null));
        }
        String id = this.newInsertTree(t);
        if(StringUtil.isEmpty(id)) {
            return false;
        }
        SysSubjectTarget target = new SysSubjectTarget();
        target.setCode(t.getCode());
        target.setTargetNameEn(t.getTargetNameEn());
        target.setName(t.getName());
        target.setClassification(t.getClassification());
        target.setTargetLevel(t.getLevel());
        target.setUnit(t.getTargetUnit());
        target.setType(t.getType());
        target.setBusiness(t.getBusiness());
        target.setAnalyseType(t.getAnalyseType());
        target.setStaLat(t.getStaLat());
        target.setMemo(t.getMemo());
        target.setTargetCalculation(t.getTargetCalculation());
        target.setTargetDataSourceMemo(t.getTargetDataSourceMemo());
        target.setSubjectId(t.getId());
        target.setSn(t.getSn());
        boolean save = subjectTargetManager.save(target);
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateInfo(SysSubjectClass t) {

        if(t.getSn() == null){
            t.setSn(this.getNextSequence(null));
        }
        SysSubjectClass subjectClass = this.getById(t.getId());
        String id = this.newUpdateTree(t, subjectClass.getName());
        if(StringUtil.isEmpty(id)) {
            return false;
        }
        QueryWrapper<SysSubjectTarget> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("subject_id_", id);

        SysSubjectTarget target = subjectTargetManager.getOne(queryWrapper);
        if(null == target) {
            target = new SysSubjectTarget();
        }
        target.setCode(t.getCode());
        target.setTargetNameEn(t.getTargetNameEn());
        target.setName(t.getName());
        target.setClassification(t.getClassification());
        target.setTargetLevel(t.getLevel());
        target.setUnit(t.getTargetUnit());
        target.setType(t.getType());
        target.setBusiness(t.getBusiness());
        target.setAnalyseType(t.getAnalyseType());
        target.setStaLat(t.getStaLat());
        target.setMemo(t.getMemo());
        target.setTargetCalculation(t.getTargetCalculation());
        target.setTargetDataSourceMemo(t.getTargetDataSourceMemo());
        target.setSubjectId(t.getId());
        target.setSn(t.getSn());
        boolean result = subjectTargetManager.saveOrUpdate(target);
        return result;
    }

    @Override
    public List<SysSubjectClass> getPatentTarget(String targetId) {
        Assert.hasText(targetId, "请选择指标id");
        SysSubjectClass subjectClass = this.baseMapper.getSubjectInfo(targetId);
        if(null == subjectClass) {
            return Lists.newArrayList();
        }
        String substring = subjectClass.getFullId().substring(0, subjectClass.getFullId().indexOf(subjectClass.getId(), 1) + targetId.length());
        String[] split = substring.split("/");

        List<SysSubjectClass> list = this.baseMapper.findByTargetId(null, Arrays.asList(split));
        list.forEach(sysSubjectClass -> {
            if (!StringUtils.isEmpty(sysSubjectClass.getTargetUnit()) && "欧元".equals(sysSubjectClass.getTargetUnit())) {
                sysSubjectClass.setTargetUnit("万欧");
            }
        });

        return list;
    }
}
