package com.ruoyi.ibs.tabs.service.impl;

import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.ibs.tabs.domain.dto.*;
import com.ruoyi.ibs.tabs.domain.entity.CustTabDetail;
import com.ruoyi.ibs.tabs.domain.entity.CustTabListInfo;
import com.ruoyi.ibs.tabs.domain.vo.*;
import com.ruoyi.ibs.tabs.enums.IndexT1lThresholdEnum;
import com.ruoyi.ibs.tabs.enums.IndexThresholdTypeEnum;
import com.ruoyi.ibs.tabs.mapper.CustTabListInfoMapper;
import com.ruoyi.ibs.tabs.service.ICustTabDetailService;
import com.ruoyi.ibs.tabs.service.ICustTabListInfoService;
//import javafx.util.Builder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;


/**
 * 指标层级关系Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-30
 */
@Service
@Transactional
public class CustTabListInfoServiceImpl implements ICustTabListInfoService
{
    @Autowired
    private CustTabListInfoMapper custTabListInfoMapper;



    @Autowired
    private ICustTabDetailService iCustTabDetailService;


    @Override
    public List<CustTabGroupVo> selectTabPotListInfoByTabType(Long tabTyep) {

        CustTabListInfo custTabListInfo = new CustTabListInfo();
        custTabListInfo.setParentId(tabTyep);
        custTabListInfo.setLoginId(getUsername());
        List<CustTabGroupVo> custTabListInfoList = custTabListInfoMapper.selectTabPotListInfoByTabType(custTabListInfo);
        return custTabListInfoList;
    }




    /**
     * 查询指标层级关系
     * 
     * @param id 指标层级关系主键
     * @return 指标层级关系
     */
    @Override
    public CustTabIdDetailVO selectCustTabListInfoById(Long id)
    {
        CustTabListInfo custTabListInfoBuilder = new CustTabListInfo();
        custTabListInfoBuilder.setParentId(id);

        List<CustTabListInfo> infos = custTabListInfoMapper.selectCustTabListInfoList(custTabListInfoBuilder);
        CustTabListInfo custTabListInfo = custTabListInfoMapper.selectCustTabListInfoById(id);

        List<CustTabListInfo> custTabListInfos = infos.stream().filter(e -> "0".equals(e.getTabEnum())).collect(Collectors.toList());

        if(custTabListInfos.size() > 0 ){
            new ServerException("指标信息查询输入有误");
        }

        // 查询指标枚举值、枚举值中各口径设置情况
        List<CustTabEnumVo> enums = infos.stream().map(e -> new CustTabEnumVo(e.getId(), e.getTabName(), iCustTabDetailService.selectCustTabDetailByTabId(e.getId()),e.getTreeList())).collect(Collectors.toList());

        //  查询历史修改记录

        CustTabListInfo custTabListInfoSource = custTabListInfoMapper.selectCustTabListInfoById(id);

        List<CustTabEditHisVo> custTabEditHisVos = custTabListInfoMapper.selectCustTabListInfoHis(custTabListInfoSource.getTabId(),SecurityUtils.getHeadId()  );
        for (int i = 0; i < custTabEditHisVos.size(); i++) {
            if (custTabEditHisVos.get(0)!=null){
                custTabEditHisVos.get(0).setUpdateType("创建");
            }
            if (i!=0&&custTabEditHisVos.get(i)!=null){
                custTabEditHisVos.get(i).setUpdateType("修改");
            }
        }
        if (custTabListInfo.getEndDate()!=null){
            Date now = new Date();
            if (now.after(custTabListInfo.getEndDate())){
                CustTabEditHisVo custTabEditHisVo = new CustTabEditHisVo();
                custTabEditHisVo.setUpdateTime(custTabListInfo.getEndDate());
                custTabEditHisVo.setUpdateType("失效");
                custTabEditHisVos.add(custTabEditHisVo);
            }
        }

        return CustTabIdDetailVO.builder().parentId(id).tabEnums(enums).custTabEditHis(custTabEditHisVos).computeType(custTabListInfo.getComputType()).endDate(custTabListInfo.getEndDate()).build();
    }

