package com.hs.api.service.Impl;

import com.hs.api.common.enums.BudgetType;
import com.hs.api.common.enums.ProjectType;
import com.hs.api.common.enums.StateType;
import com.hs.api.common.enums.TypeState;
import com.hs.api.mapper.*;
import com.hs.api.model.DicOrg;
import com.hs.api.model.SerPageValueConfig;
import com.hs.api.model.SerProjValue;
import com.hs.api.model.SerProjValueSz;
import com.hs.api.model.reqmodel.AddBudgetValue;
import com.hs.api.model.reqmodel.BudgetValue;
import com.hs.api.model.respmodel.*;
import com.hs.api.service.SerProjValueService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SerProjValueServiceImpl implements SerProjValueService {
    @Resource
    private SerProjMapper serProjMapper;
    @Resource
    private SerProjValueMapper serProjValueMapper;
    @Resource
    private SerPageProjValueMapper pageProjValueMapper;
    @Resource
    private SerPageValueConfigMapper pageValueConfigMapper;
    @Resource
    private DicOrgMapper dicOrgMapper;
    @Resource
    private SerProjValueSzMapper projValueSzMapper;

    //查询项目数值
    @Override
    public Object getValue(Integer projectType, Integer date, String deptCode, Long userId) throws Throwable {
        List<DicOrg> orgList = dicOrgMapper.selectByUser(userId);
        String orgCode = orgList != null && orgList.size() > 0 ? orgList.get(0).getOrgCode() : null;

        List<ProjectValue> result = new ArrayList<>();
        List<Map<String, Object>> enumList = TypeState.all();
        if (enumList != null && enumList.size() > 0) {
            ProjectValue projectValue = null;
            List<ProjectInfo> projectInfo = null;
            List<SerProjValueResp> values = null;
            List<SerProjValueResp> resultValues = null;
            SerProjValueSz valueSz = null;
            for (Map<String, Object> enumInfo : enumList) {
                projectValue = new ProjectValue();
                projectValue.setTypeId((Integer) enumInfo.get("value"));
                projectInfo = new ArrayList<>();
                projectInfo = serProjMapper.selectState(projectType, (Integer) enumInfo.get("value"));
                if (projectInfo != null && projectInfo.size() > 0) {
                    for (ProjectInfo projInfo : projectInfo) {
                        values = serProjValueMapper.selectValue(projectType, (Integer) enumInfo.get("value"),
                                projInfo.getExponentId(), deptCode, date, BudgetType.NOT.getValue(), orgCode);
                        if (values != null && values.size() > 0) {
                            for (SerProjValueResp value : values) {
                                valueSz = projValueSzMapper.selectByProj(value.getProjId(), date, deptCode, orgCode);
                                if (valueSz != null) {
                                    value.setSz(valueSz.getSz());
                                    value.setZxpl(valueSz.getZxpl());
                                    valueSz = null;
                                }
                            }
                        }
                        resultValues = getLevelData(values, BigDecimal.valueOf(PROJ_TOP_PARENT_ID));
                        if (resultValues != null && resultValues.size() > 0)
                            projInfo.setProjectValues(resultValues);
                    }
                }
                projectValue.setProject(projectInfo);
                result.add(projectValue);
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(Long userId, AddBudgetValue request) {
        int result = 0;
        List<DicOrg> orgList = dicOrgMapper.selectByUser(userId);
        String orgCode = orgList.get(0).getOrgCode();
        if (request != null && request.getBudgetValues() != null && request.getBudgetValues().size() > 0) {
            //先将记录插入历史表
            result = serProjValueMapper.insertToHistory(request.getDeptCode(), request.getDate(), request.getProjType(), orgCode);
            //先进行删除操作
            result = serProjValueMapper.deleteByDeptWithDate(request.getDeptCode(), request.getDate(), request.getProjType(), orgCode);
            SerProjValue info = null;
            long version = System.currentTimeMillis();
            for (BudgetValue budgetValue : request.getBudgetValues()) {
                if (budgetValue.getProjId() != null) {
                    info = new SerProjValue(budgetValue);
                    info.setDate(request.getDate());
                    info.setDeptCode(request.getDeptCode());
                    info.setCreateDate(new Date());
                    info.setState(BigDecimal.valueOf(StateType.ON.getValue()));
                    info.setVersion(String.valueOf(version));
                    info.setHoscode(orgCode);
                    serProjValueMapper.insert(info);
                }
            }
            //调用计算数值存储过程
            serProjValueMapper.updateValue(request.getDate(), orgCode);
        }
        return result > 0;
    }

    @Override
    public Object getSummary(Integer date, Integer budgetType, Long userId) {
        List<DicOrg> orgList = dicOrgMapper.selectByUser(userId);
        String orgCode = orgList.get(0).getOrgCode();

//        List<Summary> result = serProjMapper.selectDept(date, budgetType, userId);
//        if (result != null && result.size() > 0) {
//            for (Summary summary : result) {
//                summary.setProjTypeList(new ArrayList<>());
//                List<Map<String, Object>> enumList = ProjectType.all();
//                SummaryProjType projType = null;
//                List<ProjectInfo> projectInfo = null;
//                SerProjValueSz valueSz = null;
//                List<SerProjValueResp> values = null;
//                if (enumList != null && enumList.size() > 0) {
//                    for (Map<String, Object> enumInfo : enumList) {
//                        projType = new SummaryProjType();
//                        projType.setProjTypeName(String.valueOf(enumInfo.get("description")));
//                        values = serProjValueMapper.selectValue((Integer) enumInfo.get("value"), null,
//                                null, summary.getDeptCode(), date, budgetType, orgCode);
//                        projType.setProject(values);
//                        summary.getProjTypeList().add(projType);
//                    }
//                } else {
//                    summary.setProjTypeList(null);
//                }
//            }
//        }
        List<Summary> result = serProjValueMapper.selectSummary(date, orgCode);
        return result;
    }

    @Override
    public Object getData(Integer date, Integer page) {
        List<SummaryNew> result = pageProjValueMapper.selectDept(date, page);
        if (result != null && result.size() > 0) {
            for (SummaryNew summary : result) {
                List<SummaryValue> values = pageProjValueMapper.selectValue(date, page, summary.getDeptCode());
                summary.setProjTypeList(values);
            }
        }
        return result;
    }

    @Override
    public Object getDataNew(Integer page, Map<String, String> dim) {
        SerPageValueConfig pageValueConfig = pageValueConfigMapper.selectByPage(page);
        if (pageValueConfig != null) {
            Map<String, String> map = new HashMap<String, String>() {
                {
                    put("sqlStr", pageValueConfig.getSqlstr());
                    putAll(dim);
                }
            };
            List<Map<String, Object>> dataList = pageValueConfigMapper.selectSqlStr(map);
            return dataList;
        }
        return null;
    }


    private List<SerProjValueResp> getLevelData(List<SerProjValueResp> list, BigDecimal parentcode) {
        List<SerProjValueResp> resultList = new ArrayList<>();
        for (SerProjValueResp data : list) {
            if (data.getParent().equals(parentcode)) {
                List<SerProjValueResp> childList = getLevelData(list, data.getProjId());
                try {
                    if (data.getSort() != null) {
                        childList = childList.stream().sorted(Comparator.comparing(SerProjValueResp::getSort)).collect(Collectors.toList());
                    }
                    data.setChilds(childList);
                    resultList.add(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        return resultList;
    }

}
