
package com.yunzhupaas.bsc.service.impl;

import com.yunzhupaas.bsc.entity.*;
import com.yunzhupaas.bsc.mapper.ProjectTypeMapper;
import com.yunzhupaas.bsc.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.bsc.model.projecttype.*;
import org.springframework.stereotype.Service;
import com.yunzhupaas.base.service.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.yunzhupaas.util.GeneraterSwapUtil;
import java.sql.Connection;
import java.sql.SQLException;
import lombok.Cleanup;
import com.yunzhupaas.database.plugins.DynamicSourceGeneratorInterface;
import com.yunzhupaas.database.util.DynamicDataSourceUtil;
import org.apache.commons.collections4.CollectionUtils;
import com.yunzhupaas.i18n.util.I18nUtil;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.constant.MsgCode;
import java.math.BigDecimal;
import cn.hutool.core.util.ObjectUtil;
import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.yunzhupaas.base.model.ColumnDataModel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yunzhupaas.model.QueryAllModel;
import java.text.SimpleDateFormat;
import com.yunzhupaas.util.*;
import java.util.*;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.permission.entity.UserEntity;
import com.github.pagehelper.PageHelper;
/**
 *
 * 项目分类
 * 版本： V5.2.7
 * 版权： Copyright @ 2025  深圳市乐程软件有限公司版权所有
 * 作者： 深圳市乐程软件有限公司
 * 日期： 2026-05-19
 */