    @Override
    public List<PotListVo> listPot(String tabThresholdType) {
        CustTabDetail custTabDetail =  new CustTabDetail();
        custTabDetail.setTabId((long) -999);
        custTabDetail.setTabThresholdType(tabThresholdType);
        return iCustTabDetailService.selectCustTabDetailList(custTabDetail).stream().map(e-> new PotListVo(e.getPotId(),e.getPotName(),e.getTabThresholdType(),e.getEnumVal())).collect(Collectors.toList());
    }

    @Override
    public List<TopTabVo> selectTopTabList(String tabName,String custType) {

        CustTabListInfo custTabListInfo =  new CustTabListInfo();
        custTabListInfo.setTabEnum("-1");
        custTabListInfo.setCustType(custType);
        custTabListInfo.setParentId((long) -1);
        List<CustTabListInfo> infos = this.selectCustTabListInfoList(custTabListInfo);


        if(StringUtils.isNotEmpty(infos)) {
            return infos.stream().map(e -> {
                CustTabListInfo custTabListInfoe = new CustTabListInfo();
                custTabListInfoe.setTabEnum("-1");
                custTabListInfoe.setCustType(custType);
                custTabListInfoe.setParentId(e.getId());
                custTabListInfoe.setTabName(tabName);

                return  new TopTabVo(e.getTabName(), e.getId(), e.getParentId(),
                                this.selectCustTabListInfoList(custTabListInfoe).stream().map(e2 -> new TopTabVo(e2.getTabName(), e2.getId(), e2.getParentId())).collect(Collectors.toList()));
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<CustTabListVo> listTab(ListTabDTO listTabDTO) {

        CustTabListInfo custTabListInfo = new CustTabListInfo();
        BeanUtils.copyProperties(listTabDTO, custTabListInfo);
        custTabListInfo.setLoginId(getUsername());
        List<CustTabListInfo> custTabListInfoList = SpringUtils.getAopProxy(this).selectCustTabListInfoList(custTabListInfo);
        List<CustTabListVo> custTabListVos = custTabListInfoList.stream().map(e -> {
            CustTabListVo custTabListVo = BeanUtils.instantiateClass(CustTabListVo.class);
            BeanUtils.copyProperties(e,custTabListVo );
            return custTabListVo;
        }).collect(Collectors.toList());

        Date today = new Date();
        List<CustTabListVo> sortCustTabListVos = custTabListVos.stream()
                .sorted(Comparator.comparing((CustTabListVo vo) -> {
                            return vo.getEndDate() != null && vo.getEndDate().compareTo(today) >= 0;
                        }).reversed()
                        .thenComparing(CustTabListVo::getUpdateTime, Comparator.reverseOrder()))
                .collect(Collectors.toList());
        return sortCustTabListVos;
    }

    /**
     * 查询指标层级关系列表
     * 
     * @param custTabListInfo 指标层级关系
     * @return 指标层级关系
     */
    @Override
//    @DataScope(deptAlias = "ctli", userAlias = "create_by",deptIdAlias = "ctli",userIdAlias = "create_dept")
    public List<CustTabListInfo> selectCustTabListInfoList(CustTabListInfo custTabListInfo)
    {
        return custTabListInfoMapper.selectCustTabListInfoList(custTabListInfo);
    }

    /**
     * 新增指标层级关系
     * 
     * @param tabAddDTO 指标层级关系
     * @return 结果
     */
    @Override
    public int insertCustTabListInfo(TabAddDTO tabAddDTO) throws ServerException {

        CustTabListInfo custTabListInfo1 = new CustTabListInfo();
        custTabListInfo1.setTabId(tabAddDTO.getTabId());
        if( custTabListInfoMapper.selectCustTabListInfoList (custTabListInfo1).size() > 0 ){
           throw new ServerException("指标英文名称重复");
       }
        custTabListInfo1.setTabId(null);
        custTabListInfo1.setTabName(tabAddDTO.getTabName());
        if( custTabListInfoMapper.selectCustTabListInfoList (custTabListInfo1).size() > 0 ){
            throw new ServerException("指标中文名重复");
        }
        //  1. 新增大指标
        CustTabListInfo custTabListInfo = new CustTabListInfo();
        custTabListInfo.setTabName(tabAddDTO.getTabName());
        custTabListInfo.setTabId(tabAddDTO.getTabId());
        custTabListInfo.setParentId(tabAddDTO.getParentId());
        custTabListInfo.setComputType(tabAddDTO.getComputType());
        custTabListInfo.setEndDate(tabAddDTO.getEndTime());
        custTabListInfo.setAuthType(tabAddDTO.getAuthType());
        custTabListInfo.setTabEnum("0");
        custTabListInfo.setCustType(tabAddDTO.getCustType());
        custTabListInfo.setAuthUser(tabAddDTO.getAuthUser());
        custTabListInfo.setRemark(tabAddDTO.getRemark());
        custTabListInfoGetInfo(custTabListInfo);
        custTabListInfo.setTabThresholdType(tabAddDTO.getTabThresholdType());
        custTabListInfoMapper.insertCustTabListInfo(custTabListInfo);

        CustTabListInfo custTabListInfoForSecrch = new CustTabListInfo();
        custTabListInfoForSecrch.setTabId(tabAddDTO.getTabId());
        CustTabListInfo infoTab = custTabListInfoMapper.selectCustTabListInfoList(custTabListInfoForSecrch).get(0);

        //增加小指标
        for (TabPotAddDTO tabPotAddDTO : tabAddDTO.getTabPotAddDTOS()) {
            CustTabListInfo custTabDetailPot =  new CustTabListInfo();
            custTabDetailPot.setParentId(infoTab.getId());
            custTabDetailPot.setTabName(tabPotAddDTO.getTabName());
            custTabDetailPot.setTabEnum("1");
            custTabDetailPot.setPotRelation(tabPotAddDTO.getPotRelation());
            custTabDetailPot.setTreeList(tabPotAddDTO.getTreeList());
            custTabListInfoGetInfo(custTabDetailPot);
            // 计算逻辑拼出
            custTabDetailPot.setPotSql( SpringUtils.getAopProxy(this).getIndexRelaitonSql(tabPotAddDTO));
            custTabListInfoMapper.insertCustTabListInfo(custTabDetailPot);

            CustTabListInfo custPotListInfoForSecrch = new CustTabListInfo();
            custPotListInfoForSecrch.setParentId(infoTab.getId());
            custPotListInfoForSecrch.setTabName(tabPotAddDTO.getTabName());
            custPotListInfoForSecrch.setTabEnum("1");

            CustTabListInfo infoPotTab = custTabListInfoMapper.selectCustTabListInfoList(custPotListInfoForSecrch).get(0);
            // 增加口径明细
            for (PotDetalAddDTO potDetalAddDTO : tabPotAddDTO.getPotDetails() ){
                CustTabDetail custTabDetail = new CustTabDetail();

                BeanUtils.copyProperties(potDetalAddDTO, custTabDetail);
                custTabDetail.setTabId(infoPotTab.getId());
                custTabDetail.setCreateBy(getUsername());
                custTabDetail.setUpdateBy(getUsername());
                iCustTabDetailService.insertCustTabDetail(custTabDetail);
            }

        }
        return 1;
    }

    /**
     * 修改指标层级关系
     * 
     * @param tabEditDTO 指标层级关系
     * @return 结果
     */
    @Override
    public int updateCustTabListInfo(TabEditDTO tabEditDTO) throws ServerException {
        // 先删除  在新增
        SpringUtils.getAopProxy(this).deleteCustTabListInfoById(tabEditDTO.getId());
        SpringUtils.getAopProxy(this).insertCustTabListInfo(tabEditDTO.getTabAddDTO());
        return 1;
    }

    /**
     * 批量删除指标层级关系
     * 
     * @param ids 需要删除的指标层级关系主键
     * @return 结果
     */
    @Override
    public int deleteCustTabListInfoByIds(Long[] ids)
    {

        return custTabListInfoMapper.deleteCustTabListInfoByIds(ids);
    }

    /**
     * 删除指标层级关系信息
     * 
     * @param id 指标层级关系主键
     * @return 结果
     */
    @Override
    public int deleteCustTabListInfoById(Long id) throws ServerException {


        if(SpringUtils.getAopProxy(this).listTab(ListTabDTO.builder().id(id).build()).size()  == 0){
            throw  new ServerException("该标签不存在");
        };
        return custTabListInfoMapper.deleteCustTabListInfoById(id, getUsername()) ;
    }

    private void  custTabListInfoGetInfo(CustTabListInfo custTabListInfo) {
        custTabListInfo.setCreateBy(getUsername());
        custTabListInfo.setUpdateBy(getUsername());
        custTabListInfo.setBelongOrg3(SecurityUtils.getHeadId());
    }


    @Override
    public String getIndexRelaitonSql(TabPotAddDTO tabPotAddDTO) {
        String indexRelationCpt = tabPotAddDTO.getPotRelation();
        for (PotDetalAddDTO indexRelationInfoDTO : tabPotAddDTO.getPotDetails()) {
            String sql = "";
            if (IndexThresholdTypeEnum.T1.getType().equals(indexRelationInfoDTO.getTabThresholdType())) {
                sql = IndexT1lThresholdEnum.getSql(indexRelationInfoDTO.getTabThresholdRule(), indexRelationInfoDTO.getTabThreshold(), indexRelationInfoDTO.getPotId());
            }
            if (IndexThresholdTypeEnum.T2.getType().equals(indexRelationInfoDTO.getTabThresholdType())) {
                sql = String.format(" %s = %s ", indexRelationInfoDTO.getPotId(), indexRelationInfoDTO.getBooleanVal());
            }
            if (IndexThresholdTypeEnum.T3.getType().equals(indexRelationInfoDTO.getTabThresholdType())&&"0".equals(indexRelationInfoDTO.getIsUnEquals())) {
                sql = String.format(" %s = '%s' ", indexRelationInfoDTO.getPotId(), indexRelationInfoDTO.getEnumVal());
            }
            if (IndexThresholdTypeEnum.T3.getType().equals(indexRelationInfoDTO.getTabThresholdType())&&"1".equals(indexRelationInfoDTO.getIsUnEquals())) {
                sql = String.format(" %s <> '%s' ", indexRelationInfoDTO.getPotId(), indexRelationInfoDTO.getEnumVal());
            }
            indexRelationCpt = indexRelationCpt.replaceFirst(String.format("\\[%s\\]", indexRelationInfoDTO.getPotId()), sql);
        }
        return indexRelationCpt;
    }

    @Override
    public int isStart(Long id, String status) {
        CustTabListInfo custTabListInfo = new CustTabListInfo();
        custTabListInfo.setId(id);
        custTabListInfo.setIsStart(status);
        CustTabListInfo custTabListInfo1 = new CustTabListInfo();
        custTabListInfo1.setParentId(id);
        //查询出子标签，同步更新状态
        List<CustTabListInfo> custTabListInfoList = custTabListInfoMapper.selectCustTabListInfoList(custTabListInfo1);
        if (custTabListInfoList!=null&&custTabListInfoList.size()>0){
            for (CustTabListInfo custTabListInfo2 : custTabListInfoList) {
                custTabListInfo2.setIsStart(status);
                custTabListInfoMapper.updateCustTabListInfo(custTabListInfo2);
            }
        }
        return custTabListInfoMapper.updateCustTabListInfo(custTabListInfo);
    }
}