@Service
public class ProjectTypeServiceImpl extends SuperServiceImpl<ProjectTypeMapper, ProjectTypeEntity> implements ProjectTypeService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;

    @Autowired
    private  ProjectTypeMapper projectTypeMapper;
    @Override
    public List<ProjectTypeEntity> getList(ProjectTypePagination projectTypePagination){
        return getTypeList(projectTypePagination,projectTypePagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<ProjectTypeEntity> getTypeList(ProjectTypePagination projectTypePagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("bc_project_type",ProjectTypeEntity.class);
        tableClassMap.put("bc_project_expbudget_temp",ProjectExpbudgetTempEntity.class);

        MPJLambdaWrapper<ProjectTypeEntity> wrapper = JoinWrappers
                .lambda("bc_project_type",ProjectTypeEntity.class)
                .selectAssociation(ProjectExpbudgetTempEntity.class,ProjectTypeEntity::getProjectExpbudgetTemp)
                .leftJoin(ProjectExpbudgetTempEntity.class,"bc_project_expbudget_temp",ProjectExpbudgetTempEntity::getProjectTypeId,ProjectTypeEntity::getProjectTypeId)
                .selectAll(ProjectTypeEntity.class);
        MPJLambdaWrapper<ProjectTypeEntity> wrapper2 = JoinWrappers
                .lambda("bc_project_type",ProjectTypeEntity.class)
                .leftJoin(ProjectExpbudgetTempEntity.class,"bc_project_expbudget_temp",ProjectExpbudgetTempEntity::getProjectTypeId,ProjectTypeEntity::getProjectTypeId)
                .distinct().select(ProjectTypeEntity::getProjectTypeId);

        QueryAllModel queryAllModel = new QueryAllModel();
        queryAllModel.setWrapper(wrapper);
        queryAllModel.setClassMap(tableClassMap);
        queryAllModel.setDbLink(ProjectTypeConstant.DBLINKID);
        //数据过滤
        boolean isPc = ServletUtil.getHeader("yunzhupaas-origin").equals("pc");
        String columnData = !isPc ? ProjectTypeConstant.getAppColumnData() : ProjectTypeConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());
        queryAllModel.setRuleJson(ruleJson);
        //高级查询
        boolean hasSuperQuery =  true;
        if (hasSuperQuery) {
            queryAllModel.setSuperJson(projectTypePagination.getSuperQueryJson());
        }
        //数据权限
        boolean pcPermission = true;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            queryAllModel.setModuleId(projectTypePagination.getMenuId());
        }
        if (!isPc && appPermission) {
            queryAllModel.setModuleId(projectTypePagination.getMenuId());
        }
        //拼接复杂条件
        wrapper = generaterSwapUtil.getConditionAllTable(queryAllModel);
        if(wrapper == null) return new ArrayList<>();
        queryAllModel.setWrapper(wrapper2);
        wrapper2 = generaterSwapUtil.getConditionAllTable(queryAllModel);
        //其他条件拼接
        otherConditions(projectTypePagination, wrapper, isPc);
        otherConditions(projectTypePagination, wrapper2, isPc);

        //分组和树形生成这个代码,pc端返回全部数据  !"2".equals(dataType)导出选中数据
        if(isPc && !"2".equals(dataType)){
            dataType = "1";
        }
        if("0".equals(dataType)){
            com.github.pagehelper.Page<Object> objects = PageHelper.startPage((int) projectTypePagination.getCurrentPage(), (int) projectTypePagination.getPageSize(), true);
            List<ProjectTypeEntity> userIPage = this.selectJoinList(ProjectTypeEntity.class, wrapper2);
            List<Object> collect = userIPage.stream().map(t -> t.getProjectTypeId()).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(collect)){
                wrapper.in(ProjectTypeEntity::getProjectTypeId,collect);
            }
            List<ProjectTypeEntity> result = this.selectJoinList(ProjectTypeEntity.class, wrapper);
            return projectTypePagination.setData(result,objects.getTotal());
        }else{
            List<ProjectTypeEntity> list = this.selectJoinList(ProjectTypeEntity.class, wrapper);
            if("2".equals(dataType)){
                List<Object> selectIds = Arrays.asList(projectTypePagination.getSelectIds());
                return list.stream().filter(t -> selectIds.contains(t.getProjectTypeId())).collect(Collectors.toList());
            }else{
                return list;
            }
        }

    }

    /**
    * 其他条件拼接
    */
    private void otherConditions(ProjectTypePagination projectTypePagination, MPJLambdaWrapper<ProjectTypeEntity> wrapper, boolean isPc) {
        String databaseName;
        try {
            @Cleanup Connection cnn = DynamicDataSourceUtil.getCurrentConnection();
            databaseName = cnn.getMetaData().getDatabaseProductName().trim();
        } catch (SQLException e) {
            throw new DataException(e.getMessage());
        }
        wrapper.isNull(ProjectTypeEntity::getFlowId);
        //关键词
        if(ObjectUtil.isNotEmpty(projectTypePagination.getYunzhupaasKeyword())){
        }
        //普通查询
        if(isPc){
            if(ObjectUtil.isNotEmpty(projectTypePagination.getProjectTypeName())){
                String value = projectTypePagination.getProjectTypeName() instanceof List ?
                    JsonUtil.getObjectToString(projectTypePagination.getProjectTypeName()) :
                    String.valueOf(projectTypePagination.getProjectTypeName());
                wrapper.like(ProjectTypeEntity::getProjectTypeName,value);
            }

        }
        //排序
        if(StringUtil.isEmpty(projectTypePagination.getSidx())){
                wrapper.orderByDesc(ProjectTypeEntity::getProjectTypeId);
        }else{
            try {
                String[] split = projectTypePagination.getSidx().split(",");
                for(String sidx:split){
                ProjectTypeEntity projectTypeEntity = new ProjectTypeEntity();
                    String oderTableField = projectTypeEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = projectTypeEntity.getClass().getDeclaredField(sidxField);
                        declaredField.setAccessible(true);
                        sidxField = declaredField.getAnnotation(TableField.class).value();
                    }catch (Exception e){
                    }
                    String finalOderTableField = oderTableField;
                    String finalSidxField = sidxField;
                    Object select = wrapper.getSelectColumns().stream().filter(t -> Objects.equals(finalOderTableField, t.getTableAlias())
                            && Objects.equals(finalSidxField, t.getColumn())).findFirst().orElse(null);
                    oderTableField = oderTableField + "." + sidxField;
                    if (select == null) {
                        wrapper.select(oderTableField);
                    }
                    if (descFlag) {
                        wrapper.orderByDesc(oderTableField);
                    } else {
                        wrapper.orderByAsc(oderTableField);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public ProjectTypeEntity getInfo(String projecttypeid){
        MPJLambdaWrapper<ProjectTypeEntity> wrapper = JoinWrappers
                .lambda("bc_project_type",ProjectTypeEntity.class)
                .selectAssociation(ProjectExpbudgetTempEntity.class,ProjectTypeEntity::getProjectExpbudgetTemp)
                .leftJoin(ProjectExpbudgetTempEntity.class,"bc_project_expbudget_temp",ProjectExpbudgetTempEntity::getProjectTypeId,ProjectTypeEntity::getProjectTypeId)
                .selectAll(ProjectTypeEntity.class);
        wrapper.and(
            t->t.eq(ProjectTypeEntity::getProjectTypeId, projecttypeid )
            .or().eq(ProjectTypeEntity::getFlowTaskId, projecttypeid)
        );
        return this.selectJoinOne(ProjectTypeEntity.class,wrapper);
    }
    @Override
    public void create(ProjectTypeEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String projecttypeid, ProjectTypeEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ProjectTypeEntity entity){
        if(entity!=null){
            this.removeById(entity.getProjectTypeId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(ProjectTypeForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getProjectTypeId()) && !form.getProjectTypeId().equals("0");
        Object id= null;
        String countRecover = "";
        String fieldTipName = "";
        String canNotNull = I18nUtil.getMessageStr("sys.validate.textRequiredSuffix", "不能为空");
        String canNotRepeated = I18nUtil.getMessageStr("EXIST103", "不能重复");
        if (isUp){
            id = form.getProjectTypeId();
        }
        //主表字段验证
            fieldTipName =  "项目分类编码"; 
            fieldTipName =  "项目分类名称"; 
            fieldTipName =  "上级项目分类"; 
            fieldTipName =  "顺序号"; 
            fieldTipName =  "备注"; 
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param projectTypeForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(ProjectTypeForm projectTypeForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        projectTypeForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(ProjectTypeConstant.getFormData(),projectTypeForm,ProjectTypeConstant.TABLERENAMES),ProjectTypeForm.class);
        ProjectTypeEntity entity = JsonUtil.getJsonToBean(projectTypeForm, ProjectTypeEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        if(isSave){
            entity.setFlowTaskId(mainUuid);
            entity.setProjectTypeId(mainUuid);
        } else {
        }
        boolean b = this.saveOrUpdate(entity);
    ProjectTypeEntity info = this.getInfo(mainUuid);
    if (info == null) throw new RuntimeException(MsgCode.FA001.get());

    }

    @Override
    public List<Map<String, Object>> getTreeList() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<ProjectTypeEntity> list = projectTypeMapper.selectList(null);
        for (ProjectTypeEntity node : list) {
            if (node.getPid() == null || node.getPid().isEmpty() || "0".equals(node.getPid())) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectTypeId", node.getProjectTypeId());
                map.put("projectTypeName", node.getProjectTypeName());
                map.put("children", getChildrenSimple(list, node.getProjectTypeId()));
                result.add(map);
            }
        }

        return result;
    }
    private List<Map<String, Object>> getChildrenSimple(List<ProjectTypeEntity> list, String parentId) {
        List<Map<String, Object>> children = new ArrayList<>();
        for (ProjectTypeEntity node : list) {
            if (parentId.equals(node.getPid())) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectTypeId", node.getProjectTypeId());
                map.put("projectTypeName", node.getProjectTypeName());
                map.put("children", getChildrenSimple(list, node.getProjectTypeId()));
                children.add(map);
            }
        }
        return children;
    }

}
